Search code examples
c#postgresqlnpgsqlidbconnection

IDBCommand Parameters for multi-line insert


I want to create a multi-line insert statement along these lines:

insert into foo (
    value1,
    value2,
    value3
) values 
( "1", "2", "3"),
( "4", "5", "6"),
( "7", "8", "9");

where the number of rows to be inserted is variable. Is there a way to construct this query using IDBCommand parameterization?


Solution

  • Something like this should work fine.

    IDbCommand cmd = new SqlCommand();
    StringBuilder sb = new StringBuilder();
    sb.Append("insert into foo(col, col2, col3), values");
    int parms = 0;
    
    for(int i = 0 ; i<3; i++)
    {
        sb.AppendFormat("( @{0}, @{1}, @{2}),", parms, parms + 1, parms + 2);
        cmd.Parameters.Add(new SqlParameter((parms++).ToString(), ""));
        cmd.Parameters.Add(new SqlParameter((parms++).ToString(), ""));
        cmd.Parameters.Add(new SqlParameter((parms++).ToString(), ""));
    }
    sb.Append(";");
    cmd.Parameters;
    cmd.CommandText = sb.ToString().Replace(",;", ";");