簡體   English   中英

SqlDataReader不從SQL Server存儲過程返回任何數據

[英]SqlDataReader not returning any data from SQL Server stored procedure

我的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();
    }
}
string strDBNme = (string)sdrData["stateabbrev"];
       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();
            }
        }   
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();
                 }
             }
         }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM