简体   繁体   中英

SQL query works in SQL Server 2008 but doesn't work in C#

I am working on an application and I have to retrieve some data from the database. I am using the following query.

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' )); 

This query works perfectly in SQL Server 2008.

However, when I put it in my C# application it is not showing me any output.

My code:

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]);
            }
        }
}     

Can anyone tell me what is the problem is?

Please put CommandText to CommandType and try it.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM