Click here to Skip to main content
15,884,078 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi,

I have 2 tables variables as seen below :

@a
[Deptname]
[Location]
[Column1]
[Column2]
[Column3]


@b
testval1,
testval2,
30,
50,
60


The first one i.e. @a has all the column names & the second i.e. @b has all the field values.
Need to loop through these 2 table variables & form an insert statement to insert the columns & corresponding values in a third table.
i.e.
SQL
insert into my_table ([Deptname],[Location],[Column1],[Column2],[Column3])
values ('testval1','testval2','30','50','60')

Any help would be much appreciated.

What I have tried:

SQL
declare @a  varchar(100)  
  
set @a = '[Deptname],[Location],[Column1],[Column2],[Column3]'   
  
select   
    a.value('.', 'varchar(max)')   
from  
    (select cast('<m>' + REPLACE(@a, ',', '<m>') + '' AS XML) as col) as A  
    CROSS APPLY A.col.nodes ('/M') AS Split(a)  



declare @b  varchar(100)  
  
set @b = 'testval1','testval2','30','50','60'   
  
select   
    b.value('.', 'varchar(max)')   
from  
    (select cast('<m>' + REPLACE(@b, ',', '<m>') + '' AS XML) as col) as B  
    CROSS APPLY B.col.nodes ('/M') AS Split(B)
Posted
Updated 11-Feb-21 22:43pm
v2
Comments
Maciej Los 12-Feb-21 3:19am    
In your case @a and @b aren't table variables! They store data of varchar data type (as they were declared).

1 solution

First of all, your sql statement is wrong.

Second of all, you can create sql statement this way:
SQL
declare @a  varchar(1000)  
declare @b  varchar(1000)  
declare @qry varchar(4000)
  
set @a = '[Deptname],[Location],[Column1],[Column2],[Column3]'   
set @b = '''testval1'',''testval2'',''30'',''50'',''60''' 
set @qry = 'INSERT INTO my_table (' + @a + ')' + 
    ' VALUES(' + @b + ');'

print @qry;
-- to execute command, uncomment below line
--execute(@qry);

db<>fiddle[^]
But(!) this way of inserting data is NOT recommended!

Second of all, i'd avoid of using such of statements. I'd suggest to use stored procedures[^], which can accept parameters.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900