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