如何使用ODBC在SQL Server 2000中获取最后插入的ID?

时间:2015-03-07 20:10:21

标签: sql-server odbc sql-server-2000 lastinsertid last-insert-id

我正在使用此代码将新记录插入数据库:

function newProtocol($date, $type, $text, $who, $reff) {
    $sql = "INSERT INTO c_rozhovor (ref_kunde, protokol_typ, besuch_protokol, datum_vzniku, kto_vytvoril) VALUES ('"
            .msescape($reff)."','"
            .msescape($type)."','"
            .msescape($text)."','"
            .msescape($date)."','"
            .msescape($who)."')";

    $connection = odbc_connect(constant('DATABASE_NAME'),'','');
    if (!connection) return false;      

    $query = odbc_exec($connection, $sql);
    if (!query) return false;

    return "New protocol was successfuly saved!";   
}

我想以某种方式返回最后插入的ID 而不是New protocol was successfully saved!字符串。类似于MySql中的LAST_INSERT_ID()。有没有办法在SQL Server 2000中实现这一目标?

1 个答案:

答案 0 :(得分:-1)

您可以尝试对代码进行以下修改:

function newProtocol($date, $type, $text, $who, $reff) {
    $sql = "INSERT INTO c_rozhovor (ref_kunde, protokol_typ, besuch_protokol, datum_vzniku, kto_vytvoril) VALUES ('"
            .msescape($reff)."','"
            .msescape($type)."','"
            .msescape($text)."','"
            .msescape($date)."','"
            .msescape($who)."') SELECT SCOPE_IDENTITY()";

    $connection = odbc_connect(constant('DATABASE_NAME'),'','');
    if (!connection) return false;      

    $query = odbc_exec($connection, $sql);
    if (!query) return false;

    return $query;
}