Trigger to create a Primary key

  • Hi ,

    I am trying to create a before insert trigger which generates the primary key for each row being inserted in the table.  The primary key is going to be just a sequence of integers starting from 1 .  Is there a sequence object in SQL server?

  • There is no sqquence object in SQL Server, instead there is an identity property for tables




    My Blog: http://dineshasanka.spaces.live.com/

  • CREATE TABLE dbo.Product (

    ID Int Identity (1,1) NOT NULL,

    ProductName VARCHAR(50) NOT NULL ,

    ...etc

    )

    The parameters of identity are the start value of the sequence and the increment.

    You can force numbers (if you have legacy data) into the ID field by putting

    SET IDENTITY_INSERT dbo.Product ON

    INSERT dbo.Product (ID,ProductName) VALUES (5,'Widgets')

    INSERT dbo.Product (ID,ProductName) VALUES (10,'Gadgets')

    SET IDENTITY_INSERT dbo.Product OFF

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

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