SQL Server 2005: Insert multiple rows with single query

后端 未结 5 1040
北海茫月
北海茫月 2020-12-15 20:56

This should be a fairly straightforward question, but I haven\'t been able to find a solid answer online. I\'m trying to insert multiple rows into the same table, but with o

5条回答
  •  别那么骄傲
    2020-12-15 21:41

    Yep. You have to use UNION ALLs in SQL Server 2005 to insert multiple rows in a SQL script in a single statement.

    INSERT INTO Table 
      (Name, Location) 
    SELECT 'Name1', 'Location1' 
    UNION ALL
    SELECT 'Name2', 'Location2'
    UNION ALL
    SELECT 'Name3', 'Location3' 
    

    The other main alternative is to repeat the Insert statement multiple times which is even more verbose. You need to be careful to use Explicit transactions in this last case to avoid the overhead of many individual commits (and for atomicity reasons of course)

    If you have lots of rows to insert you could use BULK INSERT to load it all in from a delimited file in one statement.

    Finally if this is data already in the database that you are scripting out (perhaps to deploy on another server) the SSMS Tools Pack addin has a "Generate Insert Statements" function that can generate these statements for you.

提交回复
热议问题