Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling identity columns in an "Insert Into TABLE Values()" statement?

In SQL Server 2000 or above is there anyway to handle an auto generated primary key (identity) column when using a statement like the following?

Insert Into TableName Values(?, ?, ?) 

My goal is to NOT use the column names at all.

like image 700
James McMahon Avatar asked Jun 01 '09 15:06

James McMahon


People also ask

What is an identity column in insert statements?

An identity column contains a unique numeric value for each row in the table. Whether you can insert data into an identity column and how that data gets inserted depends on how the column is defined.

How do I get the identity column value after insert?

Once we insert a row in a table, the @@IDENTITY function column gives the IDENTITY value generated by the statement. If we run any query that did not generate IDENTITY values, we get NULL value in the output. The SQL @@IDENTITY runs under the scope of the current session.

How can insert in identity column in SQL?

To manually insert a new value into the Id column, we first must set the IDENTITY_INSERT flag ON as follows: SET IDENTITY_INSERT Students ON; To set the IDENTIT_INSERT flag ON we need to use the SET statement followed by the flag name and the name of the table.

What statement is used to insert values into a table?

The SQL INSERT statement is used to insert a one or more records into a table.


2 Answers

By default, if you have an identity column, you do not need to specify it in the VALUES section. If your table is:

ID    NAME    ADDRESS 

Then you can do:

INSERT INTO MyTbl VALUES ('Joe', '123 State Street, Boston, MA') 

This will auto-generate the ID for you, and you don't have to think about it at all. If you SET IDENTITY_INSERT MyTbl ON, you can assign a value to the ID column.

like image 66
Eric Avatar answered Oct 11 '22 12:10

Eric


Another "trick" for generating the column list is simply to drag the "Columns" node from Object Explorer onto a query window.

like image 35
Aaron Bertrand Avatar answered Oct 11 '22 12:10

Aaron Bertrand