1867

我要一次插入多组数据,比如 4 行。我的表有三列PersonIdOffice

INSERT INTO MyTable VALUES ("John", 123, "Lloyds Office");
INSERT INTO MyTable VALUES ("Jane", 124, "Lloyds Office");
INSERT INTO MyTable VALUES ("Billy", 125, "London Office");
INSERT INTO MyTable VALUES ("Miranda", 126, "Bristol Office");

我可以在一个 SQL 语句中插入所有 4 行吗?

4

4 回答 4

2476

在 SQL Server 2008 中,您可以使用单个 SQL INSERT 语句插入多行。

INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )

作为参考,请查看 MOC 课程 2778A - 在 SQL Server 2008 中编写 SQL 查询。

例如:

INSERT INTO MyTable
  ( Column1, Column2, Column3 )
VALUES
  ('John', 123, 'Lloyds Office'), 
  ('Jane', 124, 'Lloyds Office'), 
  ('Billy', 125, 'London Office'),
  ('Miranda', 126, 'Bristol Office');
于 2009-01-17T07:14:14.367 回答
853

如果要插入单个表,则可以这样编写查询(可能仅在 MySQL 中):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');
于 2009-01-17T06:10:26.447 回答
147

注意:此答案适用于 SQL Server 2005。对于 SQL Server 2008 及更高版本,如其他答案所示,有更好的方法。

您可以将INSERT 与 SELECT UNION ALL 一起使用:

INSERT INTO MyTable  (FirstCol, SecondCol)
    SELECT  'First' ,1
    UNION ALL
SELECT  'Second' ,2
    UNION ALL
SELECT  'Third' ,3
...

不过,仅适用于小型数据集,这对您的 4 条记录应该没问题。

于 2009-01-17T06:16:23.593 回答
89

INSERT使用VALUES语法的语句可以插入多行。为此,请包含多个列值列表,每个列表都包含在括号中并用逗号分隔。

例子:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
于 2009-04-01T14:07:24.633 回答