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

前端 未结 15 1883
广开言路
广开言路 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:50
    USE YourDB
    GO
    INSERT INTO MyTable (FirstCol, SecondCol)
    SELECT 'First' ,1
    UNION ALL
    SELECT 'Second' ,2
    UNION ALL
    SELECT 'Third' ,3
    UNION ALL
    SELECT 'Fourth' ,4
    UNION ALL
    SELECT 'Fifth' ,5
    GO
    

    OR YOU CAN USE ANOTHER WAY

    INSERT INTO MyTable (FirstCol, SecondCol)
    VALUES 
    ('First',1),
    ('Second',2),
    ('Third',3),
    ('Fourth',4),
    ('Fifth',5)
    
    0 讨论(0)
  • 2020-11-22 09:51

    Your syntax almost works in SQL Server 2008 (but not in SQL Server 20051):

    CREATE TABLE MyTable (id int, name char(10));
    
    INSERT INTO MyTable (id, name) VALUES (1, 'Bob'), (2, 'Peter'), (3, 'Joe');
    
    SELECT * FROM MyTable;
    
    id |  name
    ---+---------
    1  |  Bob       
    2  |  Peter     
    3  |  Joe       
    

    1 When the question was answered, it was not made evident that the question was referring to SQL Server 2005. I am leaving this answer here, since I believe it is still relevant.

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

    This is working very fast,and efficient in SQL. Suppose you have Table Sample with 4 column a,b,c,d where a,b,d are int and c column is Varchar(50).

    CREATE TABLE [dbo].[Sample](
    [a] [int] NULL,
    [b] [int] NULL,
    [c] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [D] [int] NULL
    )
    

    So you cant inset multiple records in this table using following query without repeating insert statement,

    DECLARE @LIST VARCHAR(MAX)
    SET @LIST='SELECT 1, 1, ''Charan Ghate'',11
         SELECT 2,2, ''Mahesh More'',12
         SELECT 3,3,''Mahesh Nikam'',13
         SELECT 4,4, ''Jay Kadam'',14'
    INSERT SAMPLE (a, b, c,d) EXEC(@LIST)
    

    Also With C# using SqlBulkCopy bulkcopy = new SqlBulkCopy(con)

    You can insert 10 rows at a time

       DataTable dt = new DataTable();
            dt.Columns.Add("a");
            dt.Columns.Add("b");
            dt.Columns.Add("c");
            dt.Columns.Add("d");
            for (int i = 0; i < 10; i++)
            {
                DataRow dr = dt.NewRow();
                dr["a"] = 1;
                dr["b"] = 2;
                dr["c"] = "Charan";
                dr["d"] = 4;
                dt.Rows.Add(dr);
            }
            SqlConnection con = new SqlConnection("Connection String");
            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(con))
            {
                con.Open();
                bulkcopy.DestinationTableName = "Sample";
                bulkcopy.WriteToServer(dt);
                con.Close();
            }
    
    0 讨论(0)
提交回复
热议问题