我发现有 2 种方法可以使用 SQL Server 2008 将许多行插入到表中。
其中之一可以在这里找到http://technet.microsoft.com/en-us/library/bb522522(v=sql.105).aspx说要创建一个临时表,然后将值插入临时表,最后合并与目标能够的表。
这对我来说似乎不是很有效,因为您必须创建一个表,填充表,合并到目标表,然后删除临时表。
我唯一能想到的其他事情如下......
MERGE dbo.targettable as tgt
USING (
SELECT 12 as col1, 13 as col2, 'abc' as col3, 'zyx' as col4
UNION ALL
SELECT 11 as col1, 11 as col2, 'def' as col3, 'def' as col4
(etc etc)
UNION ALL
SELECT 7 as col1, 10 as col2, 'jfj' as col3, 'tub' as col4)
as new
ON tgt.col1=new.col1
WHEN MATCHED THEN UPDATE SET tgt.col2=new.col2, tgt.col3=new.col3, tgt.col4=new.col4
WHEN NOT MATCHED THEN INSERT (col1, col2, col3, col4)
VALUES(new.col1, new.col2, new.col3, new.col4);
根据 usr 的回答,我可以找到http://msdn.microsoft.com/en-us/library/bb510625.aspx
我认为这是做到这一点的方法。有人可以验证此语法是否正确吗?
MERGE dbo.targettable as tgt
USING (VALUES(12, 13, 'abc', 'zyx'), (11, 11, 'def', 'def'),(7, 10, 'jfj', 'tub'))
AS new (col1, col2, col3, col4)
ON tgt.col1=new.col1
WHEN MATCHED THEN UPDATE SET tgt.col2=new.col2, tgt.col3=new.col3, tgt.col4=new.col4
WHEN NOT MATCHED THEN INSERT (col1, col2, col3, col4)
VALUES(new.col1, new.col2, new.col3, new.col4);