运行环境为Visual Studio 2010,数据库为SQL Server 2008。
执行下面SQL语句
SELECT SubsiteId, SubsiteTitle, count(CollectionID) CollectionNumber,count(LName) PlantNumber
FROM (SELECT DISTINCT SubsiteId, SubsiteTitle, CollectionID, LName, CName
FROM Cumplag_Garden_Plants where lname='Agave sisalana')
group by SubsiteId, SubsiteTitle
在企业管理器中运行正常,可以查询到结果,但是放在程序中却始终提示500内部错误。以下是C#代码:
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds, "ds"); //这里出错
conn.Close();
对代码try catch也捕获不到异常。
解决方法:只要将内部子查询添加一个别名即可。
SELECT q.SubsiteId, q.SubsiteTitle, count(q.CollectionID) CollectionNumber,count(q.LName) PlantNumber
FROM (SELECT DISTINCT SubsiteId, SubsiteTitle, CollectionID, LName, CName
FROM Cumplag_Garden_Plants where lname='Agave sisalana') q
group by SubsiteId, SubsiteTitle