尝试使用以下代码填充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只读取这么长时间没有结果然后给出异常吗?我错过了什么吗?
答案 0 :(得分:1)
这对我有用,请检查一下:在查询中将表更改为[table]并使用(SqlCommand cmd = new SqlCommand(sqlGetUniqueParams,conn))更改为使用(SqlCommand cmd = new SqlCommand(sql,conn) ))
/usr/local/git/bin/git