using a sub sql with expression

  • Hello,

    I have the following SQL;

     

    insert into t_postCard(ID, Source, toName, toEmail, fromName, fromEmail, message, readRecept, flash, dateSent, pass) values(4003, 'scccx', 'bxzcv', 'msdf', 'ssdf', 'sdfam', 'csdfsad', 0, 1, '01/01/2004', '2664')

     

    I would like to modify it so that the value input for the ID is the result of a select max ID value + 1. Is this possible? Also if it is, then is it a acceptable way to increase the ID value by one for a table, ID is the primary key,

     

    Many thanks

  • You could do this with some type of variable, but I would recommend using IDENTITY for an incremental ID column.

  • It is possible as I demonstrate below but it is not the recommended way to get a unique incrementing serial number.  What you want is an IDENTITY column.

    An Identity column is automatically allocated a number by SQL Server when a row is added.  The numbers generally increade by 1 each row but you can occationally get a gap in the numbering if a transaction is rolled back. 

    Create your table with

    CREATE TABLE MyTab

    ( ID integer identity not null primary key,

     Source varchar(??) etc..

    )

    The column doesn't have to be a primary key but I presume you want it to be in this case.

    You can also mark the column as an identity column via enterprise namager table designed (I can't remember where).

    When you insert the data into the table, you should miss out the identify column from the statement. e.g.

    insert into t_postCard(Source, toName, toEmail, fromName, fromEmail, message, readRecept, flash, dateSent, pass) values('scccx', 'bxzcv', 'msdf', 'ssdf', 'sdfam', 'csdfsad', 0, 1, '01/01/2004', '2664')

    The full details about Identity columns can be seen in SQL Books online.

    The SQL for not using the Identity column is below but it will not perform so well.

    insert into t_postCard(ID, Source, toName, toEmail, fromName, fromEmail, message, readRecept, flash, dateSent, pass)

    Select  (select ISNULL(MAX(ID)) + 1 from t_postCard),

     'scccx', 'bxzcv', 'msdf', 'ssdf', 'sdfam', 'csdfsad', 0, 1, '01/01/2004', '2664'

     

     

  • --This works if ID is not identity

    declare @ID int

    set @ID = MAX(ID) + 1 FROM t_postcard

    insert into t_postCard(ID, Source, toName, toEmail, fromName, fromEmail, message, readRecept, flash, dateSent, pass) values(@ID, 'scccx', 'bxzcv', 'msdf', 'ssdf', 'sdfam', 'csdfsad', 0, 1, '01/01/2004', '2664')

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

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