我的SQL知识到目前为止,请帮我解决我的问题:
我有一个生成一些数据的脚本。我需要将这些数据插入到具有以下结构的表中:
Variable_Sample (idsample, idvariable, value), idsample and idvariable - PK.
这是脚本:
Declare params cursor for
Select distinct id_variable from [UIR_DB].[dbo].[Variable_Values]
open params
Declare @idparam int
Declare @csql nvarchar(max) = ''
Declare @csql2 nvarchar(max) = ''
Declare @i int = 1
fetch next from params into @idparam
while @@FETCH_STATUS = 0
begin
Select @csql2 = @csql2 + ', param' +LTrim(Str(@i))
Select @csql = @csql + ' (Select value as param'+LTrim(Str(@i))+' from [UIR_DB].[dbo].[Variable_Values] where id_variable = '+LTrim(Str(@idparam))+') a'+LTrim(Str(@i))+' cross join'
Set @i = @i+1
fetch next from params into @idparam
end
Select @csql = '
SELECT id, CAST(SubString(Param,6,LEN(Param)-5) as int) param_id, param_val
FROM
(Select ROW_Number() over(order by '+SubString(@csql2,2,LEN(@csql2)-1)+') id, '+SubString(@csql2,2,LEN(@csql2)-1)+' from '+SubString(@csql,1,LEN(@csql)-11) + ') p
UNPIVOT
(param_val FOR Param IN
('+SubString(@csql2,2,LEN(@csql2)-1)+')
)AS unpvt
'
print @csql
exec sp_executesql @csql
close params
deallocate params
这是脚本结果:
所以我需要将脚本结果放到表Variable_Sample(idsample, idvariable, value)
中,其中(idsample, idvariable
)是表的主键。
答案 0 :(得分:2)
您可以将其添加到脚本的末尾,而不是EXEC sp_executesql @csql
:
CREATE TABLE #temptable (idsample INT, idvariable INT, value INT)
INSERT INTO #temptable EXEC @csql
SELECT idsample, idvariable, value FROM #temptable
DROP TABLE #temptable
答案 1 :(得分:1)
我认为您需要的只是: 将插入添加到@csql
e.g。
Insert into variable_sample(idsample, idvariable, value)
SELECT id, CAST(SubString(Param,6,LEN(Param)-5) as int) param_id, param_val
FROM
(Select ROW_Number() over(order by '+SubString(@csql2,2,LEN(@csql2)-1)+') id, '+SubString(@csql2,2,LEN(@csql2)-1)+' from '+SubString(@csql,1,LEN(@csql)-11) + ') p
UNPIVOT
(param_val FOR Param IN
('+SubString(@csql2,2,LEN(@csql2)-1)+')
)AS unpvt
假设该表已经存在。