What is the best way to auto-generate INSERT statements for a SQL Server table?

前端 未结 23 1393
难免孤独
难免孤独 2020-11-22 09:47

We are writing a new application, and while testing, we will need a bunch of dummy data. I\'ve added that data by using MS Access to dump excel files into the relevant table

23条回答
  •  长情又很酷
    2020-11-22 10:11

    The first link to sp_generate_inserts is pretty cool, here is a really simple version:

    DECLARE @Fields VARCHAR(max); SET @Fields = '[QueueName], [iSort]' -- your fields, keep []
    DECLARE @Table  VARCHAR(max); SET @Table  = 'Queues'               -- your table
    
    DECLARE @SQL    VARCHAR(max)
    SET @SQL = 'DECLARE @S VARCHAR(MAX)
    SELECT @S = ISNULL(@S + '' UNION '', ''INSERT INTO ' + @Table + '(' + @Fields + ')'') + CHAR(13) + CHAR(10) + 
     ''SELECT '' + ' + REPLACE(REPLACE(REPLACE(@Fields, ',', ' + '', '' + '), '[', ''''''''' + CAST('),']',' AS VARCHAR(max)) + ''''''''') +' FROM ' + @Table + '
    PRINT @S'
    
    EXEC (@SQL)
    

    On my system, I get this result:

    INSERT INTO Queues([QueueName], [iSort])
    SELECT 'WD: Auto Capture', '10' UNION 
    SELECT 'Car/Lar', '11' UNION 
    SELECT 'Scan Line', '21' UNION 
    SELECT 'OCR', '22' UNION 
    SELECT 'Dynamic Template', '23' UNION 
    SELECT 'Fix MICR', '41' UNION 
    SELECT 'Fix MICR (Supervisor)', '42' UNION 
    SELECT 'Foreign MICR', '43' UNION 
    ...
    

提交回复
热议问题