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

前端 未结 15 2141
广开言路
广开言路 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:49

    Others here have suggested a couple multi-record syntaxes. Expounding upon that, I suggest you insert into a temp table first, and insert your main table from there.

    The reason for this is loading the data from a query can take longer, and you may end up locking the table or pages longer than is necessary, which slows down other queries running against that table.

    -- Make a temp table with the needed columns
    select top 0 *
    into #temp
    from MyTable (nolock)
    
    -- load data into it at your leisure (nobody else is waiting for this table or these pages)
    insert #temp (ID, Name)
    values (123, 'Timmy'),
    (124, 'Jonny'),
    (125, 'Sally')
    
    -- Now that all the data is in SQL, copy it over to the real table. This runs much faster in most cases.
    insert MyTable (ID, Name)
    select ID, Name
    from #temp
    
    -- cleanup
    drop table #temp
    

    Also, your IDs should probably be identity(1,1) and you probably shouldn't be inserting them, in the vast majority of circumstances. Let SQL decide that stuff for you.

提交回复
热议问题