1

My knowledge in SQL not so far, please help me with my issue:

I have a script that generates some data. I need to insert this data into a table with following structure:

Variable_Sample (idsample, idvariable, value), idsample and idvariable - PK.

Here is the script:

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

Here is script result:

Script result.

So I need to put script result into table Variable_Sample(idsample, idvariable, value), where (idsample, idvariable) are the primary key of the table.

2 Answers 2

2

You can add this to the end of the script, instead of the 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
Sign up to request clarification or add additional context in comments.

1 Comment

Great I could help, upvote if it was useful so other users can check it out too when looking for another alternative.
1

I think all you need to is: Add an insert to @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

That's assuming that table already exsists.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.