SqlDataReader不从SQL Server存储过程返回任何数据

时间:2016-07-31 17:43:14

标签: c# sql-server wpf stored-procedures

我的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();
    }
}

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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();
            }
        }   

答案 2 :(得分: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();
                 }
             }
         }