SQL查询可在SQL Server 2008中使用,但不适用于;我不能在C#中工作

本文关键字:SQL 适用于 不能 工作 不适用 查询 Server 2008 | 更新日期: 2023-09-27 17:58:28

我正在开发一个应用程序,必须从数据库中检索一些数据。我正在使用以下查询。

SELECT DISTINCT Context.ContextId, ContextName 
FROM Context
INNER JOIN RunInstance 
   ON Context.ContextId IN 
      (SELECT RunInstance.ContextId 
       FROM RunInstance 
       INNER JOIN ProcessInstance 
          ON RunInstance.RunInstanceId 
             IN (SELECT RunInstanceId FROM ProcessInstance 
                 WHERE RiskDate = '2010-08-20' )); 

此查询在SQL Server 2008中运行良好。

然而,当我把它放在C#应用程序中时,它并没有向我显示任何输出。

我的代码:

string squery = @"SELECT DISTINCT Context.ContextId, ContextName FROM Context INNER JOIN RunInstance ON Context.ContextId IN 
    (Select RunInstance.ContextId From RunInstance 
    INNER JOIN ProcessInstance ON RunInstance.RunInstanceId 
    IN (SELECT RunInstanceId FROM ProcessInstance Where 
    RiskDate = '2010-08-20' )); ";
using(SqlConnection sqcon = new SqlConnection("Data Source=WMLON-Z8-SQL20,61433;Initial Catalog=statusdb;Integrated Security=True")){
    sqcon.Open();
    using(SqlCommand command = new SqlCommand(squery,sqcon))
        using(SqlDataReader reader = command.ExecuteReader()){
            while(reader.Read()){
                Console.WriteLine(reader[0]+"'t"+reader[1]);
            }
        }
}     

有人能告诉我问题出在哪里吗?

SQL查询可在SQL Server 2008中使用,但不适用于;我不能在C#中工作

请将CommandText放入CommandType并尝试。

using(SqlConnection sqcon = new SqlConnection(
"Data Source=WMLON-Z8-SQL20,61433;Initial Catalog=statusdb;Integrated Security=True"))
{
   using(SqlCommand command = new SqlCommand(squery,sqcon)){
      command.CommandType = CommandType.Text;
      sqcon.Open();
      using(SqlDataReader reader = command.ExecuteReader())
      {
          while(reader.Read()){
            Console.WriteLine(reader[0]+"'t"+reader[1]);
          }
      }
      sqcon.Close();
   }
} 
-- Using EXISTS or IN could improve your query
    SELECT DISTINCT
            Context.ContextId ,
            ContextName
    FROM    Context
            INNER JOIN RunInstance ON Context.ContextId = RunInstance.ContextId 
            INNER JOIN ProcessInstance ON RunInstance.RunInstanceId = ProcessInstance.RunInstanceId
    WHERE   RiskDate = '2010-08-20'