Du kan köra något liknande den lagrade proceduren nedan för att undvika att skriva ut alla kolumnnamn. Exemplet nedan antar en int, men du kan byta ut nyckeltypen mot vilken datatyp som helst.
create procedure [CloneRow]
@tableName varchar(max),
@keyName varchar(max),
@oldKeyId int,
@newTableId int output
as
declare @sqlCommand nvarchar(max),
@columnList varchar(max);
select @columnList = coalesce(@columnList + ',','') + sys.columns.name
from sys.columns
where object_name(sys.columns.object_id) = @tableName
and sys.columns.name not in ( @keyName )
and is_computed = 0;
set @sqlCommand = 'insert into ' + @tableName + ' ( ' + @columnList + ') (' +
'select ' + @columnList + ' from ' + @tableName + ' where ' + @keyName + ' = @oldKeyId )'
exec sp_executesql @sqlCommand, N'@oldKeyId int', @oldKeyId = @oldKeyId
select @newTableId = @@identity -- note scope_identity() won't work here!
GO
Du kallar det så här:
declare @newOrderId int
exec [CloneRow] 'orderTable', 'orderId', 625911, @newOrderId output