我相信下面的动态查询就是您想要的:
declare @tableName varchar(100), @id int, @columns varchar(max), @pk varchar(20)
set @tableName = 'MyTable'
set @pk = 'id'
set @id = 45
set @columns = stuff((select ',['+c.name+']' [text()] from sys.tables t
join sys.columns c on t.object_id = c.object_id
where t.name = @tableName and c.name <> @pk for xml path('')),1,1,'')
print 'insert into [' + @tableName + '] (' + @columns + ')
select ' + @columns + '
from [' + @tableName + ']
where ' + @pk + ' = ' + cast(@id as varchar)
你真正想要的是:
declare @tableName varchar(100), @id int, @columns nvarchar(max), @pk nvarchar(20), @columnValues nvarchar(max)
set @tableName = 'MyTable'
set @pk = 'id'
set @id = 45
set @columns = stuff((select ',['+c.name+']' [text()] from sys.tables t
join sys.columns c on t.object_id = c.object_id
where t.name = @tableName and c.name <> @pk for xml path('')),1,1,'')
set @columnValues = 'set @actualColumnValues = (select' +
stuff((select ','','''''' + cast(['+c.name+'] as varchar(max)) + '''''''' [text()]' [text()]
from sys.tables t
join sys.columns c on t.object_id = c.object_id
where t.name = @tableName and c.name <> @pk for xml path('')),1,1,'')
+ 'from [' + @tableName + ']
where ' + @pk + ' = ' + cast(@id as varchar)
+ 'for xml path(''''))'
--select @columnValues
declare @actualColumnValues nvarchar(max), @columnValuesParams nvarchar(500)
SET @columnValuesParams = N'@actualColumnValues nvarchar(max) OUTPUT';
EXECUTE sp_executesql @columnValues, @columnValuesParams, @actualColumnValues OUTPUT;
--SELECT stuff(@actualColumnValues, 1,1, '')
declare @statement nvarchar(max)
set @statement =
'insert into [' + @tableName + '] (' + @columns + ')
select ' + stuff(@actualColumnValues,1,1,'')
print @statement
它产生了
insert
语句,然后查询表中的实际数据并生成
select
有数据的声明。对于某些非常复杂的数据类型可能无法正常工作,但是对于varchars,datetimes和int应该可以像一个符咒一样工作。