1

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.

2
  • Which DBMS are you using ? Commented Jan 6, 2022 at 19:18
  • @MalwareWerewolf I'm using SQL Server, sorry forgot to mention it Commented Jan 6, 2022 at 19:20

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, will try it in the morning, just leaving the office now. Will report back in the morning.
Thanks, this worked like a charm - exactly what I was looking for. :)
I’m glad that worked ;)

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.