-5

I have created a list in c#, now I need to insert the list into SQL Server 2008. Is this possible? please explain with a simple example.

3

1 Answer 1

6

Here's a simple example:

List<String> list = new List<String>() { "A", "B", "C" };
using (var con = new SqlConnection(connectionString))
{
    con.Open();
    using (var cmd = new SqlCommand("INSERT INTO TABLE(Column)VALUES(@Column)", con))
    {
        cmd.Parameters.Add("@Column", SqlDbType.VarChar);
        foreach (var value in list)
        {
            cmd.Parameters["@Column"].Value = value;
            int rowsAffected = cmd.ExecuteNonQuery();
        }
    }
}

This just loops through all items in the list and executes one insert-command after the other with ExecuteNonQuery.

Edit: If you want to know the most efficient ways to insert arrays(or lists) into sql-server, you should definitely read this: http://www.sommarskog.se/arrays-in-sql-2008.html

If you have a specific question later, you can come back and show what you've tried.

Sign up to request clarification or add additional context in comments.

8 Comments

Well, that's not really an efficient way to insert a list, that's just a way to loop through a list and insert one at a time. A TVP would be a much more attractive option. :-)
@AaronBertrand: I wanted to show a simple example since i've assumed that OP just wants to insert his 1-dimensional list(one field). There was no requirement for the most efficient way ;) If he wants to know how to handle lists(arrays) most efficiently he should read this: sommarskog.se/arrays-in-sql-2008.html
My database has 30 columns, but what I have in list is only 20 columns and it grows dynamically based upon user. Now, How to do the insert?
@user1671639 you need to start with a tutorial (a search can yield these pretty easily), then come back here with problems when you've written some code and can't quite get it to work. This isn't a "write my code for me" site.
I missed to pick this answer sorry for being too late :( Thank you :)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.