我有一个存储过程,该存储过程在调用时会更新一些表并最终返回一个整数值。
当我使用SQL Pro工具调用此存储过程时,我得到了预期的结果。该工具自动生成的SQL是这样的;
DECLARE @return_value int
EXEC @return_value =
dbo.GetNextReference
@c_tableName = 'prp',
@c_offYear = 'rcs14'
SELECT
'Return Value' = @return_value
但是,当我尝试使用PHP PDO驱动程序执行此操作时,似乎看不到相同的结果或任何结果。
到目前为止,这是我的代码;
$conn = $this->getPDO();
$sql = "CALL GetNextReference (? , ?)";
$stmt = $conn->prepare($sql);
$tbl = 'prp';
$year = "rcs14";
$stmt->execute([$tbl, $year]);
$results = $stmt->fetchAll();
该语句执行无任何错误,但结果以空数组的形式返回。
我想念什么?
对不起,我不允许发布实际的存储过程。
答案 0 :(得分:1)
如果我正确理解了您的问题,并且想要检查存储过程执行的结果,则可以尝试以下操作:
<?php
# Connection
$server = 'server\instance,port';
$database = 'database';
$uid = 'user';
$pwd = 'password';
# Statement
try {
$conn = new PDO("sqlsrv:server=$server;Database=$database", $uid, $pwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server" );
}
try {
$sql = "{? = call GetNextReference (? , ?)}";
# This should work also.
#$sql = "exec ? = GetNextReference (? , ?)";
$spresult = 0;
$tbl = 'prp';
$year = "rcs14";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $spresult, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
$stmt->bindParam(2, $tbl);
$stmt->bindParam(3, $year);
$stmt->execute();
# Next line for single resultset
#$results = $stmt->fetchAll();
# Multiple resultsets
do {
$results = $stmt->fetchAll();
print_r($results, true);
} while ($stmt->nextRowset());
} catch( PDOException $e ) {
die( "Error connecting to SQL Server" );
}
$stmt = null;
$conn = null;
echo 'Stored procedure return value : '.$spresult."</br>";
?>
答案 1 :(得分:0)
Op要求提供一个OUTPUT
参数的示例。它并没有具体回答他们的问题,但是,发表评论的时间太长了:
USE Sandbox;
GO
--Sample Table
CREATE TABLE dbo.TestTable (ID int IDENTITY(1,1),
SomeString varchar(20));
GO
--Sample proc
CREATE PROC dbo.TestSP @SomeString varchar(20), @ID int OUTPUT AS
--You cannot OUTPUT from an INSERT into a scalar variable, so we need a table variable
DECLARE @IDt table(ID int);
INSERT INTO dbo.TestTable (SomeString)
OUTPUT inserted.ID
INTO @IDt
SELECT @SomeString;
--Now set the scalar OUTPUT parameter to the value in the table variable
SET @ID = (SELECT ID FROM @IDt); --this works, as the SP is designed for only one row insertion
GO
DECLARE @SomeString varchar(20) = 'abc', @ID int;
EXEC dbo.TestSP @SomeString = @SomeString,
@ID = @ID OUTPUT; --ID now has the value of the IDENTITY column
--We can check here:
SELECT @ID AS OutputID;
SELECT *
FROM dbo.TestTable;
GO
--Clean up
DROP PROC dbo.TestSP;
DROP TABLE dbo.TestTable;
GO