2016-07-31 24 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替換您的連接字符串即可。 –

相關問題