首页 文章

在单个SQL查询中插入多行? [重复]

提问于
浏览
1431

这个问题在这里已有答案:

我有一组数据要一次插入,比如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");

我可以 insert 单个 SQL statement 中的所有4行吗?

4 回答

  • 71

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

    Example:

    INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
    
  • 1906

    NOTE: 这个答案适用于SQL Server 2005.对于SQL Server 2008及更高版本,有更好的方法,如其他答案所示 .

    你可以使用INSERT with SELECT UNION ALL

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

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

  • 733

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

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

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

相关问题