About Me

My photo
Mumbai, Maharastra, India
He has more than 7.6 years of experience in the software development. He has spent most of the times in web/desktop application development. He has sound knowledge in various database concepts. You can reach him at viki.keshari@gmail.com https://www.linkedin.com/in/vikrammahapatra/ https://twitter.com/VikramMahapatra http://www.facebook.com/viki.keshari

Search This Blog

Saturday, January 19, 2013

Inserting data into a table that has just one column which is identity type???


If you have a table with one column, which is promoted with an identity column and you were told to insert rows into the table, how you will be performing the command?

Let’s stimulate the case by taking a table OneColumnTable with only one column id

create table OneColumnTable
(id int identity(1,1))

Now try to insert record in this table using insert statement

insert into OneColumnTable values(1)
//OUTPUT
Msg 8101, Level 16, State 1, Line 1
An explicit value for the identity column in table 'OneColumnTable' can only be specified when a column list is used and IDENTITY_INSERT is ON.

So it is not allowing to insert record in the table, but then you got a task to insert data into this table, how to do the insertion, lets fire the below query

insert into OneColumnTable default values
(1 row(s) affected)

select * from OneColumnTable
id
-----------
1
(1 row(s) affected

Note: If you want to continue inserting identity values, then you can make use of default value clause
And, If you want to insert explicit values then you can write

set identity_insert oneColumnTable on
insert into OneColumnTable(id) values(5);
set identity_insert oneColumnTable on
(1 row(s) affected)

select * from OneColumnTable
id
-----------
1
5
(2 row(s) affected)

That’s how you can insert values in identity column. J

Put out of your mind, it’s coding; very straightforward J   


Post Reference: Vikram Aristocratic Elfin Share

No comments:

Post a Comment