【问题标题】:How can I get the ID of the last INSERTed row using PDO with SQL Server?如何使用带有 SQL Server 的 PDO 获取最后一个 INSERTed 行的 ID?
【发布时间】:2011-09-02 16:31:46
【问题描述】:

在其他情况下我可能会想使用

$result = mssql_query("INSERT INTO table (fields) VALUES (data); 
                       SELECT CAST(scope_identity() AS int)");

但由于我将插入用户提交的数据,我想继续使用 PDO,它返回一个空数组。

不幸的是,我在 Linux 服务器上运行 PHP 并使用 dblib 与不支持 PDO::lastInsertID() 的 Microsoft SQL Server 交互。

请帮忙!

更新以包含代码示例

这是我正在使用的代码:col1 是int identity 类型的字段,col2 是datetime,默认为getdate()

//  Connect to db with PDO
$pdo = new PDO( 'dblib:host=' . $host . ';dbname=' . $database . ';', $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) );
//  Connect to db with MSSQL
$sql = mssql_connect( $host, $username, $password );
mssql_select_db( $database, $sql );
//  Create SQL statement
$query = "INSERT INTO [table] ( col3, col4, col5 )
          VALUES ( 'str1', 'str2', 'str3' );
          SELECT SCOPE_IDENTITY() AS theID;";
//  Run with MSSQL
echo "Using MSSQL...\n";
$result = mssql_query( $query );
$the_id = mssql_result( $result, 0, 'theID' );
echo "Query OK. Returned ID is " . $the_id . "\n";
// Run with PDO
echo "\nUsing PDO...\n";
$stmt = $pdo->query( $query );
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
print_r( $result );

这就是显示的内容:

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

Using PDO...
Array
(
)

我很想知道我做了一些愚蠢的事情,而不是遇到可怕的死胡同:)

【问题讨论】:

    标签: php sql-server sql-server-2000 pdo


    【解决方案1】:

    你有几个选择:

    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() 是最佳候选。

    【讨论】:

    • PDO 仍然返回一个空数组。我做错了吗?
    • 也许可以尝试别名化结果:SELECT scope_identity() AS id
    • 感谢您的建议。我仍然得到一个空数组。我已经更新了我的问题以包含我正在使用的测试代码。
    • 更新:我没有意识到 SELECT SCOPE_IDENTITY() 可以在原始查询之后发送。现在一切正常,感谢您的帮助。
    【解决方案2】:

    也许您正在返回两个行集。尝试添加 SET NOCOUNT ON;消除 INSERT 的行集,或使用 $stmt->nextRowset 如果您的驱动程序支持它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 2015-05-21
      • 2019-03-09
      • 2013-08-28
      • 2013-12-09
      相关资源
      最近更新 更多