auto generate

  • hi everybody

    i want create a table Events

    this table has a primary key EventID

    .I want create auto generate EventID by using Procedure or trigger

    please , tell me the way to create

    thanks

  • You are better off letting the server do it for you.  This would be a good start for the table :

     

    IF EXISTS (SELECT * FROM dbo.SysObjects WHERE Name = 'Events' AND XType = 'U' AND USER_NAME (uid) = 'dbo')

     DROP TABLE dbo.Events

    GO

    CREATE TABLE dbo.Events

    (

       EventID INT NOT NULL IDENTITY(1,1)

     , EventName varchar(50) NOT NULL

     , CONSTRAINT [PK_EventID] PRIMARY KEY CLUSTERED

     (

      EventID

    &nbsp  ON [PRIMARY]

    ) ON [PRIMARY]

    GO

    INSERT INTO dbo.Events (EventName) VALUES ('Demo1')

    INSERT INTO dbo.Events (EventName) VALUES ('Demo2')

    SELECT * FROM dbo.Events

    --DROP TABLE dbo.Events

  • BTW, the smiley face delete one character from my script.  Add a ) in place of the smiley to correct the error.

     

    Also this question would have been better placed in the newbie or TSQL forum. This allows you to get the most and fastest responses.

  • thanks Ninja

    but EventID : Char(6)

    exp: '000001'

    '000002'

    '000003'

    ......

    please help me againt

    thank for your question

  • IF EXISTS (SELECT FROM dbo.SysObjects WHERE Name 'Events' AND XType 'U' AND USER_NAME (uid'dbo')
    
           DROP TABLE dbo.Events
    
    GO
    
    CREATE TABLE dbo.Events
    
    (
    
           EventID INT NOT NULL IDENTITY(1,1)
    
           , EventIDChr AS RIGHT('00000' CAST(EventID AS VARCHAR(6)), 6)
    
           , EventName VARCHAR(50) NOT NULL
    
           , CONSTRAINT [PK_EventID] PRIMARY KEY CLUSTERED 
    
           (
    
                   EventID
    
           )
    
           ON [PRIMARY]
    
    ON [PRIMARY]
    
    GO
    
    INSERT INTO dbo.Events (EventNameVALUES ('Demo1')
    
    INSERT INTO dbo.Events (EventNameVALUES ('Demo2')
    
    SELECT FROM dbo.Events
    
    
    
    --DROP TABLE dbo.Events
  • thanks you very must Ninja

Viewing 6 posts - 1 through 5 (of 5 total)

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