很抱歉这是一个语法问题,但是在T-SQL中如何在INSERT语句中指定我要插入哪个DB以及从哪个DB加入LEFT 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
很抱歉这样一个noob问题,但我找不到合适的例子。
答案 0 :(得分:36)
您想要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;
我还修复了查询以使用表别名,因此更容易阅读。
答案 1 :(得分:4)
INSERT INTO [DB_A].[dbo.a_test] (a,b,c, d)
SELECT dbo.products.product_info, dbo.products.product_date, dbo.products.smth, dbo.program.program_smth
FROM [DB_B].dbo.products
LEFT JOIN [DB_B].dbo.program
ON dbo.program.program_name = dbo.products.product_info