tableName'sts.students'
columnname'studentid,studentfname,studentlname'
我想使用columnname和tableName获取动态脚本,以将数据插入新表'tabdata'。我能怎么做 ?
答案 0 :(得分:-1)
对不起,我不清楚您的理解。你想要这个吗?
Create table tabdata(header1 varchar(100), header2 varchar(100),
header3 varchar(100),header4 varchar(100),header5 varchar(100))
declare @tableName varchar(100)
declare @columnname varchar(max)
declare @target_columnname varchar(max)
declare @sql varchar(max)
set @tableName='sts.students'
set @columnname='studentid,studentfname,studentlname'
set @target_columnname= (stuff((select ',' +[Name] from (
Select row_number()over(order by Name)as rn ,Name
FROM SysColumns Where id=Object_Id('tabdata')) a
where rn<=len(@columnname)-len(replace(@columnname, ',', ''))+1
FOR XML PATH('')),1,1,''))
SELECT @sql = 'INSERT INTO tabdata(' +
STUFF ((
SELECT ',' + @target_columnname + ''
FOR XML PATH('')), 1, 1, '') +
') select ' +@columnname +' from '+@tableName
print (@sql)
exec(@sql)
/*
INSERT INTO tabdata(header1,header2,header3) select studentid,studentfname,studentlname from sts.students
*/