Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL INSERT INTO with LEFT JOIN

Sorry this is a syntax question, but in T-SQL how do I specify in INSERT statement in which DB I want to INSERT and in LEFT JOIN from which DB I want to join?

if not exists (select * from [DB_A].[dbo.a_test]) create table [DB_A].[dbo.a_test] ( a int(10) , b int(10) , c varchar(200) , d varchar(200) , e varchar(200) ,             PRIMARY KEY (a) )   INSERT INTO [DB_A].[dbo.a_test] (a,b,c, d) VALUES dbo.products.product_info, dbo.products.product_date, dbo.products.smth, *dbo.program.program_name*, dbo.program.program_smth FROM [DB_B].dbo.products     LEFT JOIN [DB_B].dbo.program ON dbo.program.program_name = dbo.products.product_info 

Sorry for such a noob question, but I could not find a suitable example.

like image 985
user1054844 Avatar asked May 22 '14 13:05

user1054844


People also ask

Can we use insert with join?

Example 5: INSERT INTO SELECT statement with Join clause to get data from multiple tables. We can use a JOIN clause to get data from multiple tables. These tables are joined with conditions specified with the ON clause. Suppose we want to get data from multiple tables and insert into a table.

Can we use join in insert query in SQL Server?

SQL server insert multiple rows using an inner join would be possible. -- Insert into line will select the columns.

Does LEFT join add rows?

A left outer join or left join retains all of the rows of the left table company, regardless of whether there is a row that matches on the right table foods.


1 Answers

You want insert into . . . select:

INSERT INTO [DB_A].[dbo.a_test](a,b,c,d,e) --ADDED A COLUMN     select p.product_info, p.product_date, p.smth, pr.program_name, pr.program_smth     FROM [DB_B].dbo.products p LEFT JOIN          [DB_B].dbo.program pr          ON p.program_name = pr.product_info; 

I also fixed the query to use table aliases, so it is much easier to read.

like image 57
Gordon Linoff Avatar answered Sep 25 '22 03:09

Gordon Linoff