我有一个查询将返回插入行的ID。当我将查询更改为插入到另一个表中时,我只在获取标识时出错。请记住,这是主程序的精简调试代码,因此我可以更好地排除故障。
我还应该提一下,我在sqlsrv命令周围使用自定义包装器,但它们基本相同。假设$ IC->连接是连接资源并执行连接 - > prepare返回结果stmt对象。
$upsert_custom = "
INSERT INTO CampusDictionary (attributeID, code, name, seq, active)
SELECT ?, ?, ?, 0, 1;
SELECT SCOPE_IDENTITY();"; // This query will work as expected
$upsert_custom = "
INSERT INTO Person (currentIdentityID, staffNumber, comments)
SELECT ?, ?, ?;
SELECT SCOPE_IDENTITY();"; // Using this query I get errors
$custom_stmt = $IC->connection->prepare( $upsert_custom, array( &$attributeID, &$code, &$name) );
$name = "TEST";
$attributeID = '832';
$code = '9999';
$IC->connection->begin_transaction();
$custom_stmt->execute();
$custom_stmt->next_result();
$custom_stmt->fetch();
$dictionaryID = $custom_stmt->get_field(0);
print_r("THIS WOULD CREATE ID: " . "\r\n");
var_dump($dictionaryID);
die( print_r( $IC->connection->get_errors(), true));
$IC->connection->rollback();
$custom_stmt->cancel();
仅使用第一个查询时,我得到以下输出:
php test.php
THIS WOULD CREATE ID:
string(5) "16774"
使用第二个查询时,我得到以下内容:
THIS WOULD CREATE ID:
bool(false)
Array
(
[0] => Array
(
[0] => IMSSP
[SQLSTATE] => IMSSP
[1] => -14
[code] => -14
[2] => An invalid parameter was passed to sqlsrv_get_field.
[message] => An invalid parameter was passed to sqlsrv_get_field.
)
)
我知道Person表上的AFTER INSERT和AFTER UPDATE触发器存在,但我无权查看这些触发器。根据我的阅读,SCOPE_IDENTITY不应该担心触发器。
这里发生了什么?我需要插入Person表并在一个事务中使用另一个表中的ID。我花了几个小时对此进行故障排除,但无法使其正常工作。
答案 0 :(得分:0)
经过几个小时的故障排除后,我终于在这里发布,并在10分钟内解决了......我会把这个问题留给其他遇到此问题的人。也许比我聪明的人可以解释为什么。
解决方案是添加“SET NOCOUNT ON;”到查询的开头。第二个查询的工作代码如下所示:
$upsert_custom = "
SET NOCOUNT ON;
INSERT INTO Person (currentIdentityID, staffNumber, comments)
SELECT ?, ?, ?;
SELECT SCOPE_IDENTITY();";
$custom_stmt = $IC->connection->prepare( $upsert_custom, array( &$attributeID, &$code, &$name) );
$name = "TEST";
$attributeID = '832';
$code = '9999';
$IC->connection->begin_transaction();
$custom_stmt->execute();
//$custom_stmt->next_result();//$custom_stmt->next_result();
//$dictionaryID = $custom_stmt->fetch_assoc();
$custom_stmt->fetch();
$dictionaryID = $custom_stmt->get_field(0);
print_r("THIS WOULD CREATE ID: " . "\r\n");
var_dump($dictionaryID);
//die( print_r( $IC->connection->get_errors(), true));
$IC->connection->rollback();
$custom_stmt->cancel();
输出是:
THIS WOULD CREATE ID:
string(5) "43210"