We help IT Professionals succeed at work.

SQL SERVER - COPY ONE ROW WITH PRIMARY KEY

javilmer
javilmer asked
on
Medium Priority
241 Views
Last Modified: 2012-03-13
Hi,
We have a table with hundreds columns, so it would be a bit heavy to name each, and we need a stored procedure that copies one row. We have a primary key autonum, so :
insert into myTable select * from myTable does not work.
Any (simple) idea ?
Thanks for help
Comment
Watch Question

Michael CarrilloInformation Systems Manager
Top Expert 2012

Commented:
Are you wanting any record or a specific record?

Something like:

insert into myTable
select  Top 1 * from myTable
SQL Server DBA
Top Expert 2011
Commented:
You cannot use '*' in your insert queries if you have identity columns in the destination table,
a tricky way to get all non identity columns is by using the result of the following query.

SELECT STUFF((SELECT ', '+name
FROM sys.columns
WHERE is_identity = 0
AND object_id = OBJECT_ID('YourTable')
FOR XML PATH('')),1,1,'')

Author

Commented:
anujnb : that's sounds interesting, how can i do the insert though ?
AnujSQL Server DBA
Top Expert 2011

Commented:
Execute the above query, this will gives a list of columns separated by comma, copy the results and paste into your Stored procedure, this is just a tricky way of doing the things you can do the same using dynamic sql but its not recommended.

Author

Commented:
I can't do it manually, if not i would copy/paste in visual studio, I need a stored proc because the application needs a "copy function" :)

Commented:
With a identity-column you mustalways specify the columnlist

insert into mytable (col1,col2 ...;)
select col1, col2
from ....

If you also want to insert the identity-column itself you must SET IDENTITIY_INSERT
http://msdn.microsoft.com/en-us/library/ms188059.aspx

And I would advise always include the column-list because for future changes in source or destination your sql could become invallid.

Notice that when in SSMS you select your table and click right, you can choose for that table to generate a insert statement for you .... no typing for the columnlist only copy/paste

Explore More ContentExplore courses, solutions, and other research materials related to this topic.