MS SQL – Last Inserted ID

Notiz:

While trying to return a @@IDENTITY after an INSERT statement, the only way I could get a valid return result was to encapsulate the query within an EXEC like so:

$result = mssql_query(”
exec(”
INSERT INTO Files
(ownerId, name, sizeKB, path)
VALUES (‘$contactId’, ‘$userfile_name’, ‘$filesize’, ‘$path’)
SELECT @@IDENTITY as fileId”)
“);
list($fileId) = mssql_fetch_row($result);

This returned the appropriate @@IDENTITY in a valid result set. Not sure if mssql supports multiple inline commands or not. But that assumption would back the useage of the EXEC command in order to execute these properly.
(fundstelle: PHP Resource)

5 Responses to “MS SQL – Last Inserted ID”

  1. Harry Says:

    Hi

    Genau das was ich gesucht habe!

    Vielen Dank!

    Harry

  2. mukesh Says:

    mssql insert_id()

  3. Vlad Pop Says:

    That would be mysql_insert_id(). There’s no mssql_insert_id().

  4. Lari Says:

    As you might have paid attention to, that ‘exec’ allows sql injections.

  5. Hinek Says:

    I think you should use
    SELECT scope_identity()