Since there is no Sqlserver array parameter, what's the best way to proceed?

前端 未结 5 1163
孤独总比滥情好
孤独总比滥情好 2020-12-10 19:23

I need to create multiple records in sqlserver, each with the same value in column A, but with a unique value in column B. I have the values for column B in an array.

<
5条回答
  •  囚心锁ツ
    2020-12-10 20:13

    Both options have their advantages (option 1 is a single round-trip, option 2 doesn't use hokey string processing), but I would likely end up going with option 2. Option 1 suffers from the size limits of varchars (8000 unless you use varchar(MAX); I have no idea what the performance would be on a comma-delimited varchar(MAX) string that's terribly long).

    As far as rollback, yes, just do all of the operations on a single open connection and use a SqlTransaction object.

    For example...

    using(SqlConnection conn = new SqlConnection("connection string"))
    {
        conn.Open();
    
        using(SqlTransaction trans = conn.BeginTrasnaction())
        {
            try
            {
                using(SqlCommand cmd = new SqlCommand("command text", conn, trans))
                {
                    SqlParameter aParam = new SqlParameter("a", SqlDbType.Int);
                    SqlParameter bParam = new SqlParameter("b", SqlDbType.Int);
    
                    cmd.Parameters.Add(aParam);
                    cmd.Parameters.Add(bParam);
    
                    aParam.Value = 1;
    
                    foreach(int value in bValues)
                    {
                        bValue = value;
    
                        cmd.ExecuteNonQuery();
                    }
                }
    
                trans.Commit();
            }
            catch
            {
                trans.Rollback();
    
                throw; // so the exception can propogate up
            }
        }
    }
    

提交回复
热议问题