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

前端 未结 15 2142
广开言路
广开言路 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条回答
  •  猫巷女王i
    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();
            }
    

提交回复
热议问题