1

I'm trying to have (unknown amount) multiple values put in the database (Using ASP.NET MVC - C#), creating a query like:

INSERT INTO [dbo].[names](name, lastname) 
VALUES ("Foo", "Bar"), 
       ("John, "Smith"),
       ("Var", "Dar")

which in C# code looks like so:

//conn is an SqlConnection object
using (var cmd = conn.CreateCommand())
{
    cmd.CommandText = @"INSERT INTO [dbo].[names](name, lastname) VALUES ";
    //The reason it goes backwards is because this is only simplified insert query,
    //real query also does some sorting, which does Not cause the issue.
    for (int i = articleFullList.Count - 1; i > 0; i--)
    {
        cmd.CommandText += "(@firstname" + i + ", @lastname" + i + ")";
        if(i > 0)
            cmd.CommandText += ", ";
        cmd.Parameters.AddWithValue("@firstname" + i, someFirstNameValue);
        cmd.Parameters.AddWithValue("@lastname" + i, someLastNameValue);
    } 
}

But I always get a

Syntax error near ,

error, but if I remove the if(i > 0) statement (and line below it) I get a similar error

Syntax error near @firstname1

Thanks for reading!

Toza
  • 1,348
  • 2
  • 14
  • 35

1 Answers1

3

The loop must continue until reaches zero:

for (int i = articleFullList.Count - 1; i >= 0; i--) 
Taher Rahgooy
  • 6,528
  • 3
  • 19
  • 30
  • Such a simple solution unseen for such a long time...I'm ashamed. Thank you @Taher, I'll check out if it works in a bit and give you a positive review. – Toza Aug 26 '15 at 06:40
  • Sorry for the wait, the solution works perfectly :) It's a confirmed answer. – Toza Aug 26 '15 at 07:20