I want to extracing a column from a database and save it into a list. Now it works but NULL value.
The column vlues in the original database are:
19506
19022
117037
NULL
1680
70659
1666
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
8113
NULL
You see there are a lot of “NULL”. I only want to get one “NULL”. My code’s result got many empty strings.
"19506"
"19022"
"117037"
""
"1680"
"70659"
"1666"
""
""
""
""
""
""
""
""
""
""
"8113"
""
What I want is:
"19506"
"19022"
"117037"
""
"1680"
"70659"
"1666"
"8113"
My code:
public static List<string> ExecuteReader(string commandtext,string col)
{
List<string> sRetVal = new List<string>();
try
{
using (SqlConnection cnn = new SqlConnection(conn))
{
cnn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cnn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = commandtext;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
sRetVal.Add(reader[col].ToString());
}
}
}
cnn.Close();
}
}
catch (Exception ex)
{
}
return sRetVal.ToList().Distinct().ToList();
}
Thanks.
UPDATED:
string commandtext = "select QO FROM [T1]";
Do the
DISTINCTin the database, and it will handle this for you automatically:COALESCE: