ranga nathan
ranga nathan

Reputation: 163

How to use a select query inside an insert query in SQL Server 2005

I need to insert values into a table. But my condition is that I need to select Min(date) from another table and this value should be inserted into another table.

My query

Insert into tempTable values
('Value1','Value2','Value3',(select min(val_dt) from anotherTable),'Y',getdate())

If I use this query I am facing error.

Guide me how to use select query inside the insert query.

Upvotes: 5

Views: 4494

Answers (1)

rikitikitik
rikitikitik

Reputation: 2450

Instead of using VALUES() in the INSERT statement, use a SELECT to add the row values:

INSERT INTO tempTable
SELECT 'Value1', 'Value2', 'Value3', MIN(val_dt), 'Y', GETDATE()
FROM anotherTable

And the SELECT statement can be as convoluted as you want, meaning WHEREs and the like can be included.

Upvotes: 7

Related Questions