1

到目前为止,我对 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

这是脚本结果:

脚本结果.

所以我需要将脚本结果放入 table Variable_Sample(idsample, idvariable, value),其中 ( idsample, idvariable) 是 table 的主键。

4

2 回答 2

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
于 2013-05-05T20:59:10.367 回答
1

我认为您需要做的就是:向@csql 添加一个插入

例如

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

这是假设该表已经存在。

于 2013-05-05T20:55:59.387 回答