Dynamic parametized sql insert - is this a good idea?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • z1freeride
    New Member
    • Feb 2009
    • 36

    #1

    Dynamic parametized sql insert - is this a good idea?

    I wanted to build an insert sql statement with an unknown number of values. Would this be better as a stored procedure? Is it possible to do this as a stored procedure?

    Code:
    public static string sqlInsert(string table, ArrayList values, int numValues)
    {
        string result = String.empty;
        string sqlValues = String.Empty;
        for (int i = 1; i <= numValues; i++)
        {
            if (i < numValues)
            {
                sqlValues += "@val" + i + ",";
            }
            else
            {
                sqlValues += "@val" + i;
            }
        }
        string sql = "insert into dbo." + table + " values (" + sqlValues + ")";
    
        SqlConnection conSql = new SqlConnection(ConnStr);            
        SqlCommand sc = new SqlCommand(sql, conSql);
    
        int j = 1;
        foreach (string value in values)
        {
            if (String.IsNullOrEmpty(value))
            {
                sc.Parameters.AddWithValue("@val" + j, DBNull.Value);
            }
            else
            {
                sc.Parameters.AddWithValue("@val" + j, value);
            }
            j++;
        }
    
        try
        {
            sc.Connection.Open();
            sc.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            result = ex.Message;
        }
        finally
        {
            sc.Connection.Close();
        }
        return result;
    }
Working...