Php 如何使用带有SQL Server的PDO获取最后插入行的ID?

Php 如何使用带有SQL Server的PDO获取最后插入行的ID?,php,sql-server,sql-server-2000,pdo,Php,Sql Server,Sql Server 2000,Pdo,在其他情况下,我可能会尝试使用 $result = mssql_query("INSERT INTO table (fields) VALUES (data); SELECT CAST(scope_identity() AS int)"); 但在插入用户提交的数据时,我希望继续使用PDO,它返回一个空数组 不幸的是,我在Linux服务器上运行PHP,并使用dblib与Microsoft SQL server接口,而Microsoft SQL se

在其他情况下,我可能会尝试使用

$result = mssql_query("INSERT INTO table (fields) VALUES (data); 
                       SELECT CAST(scope_identity() AS int)");
但在插入用户提交的数据时,我希望继续使用PDO,它返回一个空数组

不幸的是,我在Linux服务器上运行PHP,并使用dblib与Microsoft SQL server接口,而Microsoft SQL server不支持
PDO::lastInsertID()

请帮忙

更新以包含代码示例

下面是我使用的代码:col1是类型为
int-identity
的字段,col2是
datetime
,默认值为
getdate()

这就是展示的内容:

Using MSSQL...
Query OK. Returned ID is 149

Using PDO...
Array
(
)

我想知道我做了什么蠢事,而不是遇到可怕的死胡同:)

你有几个选择:

SELECT @@IDENTITY - return the last ID created by actions of the current connection, regardless of table/scope

SELECT SCOPE_IDENTITY() - last ID produced by the current connection, in scope, regardless of table

SELECT IDENT_CURRENT('name_of_table'); - last ID produced on that table, regardless of table/scope/connection

在这三个行中,SCOPE_IDENTITY()是最佳候选行。

可能返回了两个行集。尝试添加设置无计数;要消除INSERT的行集,请使用$stmt->nextRowset(如果驱动程序支持)。

PDO
仍然返回空数组。我做错了什么吗?也许可以尝试将结果别名:
选择scope\u identity()作为id
谢谢您的建议。但我仍然得到一个空数组。我已经更新了我的问题以包含我正在使用的测试代码。更新:我没有意识到
SELECT SCOPE\u IDENTITY()
可以在原始查询之后发送。现在一切正常,谢谢你的帮助。
SELECT @@IDENTITY - return the last ID created by actions of the current connection, regardless of table/scope

SELECT SCOPE_IDENTITY() - last ID produced by the current connection, in scope, regardless of table

SELECT IDENT_CURRENT('name_of_table'); - last ID produced on that table, regardless of table/scope/connection