Get last inserted UNIQUEIDENTIFIER in SQL Server 2000

10,477
DECLARE @uid uniqueidentifier 
SET @uid  = newid()

INSERT INTO sample (ID, Title)
VALUES (@uid,'Test1')

SELECT @uid AS ID
Share:
10,477

Related videos on Youtube

Shay
Author by

Shay

Solutions Architect with never-ending passion for code and ever-expanding skill set. Specialize in designing scalable, performant, and practical APIs for any application from start-up to enterprise.

Updated on May 31, 2022

Comments

  • Shay
    Shay almost 2 years

    The OUTPUT clause is compatible with SQL Server 2005 but not SQL Server 2000.

    How do I convert this command to work in SQL Server 2000?

    CREATE TABLE sample
    (
     ID uniqueidentifier NOT NULL DEFAULT newid(),
     Title varchar(30) NOT NULL
    )
    
    INSERT INTO sample (Title)
    OUTPUT INSERTED.ID
    VALUES ('Test1')
    

    I need the command to retrieve the ID since the INSERT command needs to be called from a stored procedure.

    Thanks for any help!

  • Shay
    Shay almost 13 years
    This is a generic INSERT command that works on different tables (some with int IDENTITY(1,1) and some with uniqueidentifier).I need to use the DEFAULT newid().
  • Martin Smith
    Martin Smith almost 13 years
    @ShayN - This is the only way of doing it in SQL Server 2000. There is no equivalent of OUTPUT or SCOPE_IDENTITY() for uniqueidentifier columns. Although I suppose you could simulate the OUTPUT clause by adding an INSERT trigger to the table that does SELECT inserted.id but that would apply to all inserts on the table.
  • Shay
    Shay almost 13 years
    I already saw the trigger solution on other website and I wouldn't be able to use it. I needed to confirm that there is no equivalent. Thank you!