Home > other >  Passing Variable to SQL insert statement
Passing Variable to SQL insert statement

Time:01-08

I know this code here selects columns from one table and inserts it into another table. However, I have a value that I want to insert into one of the columns, how do I pass in the value?

This selects from on table and inserts into another...

INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;

However, I want column1 to have a value that I set above the code e.g MY_NAME varchar(20)

set @MY_NAME = "Helen"

Then my insert statement to be something like this:

INSERT INTO table2 (column1, column2, column3, ...)
SELECT *@MY_NAME*, column2, column3, ...
FROM table1
WHERE condition;

Any help would be appreciated.

CodePudding user response:

To achieve that you should do something like this:

declare @MY_NAME AS varchar(20)
set @MY_NAME = 'Helen'

Insert into table2([column1], [column2], [column3]) 
select @MY_NAME, column2, column3  
from table1
  •  Tags:  
  • Related