Insert multiple rows WITHOUT repeating the “INSERT INTO …” part of the statement?

前端 未结 15 1882
广开言路
广开言路 2020-11-22 09:16

I know I\'ve done this before years ago, but I can\'t remember the syntax, and I can\'t find it anywhere due to pulling up tons of help docs and articles about \"bulk import

相关标签:
15条回答
  • 2020-11-22 09:28

    Using INSERT INTO ... VALUES syntax like in Daniel Vassallo's answer there is one annoying limitation:

    From MSDN

    The maximum number of rows that can be constructed by inserting rows directly in the VALUES list is 1000

    The easiest way to omit this limitation is to use derived table like:

    INSERT INTO dbo.Mytable(ID, Name)
    SELECT ID, Name 
    FROM (
       VALUES (1, 'a'),
              (2, 'b'),
              --...
              -- more than 1000 rows
    )sub (ID, Name);
    

    LiveDemo


    This will work starting from SQL Server 2008+

    0 讨论(0)
  • 2020-11-22 09:29
    INSERT INTO dbo.MyTable (ID, Name)
    SELECT 123, 'Timmy'
    UNION ALL
    SELECT 124, 'Jonny'
    UNION ALL
    SELECT 125, 'Sally'
    

    For SQL Server 2008, can do it in one VALUES clause exactly as per the statement in your question (you just need to add a comma to separate each values statement)...

    0 讨论(0)
  • 2020-11-22 09:32

    I've been using the following:

    INSERT INTO [TableName] (ID, Name)
    values (NEWID(), NEWID())
    GO 10
    

    It will add ten rows with unique GUIDs for ID and Name.

    Note: do not end the last line (GO 10) with ';' because it will throw error: A fatal scripting error occurred. Incorrect syntax was encountered while parsing GO.

    0 讨论(0)
  • 2020-11-22 09:34

    Corresponding to INSERT (Transact-SQL) (SQL Server 2005) you can't omit INSERT INTO dbo.Blah and have to specify it every time or use another syntax/approach,

    0 讨论(0)
  • 2020-11-22 09:38

    This looks OK for SQL Server 2008. For SS2005 & earlier, you need to repeat the VALUES statement.

    INSERT INTO dbo.MyTable (ID, Name)  
    VALUES (123, 'Timmy')  
    VALUES (124, 'Jonny')   
    VALUES (125, 'Sally')  
    

    EDIT:: My bad. You have to repeat the 'INSERT INTO' for each row in SS2005.

    INSERT INTO dbo.MyTable (ID, Name)  
    VALUES (123, 'Timmy')  
    INSERT INTO dbo.MyTable (ID, Name)  
    VALUES (124, 'Jonny')   
    INSERT INTO dbo.MyTable (ID, Name)  
    VALUES (125, 'Sally')  
    
    0 讨论(0)
  • 2020-11-22 09:40

    You could do this (ugly but it works):

    INSERT INTO dbo.MyTable (ID, Name) 
    select * from
    (
     select 123, 'Timmy'
      union all
     select 124, 'Jonny' 
      union all
     select 125, 'Sally'
     ...
    ) x
    
    0 讨论(0)
提交回复
热议问题