locked
Declaring variables for INSERT RRS feed

  • Question

  • User-981963818 posted

    I need to dynamically create an insert statement. (Where the fields, and number of fields are dynamic)

    If I am doing an insert command like this:

    var sql = "INSERT INTO Test(Field1, Field2, Field3) VALUES (@0, @1, @2)";
    db.Execute(sql, vals[0], vals[1], vals[2]);

    I am able to dynamically create the Insert statement since it is a string, but I am not sure how to do this with the Execute.

    I thought maybe I could try

    // var Array = vals[0], vals[1], vals[2]
    db.Execute(sql, Array);

    or

    // var Array = vals[0], vals[1], vals[2]
    db.Execute(sql, @Array);

    but it just says: Must declare the scalar variable "@1".

    It this possible to do, or do I need to perform the insert another way?

    Thursday, September 4, 2014 3:26 PM

Answers

  • User-1360095595 posted

    Yes, I think you can pass an array. In your first code sample, it would be:

    db.Execute(sql, vals);

    Does that work?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 4, 2014 3:29 PM

All replies

  • User-1360095595 posted

    Yes, I think you can pass an array. In your first code sample, it would be:

    db.Execute(sql, vals);

    Does that work?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 4, 2014 3:29 PM
  • User-981963818 posted

    Thanks, that worked. I would call that an oversight on my part.

    Thursday, September 4, 2014 3:59 PM