2016-07-31 120 views
0

任何数据我有我的SQL Server数据库中的以下存储过程,其执行罚款:SqlDataReader的不返回从SQL Server存储过程

SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 

CREATE PROCEDURE [dbo].[LoadStates] 
AS 
BEGIN 
    SELECT stateabbrev 
    FROM states 
    ORDER BY stateabbrev 
END 
GO 

这里是我的C#代码; sdrData已被初始化,似乎是正确的,但结果集是空的。请帮忙。

using (SqlCommand sqlCmd = new SqlCommand("LoadStates", sqlConn)) 
{ 
    sqlCmd.CommandType = CommandType.StoredProcedure; 

    // set up the parameters that the Stored Procedure expects 
    //sqlCmd.Parameters.Add("@States", SqlDbType.Char, 2).Direction = ParameterDirection.Output; 

    using (SqlDataReader sdrData = sqlCmd.ExecuteReader()) 
    { 
     while (sdrData.Read()) 
     { 
      string strDBNme = sdrData.ToString(); 
      //string strDBNme = (string)sdrData["States"]; 
      cmbxACState.Items.Add(strDBNme); 
     } 

     sdrData.Close(); 
    } 
} 

回答

0
 SqlDataReader sdrData = null; 
     // create a connection object 
     SqlConnection conn = new SqlConnection(create your sql connection string here); 

// create a command object 
    SqlCommand cmd = new SqlCommand("LoadStates", conn); 
    sqlCmd.CommandType = CommandType.StoredProcedure; 
     try 
     { 
      // open the connection 
      conn.Open();     
      sdrData = cmd.ExecuteReader(); 
      while (sdrData.Read()) 
        { 
         //string strDBNme = sdrData.ToString(); 
         string strDBNme = (string)sdrData["States"]; 
         cmbxACState.Items.Add(strDBNme); 
        } 

     } 
     finally 
     { 
      // 3. close the reader 
      if (sdrData != null) 
      { 
       sdrData.Close(); 
      } 

      // close the connection 
      if (conn != null) 
      { 
       conn.Close(); 
      } 
     } 
+0

#Ramdeo angh - 我试过了,结果仍然一样。我的连接字符串已经打开,我在之前的一个步骤中完成。有没有办法跟踪对sql服务器的调用,看看调用会发生什么? – Cass

+0

看看我发布的新答案。它的工作和测试。你需要改变你的代码。在SQL命令语句之前打开您的连接。 SqlConn.openConnection()。接下来的改变是在while循环中.. string strDBNme =(string)sdrData [“stateabbrev”];在国家的地方需要把stateabbrev。 –

0
string strDBNme = (string)sdrData["stateabbrev"]; 
+0

我没有得到这个说法,串strDBNme =(字符串)sdrData [ “stateabbrev”] ;. sdrData.Read()不返回anythig – Cass

+0

您可以使用像这样的数字索引器来提取行的每一列,但它不可读。所以使用列名。 –

0
string connectionString = ConfigurationManager.ConnectionStrings["StackDemo"] 
       .ConnectionString; 
     using (SqlConnection connection = new SqlConnection(connectionString)) 
     { 

      connection.Open(); 
      using (SqlCommand cmd = new SqlCommand("LoadStates", connection)) 
      { 
       cmd.CommandType = CommandType.StoredProcedure; 


       using (SqlDataReader sdrData = cmd.ExecuteReader()) 
       { 
        while (sdrData.Read()) 
        { 
         Console.WriteLine((string)sdrData["stateabbrev"]); 

        } 

        sdrData.Close(); 
       } 
      } 
     } 
+0

它的工作演示。只需用StackDemo替换您的连接字符串即可。 –