I have a table with about 20 columns, and I wish to duplicate a record. I could just do:
INSERT INTO [Table] (ColumnA, ColumnB, ColumnC, .... ColumnZ)
SELECT TOP 1 ColumnA, ColumnB, ColumnC, .... ColumnZ
FROM [Table]
WHERE ID=@ID
However, this will be time consuming, and if a new column is added to the table in the future i want this to be automatically duplicated. Therefore I’m looking for some way of doing:
INSERT INTO [Table]
SELECT TOP 1 * (apart from identity)
FROM [Table]
WHERE ID=@ID
Is this possible?
SQL Server does not provide any kind of “select * except for identity” functionality, you would have to write that yourself by specifying each column. If the table’s column definitions will change over time (add, rename, or drop columns), then the only way to do it is with dynamic code, building the insert statement based on the contents of sys.columns for object_kd = object_id(‘YourTable’), excluding the identity column if one is present. For my money, if you add columns, you’re better off reviewing and updating the code that references that table.
Oh, and if ID is a primary key, then
top 1is unnecessary.