Du kan køre noget som den lagrede procedure nedenfor for at undgå at skrive alle kolonnenavnene. Eksemplet nedenfor antager en int, men du kan skifte nøgletypen ud med enhver datatype.
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 kalder det sådan her:
declare @newOrderId int
exec [CloneRow] 'orderTable', 'orderId', 625911, @newOrderId output