【发布时间】:2016-01-27 19:22:28
【问题描述】:
尝试使用以下代码填充List:
string sql = ";WITH getUniqueParams AS (" +
"SELECT DISTINCT [a] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [b] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [c] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [d] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [e] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [f] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [g] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [h] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [i] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [j] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [k] AS 'param' FROM table) " +
"SELECT DISTINCT [param] FROM getUniqueParams ORDER BY [param]"; //the result of this statement to be stored in a string
List<string> lUniqueParams = new List<string>();
// set up SQL connection and command
using (SqlConnection conn = new SqlConnection(@"Data Source=server;Initial Catalog=db;Integrated Security=SSPI"))
using (SqlCommand cmd = new SqlCommand(sqlGetUniqueParams, conn))
{
conn.Open();
// get a SqlDataReader to read multiple rows
using (SqlDataReader rdr = cmd.ExecuteReader()) //getting exception here when debugging
{
// while there are more result rows.....
while (rdr.Read())
{
// grab the 0-index value from the result row
lUniqueParams.Add(rdr.GetString(0));
}
}
conn.Close();
conn.Dispose();
}
我在以下代码行遇到异常:
using (SqlDataReader rdr = cmd.ExecuteReader())
我的查询在语法上不正确吗?查询表现不好,rdr是不是只读了这么久没有结果,然后给出异常?我错过了什么吗?
【问题讨论】:
-
表格有多少行?尝试删除
distinct关键字,使用union而不是union all并删除排序。 -
表格有260行
-
那么你的表可能被锁定了。尝试使用
nolock看看。 260 行不算什么... -
什么异常?当您直接在 Management Studio 中运行查询时会发生什么?
-
添加
cmd.CommandTimeout= 0;并检查。
标签: c# sql sql-server list populate