SQL Server - 使用单个(ANSI 样式)语句插入多行 [英] SQL Server – inserting multiple rows with single (ANSI style) statement

查看:43
本文介绍了SQL Server - 使用单个(ANSI 样式)语句插入多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下方法使用单个 INSERT 语句插入多行,这是插入行的 ANSI 样式.它在 SQL Server 2008 和 2012 中可用.我不确定 SQL Server 2005/2000.

I am using following method for inserting multiple rows using a single INSERT statement, that is the ANSI style of inserting rows. It is available in SQL Server 2008 and 2012. I am not sure of SQL Server 2005/ 2000.

创建测试表:

create table TestInsert (ID INT, Name NVARCHAR(50))

单个INSERT语句插入5行

INSERT INTO TestInsert 
VALUES (1,'a'),
       (2,'b'),
       (3,'c'),
       (4,'d'),
       (5,'e')

请告诉我是否还有其他最佳方法可以实现这一目标

Please let me know if there is any other best way to achieve this

推荐答案

SQL Server - 使用单个(ANSI 样式)语句插入多行

对于 SQL Server 2000+

根据 SQL 完整参考,第三版(8 月2009 年 12 月 12 日):

1) 多行 INSERT 的语法是

1) The syntax for multirow INSERTs is

INSERT INTO table-name (columns not mandatory) 
query

(第 236 页,图 10-3).

(page 236, Figure 10-3).

2) SELECT 语句必须使用 FROM 子句(第 87 页,图 6-1).

2) The SELECT statement has the FROM clause mandatory (page 87, Figure 6-1).

因此,在这种情况下,要仅使用一个 INSERT 语句插入多行,我们需要一个 只有一行的辅助表:

So, in this case, to insert multiple rows using just one INSERT statement we need an auxiliary table with just one row:

CREATE TABLE dual(value INT PRIMARY KEY CHECK(value = 1))
INSERT dual(value) VALUES(1)

然后

INSERT INTO table-name (columns) -- the columns are not mandatory
SELECT values FROM dual
UNION ALL
SELECT another-values FROM dual
UNION ALL
SELECT another-values FROM dual

编辑 2:对于 SQL Server 2008+

从 SQL Server 2008 开始,我们可以使用行构造函数:(第 1 行的值)、(第 2 行的值)、(第 3 行的值)等(第 218 页).

Starting with SQL Server 2008 we can use row constructors: (values for row 1), (values for row 2), (values for row 3), etc. (page 218).

所以,

INSERT INTO TestInsert 
VALUES (1,'a'), --The string delimiter is ' not ‘...’
       (2,'b'),
       (3,'c'),
       (4,'d'),
       (5,'e')

适用于 SQL Server 2008+.

will work on SQL Server 2008+.

这篇关于SQL Server - 使用单个(ANSI 样式)语句插入多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆