SQL Server – inserting multiple rows with single (ANSI style) statement

前端 未结 2 1479
被撕碎了的回忆
被撕碎了的回忆 2020-12-22 06:57

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

相关标签:
2条回答
  • 2020-12-22 07:53

    Try this instead:

    INSERT TestInsert
        SELECT  1, 'a'
        UNION ALL
        SELECT  2, 'b'
        UNION ALL
        SELECT  3, 'c'
        UNION ALL
        SELECT  4, 'd'
        UNION ALL
        SELECT 5, 'e' 
    
    0 讨论(0)
  • 2020-12-22 07:55

    SQL Server - inserting multiple rows with single (ANSI style) statement

    For SQL Server 2000+

    According to SQL The Complete Reference, Third Edition (August 12, 2009):

    1) The syntax for multirow INSERTs is

    INSERT INTO table-name (columns not mandatory) 
    query
    

    (page 236, Figure 10-3).

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

    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)
    

    and then

    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
    

    Edit 2: For SQL Server 2008+

    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).

    So,

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

    will work on SQL Server 2008+.

    0 讨论(0)
提交回复
热议问题