2

Is there any way to capture the values to be inserted to a table into one variable as comma separated values and use the variable to execute insert into statement. For example, create a test table as

create table id_test (id int, name varchar(10))

declare a variable and set the value for the variable to be the values to be inserted into table with comma separated as shown below:

declare @test as varchar(60) ;
set @test = '10,''john''';

Now use the variable @test in insert into as

insert into id_test (id,name) values(@test)

Reason for asking this question is that, I do not want to pass all the variables from web page to a stored procedure. Instead I want to pass pass one variable from Web page which holds the comma separated values to be inserted into table.

4
  • The best method is to pass all variable's values as a separate parameter. Your method will lead to SQL Injection Commented Jul 20, 2016 at 10:04
  • @Madhivanan , is there any specific reason to do so? I thought, better to have one variable instead of passing individual variables as each table has more number of columns. Commented Jul 20, 2016 at 10:12
  • 2
    yes it leads to sql injection stackoverflow.com/questions/601300/what-is-sql-injection Commented Jul 20, 2016 at 10:31
  • Thanks Madhivanan.. I checked the link you gave. I will consider sql injects before finalizing solution! thanks again! Commented Jul 20, 2016 at 10:51

1 Answer 1

2

Using a dynamic query you can achieve this. In stored procedure after variable declaration

declare @test as varchar(60); 
set @test = '10,''john''';   

declare @sql AS VARCHAR(MAX) = 'insert into id_test (id, name) values('+@test+')'

--USE EXEC() to execute your insert command
EXEC(@sql)
Sign up to request clarification or add additional context in comments.

1 Comment

Looks wide open to SQL Injection attacks.

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.