Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate List<String> from SQL query?

If I have a DbCommand defined to execute something like:

SELECT Column1 FROM Table1

What is the best way to generate a List<String> of the returned records?

No Linq etc. as I am using VS2005.

like image 973
CJ7 Avatar asked Aug 19 '12 04:08

CJ7


People also ask

How do I create a list of strings in SQL?

You can create lists of SQL Query or Fixed Data values . In the Data Model components pane, click List of Values and then click Create new List of Values. Enter a Name for the list and select a Type.

How do I print a list in SQL?

Declare @SumVal int; Select @SumVal=Sum(Amount) From Expense; Print @SumVal; You can, of course, print any number of fields from the table in this way. Of course, if you want to print all of the results from a query that returns multiple rows, you'd just direct your output appropriately (e.g. to Text).

How do I create a list to a table in SQL?

To insert a row into a table, you need to specify three things: First, the table, which you want to insert a new row, in the INSERT INTO clause. Second, a comma-separated list of columns in the table surrounded by parentheses. Third, a comma-separated list of values surrounded by parentheses in the VALUES clause.

Can I Make my query results appear as a list in SQL?

Starting with SQL Server 2017, you can now make your query results appear as a list. This means you can have your result set appear as a comma-separated list, a space-separated list, or whatever separator you choose to use. While it’s true that you could achieve this same effect prior to SQL Server 2017, it was a bit fiddly.

How to get the list position of a list in SQL?

If you on are SQL 2016 or later, and you need the list position but you cannot write your own function, there is an option that is easier to use than XML, to wit JSON: DECLARE @list nvarchar(MAX) = '1,99,22,33,45' SELECT convert(int, [key]) + 1 AS listpos, convert(int, value) AS n FROM OPENJSON('[' + @list + ']')

How to pair values from lists in SQL Server?

To pair the values from the lists, we synchronise them on the listposcolumn. Say now that you need to update one of the values in the list. Well, didn't I tell you: you need to change the design so that the delimited list becomes a child table?

How to create comma delimited list from a list in SQL?

'Build your Comma-delimited list using the values from your List' Dim values = String.Join (",",myList.ToArray ()) 'Add the values of your comma delimited list into your string' Dim ssql As String = String.Format ("SELECT * FROM table WHERE myId IN ( {0})",values)


2 Answers

I think this is what you're looking for.

List<String> columnData = new List<String>();

using(SqlConnection connection = new SqlConnection("conn_string"))
{
    connection.Open();
    string query = "SELECT Column1 FROM Table1";
    using(SqlCommand command = new SqlCommand(query, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                columnData.Add(reader.GetString(0));
            }         
        }
    }
}

Not tested, but this should work fine.

like image 161
Chuck Callebs Avatar answered Oct 19 '22 19:10

Chuck Callebs


Loop through the Items and Add to the Collection. You can use the Add method

List<string>items=new List<string>();
using (var con= new SqlConnection("yourConnectionStringHere")
{
    string qry="SELECT Column1 FROM Table1";
    var cmd= new SqlCommand(qry, con);
    cmd.CommandType = CommandType.Text;
    con.Open();
    using (SqlDataReader objReader = cmd.ExecuteReader())
    {
        if (objReader.HasRows)
        {              
            while (objReader.Read())
            {
              //I would also check for DB.Null here before reading the value.
               string item= objReader.GetString(objReader.GetOrdinal("Column1"));
               items.Add(item);                  
            }
        }
    }
}
like image 5
Shyju Avatar answered Oct 19 '22 19:10

Shyju