2016-07-31 8 views
0

から任意のデータを返さない:ここではSqlDataReaderのは、私は罰金を実行私のSQL Serverデータベースに次のストアドプロシージャを持っている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 Serverへの呼び出しをトレースし、呼び出しがどうなるかを確認する方法はありますか? – Cass

+0

私が投稿した新しい答えを見てください。それは動作し、テストされています。コードを変更する必要があります。 SQLコマンド文の前に接続を開きます。 SqlConn.openConnection()。次の変更はwhileループ内にあります。string strDBNme =(文字列)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に置き換えてください。 –

関連する問題