You can run something like the stored procedure below to avoid typing out all of the column names. The example below assumes an int, but you can swap the key type out for any data type.
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
You call it like this:
declare @newOrderId int
exec [CloneRow] 'orderTable', 'orderId', 625911, @newOrderId output
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…