1

I currently have this function (see below) which adds answers and related content (e.g. notes) to 50 questions or so. I'm trying to make the database secure by changing it to a stored procedure so I can remove the write permission from the users. Is this the right approach?

Should I use table-valued parameters? Or should I call the stored procedure 50 times? The former feels like it's right, but the latter would look nicer in code although I expect is inefficient?

Or ... is there a better way/approach?

int AddAnswersToTable()
{
    var Cmd = Db.NewCommand();
    var Str = new StringBuilder("INSERT INTO answers (qu_id,answer,notes) VALUES");
    int i = 1;
    string Join = string.Empty;

    foreach (var Qu in Page)
    {
        Str.Append(Join);
        Str.Append("(");

        Str.Append((Name = "@qu_id" + i) + ",");
        Cmd.Parameters.AddWithValue(Name, Qu.QuId);

        Str.Append((Name = "@ans" + i) + ",");
        Cmd.Parameters.AddWithValue(Name, Qu.Answer.Truncate(499));

        Str.Append((Name = "@notes" + i) + ",");
        Cmd.Parameters.AddWithValue(Name, Qu.Notes.Truncate(499));

        Str.Append(")");
        Join = ",";
        i++;
    }

    return Cmd.ExecuteNonQuery(Str.ToString());
}

Thanks in advance.

0

2 Answers 2

1

I haven't used Table Valued Parameters so I can't say if that is the way to go. But another option would be to do batch updates using SqlDataAdapter. By setting the "UpdateBatchSize" property you can send multiple values/rows at a time.

You can read about it at MSDN: http://msdn.microsoft.com/en-us/library/aadf8fk2%28v=vs.100%29.aspx

And here is an article where a stored procedure is used: http://www.dotnetspider.com/resources/4467-Multiple-Inserts-Single-Round-trip-using-ADO-NE.aspx

0
1

Whether a stored procedure is the right approach is a religious matter. I believe it is, FWIW.

Calling the procedure 50 times is simpler, but neither approach is wrong, per se.

1
  • Interesting. I expected derision at the mere suggestion of calling multiple times!!
    – noelicus
    Oct 15, 2013 at 9:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.