gpt4 book ai didi

mysql将变量值添加到存储过程中的结果集

转载 作者:行者123 更新时间:2023-11-29 06:03:57 25 4
gpt4 key购买 nike

我有这个场景(工作正常):

CREATE PROCEDURE `my_sp`(
IN in_var VARCHAR(32),
OUT out_var VARCHAR(255)
)
BEGIN

DECLARE mysql_query VARCHAR(255);
DECLARE mysql_result VARCHAR(32);

SET @mysql_query = CONCAT("
CALL other_BD.other_Stored_Procedure( '",in_var,"', @other_sp_result );
");

PREPARE stmt FROM @mysql_query;
EXECUTE stmt;
SELECT @other_sp_result INTO @mysql_result;
DEALLOCATE PREPARE stmt;

IF (@mysql_result = 'OK')
THEN
SELECT * FROM my_table WHERE my_column = 'my_value' LIMIT 1;
SET out_var = 'whatever';
ELSE
SET out_var = 'NOT OK';
END IF;
END;

PHP:

$dbh = new PDO( $connection_params );

$sql = "CALL my_sp( :in_var , @outvar )";

$stmt = $dbh->prepare( $sql );
$stmt->execute( array( ':in_var' => $_POST['in_var'] ) );

//that return the result from SELECT * FROM my_table ... (from my_sp)
$result1 = $stmt->fetchAll( PDO::FETCH_ASSOC );

//That avoid error: Cannot execute queries while other unbuffered queries are active ...
$stmt->closeCursor();


$sql = "SELECT @outvar";
$query = $dbh->query( $sql );
//that return the out_var result ("whatever" for this case);
$result2 = $query->fetchAll( PDO::FETCH_ASSOC );

问题是:

有没有办法添加

SET out_var = 'whatever'

结果

SELECT * FROM my_table WHERE my_column = 'my_value' LIMIT 1;

因此只在 php 中进行一次查询以将所有数据集中在一起,例如:

col_1 => 'val', ... col_n => 'val' ... my_out_var => 'whatever_value'

最佳答案

尝试这样使用:

第一步:

create procedure proc_out(input int,out this_out int)
BEGIN

//Your code here..
set this_out = input * 2;

end


$sql ="call proc_out(10, @outvar);
select @outvar;"

或者

像这样包装你的旧存储过程:

第二步:

create procedure proc_get_outvar(input int)
begin

call proc_out(input, @outvar);
select @outvar;

end;

使用:

$sql ="call proc_out(10);"

您可以在该过程中替换您需要的数据类型:

希望对你有帮助。

关于mysql将变量值添加到存储过程中的结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43035919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com