get identity from a table right after it inserts into the table

  • Hi all,

    This is what I have. but somehow it keeps saying that

    Procedure getSelectCertNumber, Line 9

    Invalid column name 'Id'. I don't where it went wrong.

    Can you help?Thanks.

    Betty

    CREATE Proc [dbo].[getSelectCertNumber]

    As

    Declare @CertNumber As TABLE(Id int)

    Declare @NewId AS INT

    Insert Into DBO.TIS_SelectCertNumber

    (InsertDate)

    OUTPUT Inserted.Id INTO @CertNumber

    Values(getDate())

    Select @NewID=Id FROM @CertNumber

    PRINT @NewID

    return

    I can insert data to this table without any problem.

    Insert Into DBO.TIS_SelectCertNumber (InsertDate)Values(getDate())

    CREATE TABLE TIS_SelectCertNumber

    (

    CertificateNumber decimal(18,0) identity(96600,1) not null,

    InsertDate datetime

    )

  • You do not have an id column in the inserted table because you do not have an id column in your base table. Your code should be:

    [font="Courier New"]CREATE      PROC [dbo].[getSelectCertNumber]

    AS

            DECLARE @CertNumber AS TABLE(Id INT)

            DECLARE @NewId AS INT

                    

            INSERT INTO DBO.TIS_SelectCertNumber

                    (InsertDate)

                    OUTPUT Inserted.CertificateNumber INTO @CertNumber

                    VALUES(GETDATE())

                    SELECT @NewID=Id FROM @CertNumber

                    PRINT @NewID

       RETURN[/font]

  • Look up SCOPE_IDENTITY() in books online.

  • Scope_identity() is definitely a more efficient way to do this.

    - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
    Property of The Thread

    "Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply