将select语句中的多行插入到现有表中

时间:2014-10-09 17:54:22

标签: sql sql-server

我编写了一个从数据库表中提取数据的查询。我正在将查询的结果合并到另一个数据库表中,我需要一些建议。我的select语句如下所示:

SELECT * FROM dbo.ActivePasscodes
WHERE ACCOUNT NOT IN 
('BCLions','DCL02','DEM02','DEMO2','Fission','Havilah','Mbac',
'NEW','OrkoSilver','PDAC2012','PDAC2012D','PROMO2','Rocktech','XMAS',
'Xmas1','Xmas2','Xmas3','Xmas4','Xmas5','Xmas6',
'Xmas7','Xmas8','CMP33','TEST','ZZZ3','DNB02','XXX02',
'DNBTEST','32576','TEST123','TEST REC','CCTest','XXX') 
AND Deleted <> '1'
AND CODE NOT IN ('21717312','24536779','27227816','37121896','47241',
'35965','51983','68696')

此查询返回1501条记录。我想要完成的是将这些1501记录插入另一个具有相同记录的现有数据库表中(如同所有列匹配)。

有人可以告诉我或者至少指出我如何将此查询返回的所有记录插入到我的其他数据库表中吗?我是微软SQL Server的新手,并对此做了一些研究,但没有找到与我的场景非常相似的东西。如果事情不是很清楚,请随时要求进一步澄清。

我很感激帮助!

谢谢!

-Dave

2 个答案:

答案 0 :(得分:3)

试试这个:

您可以从现有数据库访问您的远程表,如下所示:

select * from NewDataBase.dbo.NewTable

同样的方式。只需要编写NewDatabase名称并指定所有列

Insert into NewDataBase.dbo.NewTable(Col1,Col2,Col3,Col4)
SELECT (Col1,Col2,Col3,Col4) FROM dbo.ActivePasscodes
WHERE ACCOUNT NOT IN 
('BCLions','DCL02','DEM02','DEMO2','Fission','Havilah','Mbac',
'NEW','OrkoSilver','PDAC2012','PDAC2012D','PROMO2','Rocktech','XMAS',
'Xmas1','Xmas2','Xmas3','Xmas4','Xmas5','Xmas6',
'Xmas7','Xmas8','CMP33','TEST','ZZZ3','DNB02','XXX02',
'DNBTEST','32576','TEST123','TEST REC','CCTest','XXX') 
AND Deleted <> '1'
AND CODE NOT IN ('21717312','24536779','27227816','37121896','47241',
'35965','51983','68696')

答案 1 :(得分:1)

INSERT INTO MyTableName (MyField1, MyField2, etc)
SELECT MyField1, MyField2, etc 
FROM dbo.ActivePasscodes
WHERE ACCOUNT NOT IN 
  ('BCLions','DCL02','DEM02','DEMO2','Fission','Havilah','Mbac', 'NEW','OrkoSilver','PDAC2012','PDAC2012D','PROMO2','Rocktech','XMAS', 'Xmas1','Xmas2','Xmas3','Xmas4','Xmas5','Xmas6', 'Xmas7','Xmas8','CMP33','TEST','ZZZ3','DNB02','XXX02', 'DNBTEST','32576','TEST123','TEST REC','CCTest','XXX') 
  AND Deleted <> '1'
  AND CODE NOT IN ('21717312','24536779','27227816','37121896','47241', '35965','51983','68696')