协慌网

登录 贡献 社区

在单个 SQL 查询中插入多行?

我有一组数据要一次插入,比如 4 行。

我的表有三列: Person , Id和Office 。

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 statement insert所有 4 行吗?

答案

在 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');

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

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');

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

您可以在 SELECT UNION ALL 中使用INSERT :

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

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