Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 214
  • Last Modified:

SQL SERVER - COPY ONE ROW WITH PRIMARY KEY

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
0
javilmer
Asked:
javilmer
1 Solution
 
macarrillo1Commented:
Are you wanting any record or a specific record?

Something like:

insert into myTable
select  Top 1 * from myTable
0
 
AnujCommented:
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,'')
0
 
javilmerAuthor Commented:
anujnb : that's sounds interesting, how can i do the insert though ?
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
AnujCommented:
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.
0
 
javilmerAuthor 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" :)
0
 
jogosCommented:
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
0

Featured Post

NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now