从不需要参数的存储过程中获取值

问题描述 投票:0回答:3

我有一个如下所示的存储过程,该存储过程从数据库中检索前3行。

存储过程

USE [PaydayLunch]
GO
/****** Object:  StoredProcedure [dbo].[GetPastPlaces]    Script Date: 27/10/15 12:28:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetPastPlaces]
AS
SELECT TOP 3* From Past_Places
  order by id desc

我的数据库具有以下列:

  • ID
  • Past_Place
  • Click_Date

我想从数据库的第一行中获取'Months'值,但是我不知道如何在我的代码后面写这个值,因为我发现所有解决方案都填充了gridview或参数中不需要,也不需要它们。

我需要此值,以便可以在我的视图的IF语句中使用它。

请注意,我确实必须遵循使用另一个存储过程更新表的代码。

protected void BtnDecideForMe_Click(object sender, EventArgs e)
{
    string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
    SqlConnection conn = new SqlConnection(connection);

    using (SqlCommand cmd = new SqlCommand("dbo.GetRandomPlace", conn))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        // Sets up the parameter
        cmd.Parameters.Add("@OutputVar", SqlDbType.VarChar, 25).Direction = ParameterDirection.Output;

        // Opens the SQL connection & execute's the 'GetRandomPlace' sproc
        conn.Open();
        cmd.ExecuteNonQuery();

        // Reads the output value from @OutputVar in the sproc
        string place = Convert.ToString(cmd.Parameters["@OutputVar"].Value);
        conn.Close();

        // Populates the input field
        txtDestination.Text = place;
    }

    // Generates & updates past places table
    SqlPastPlaces.InsertParameters["Past_Place"].DefaultValue = ((TextBox)txtDestination).Text;
    SqlPastPlaces.InsertParameters["Month"].DefaultValue = DateTime.Now.ToString("MMMM");
    SqlPastPlaces.InsertParameters["Click_Date"].DefaultValue = DateTime.Now.ToString();

    SqlPastPlaces.Insert();
}
c# sql asp.net ado.net sqldatareader
3个回答
1
投票

使用阅读器:

SqlConnection connection = new SqlConnection(ConnectionString);

command = new SqlCommand("TestProcedure", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
connection.Open();
reader = command.ExecuteReader();

List<Test> TestList = new List<Test>();
Test test;

while (reader.Read())
{
    test = new Test();
    test.ID = int.Parse(reader["ID"].ToString());
    test.Name = reader["Name"].ToString();
    TestList.Add(test);
}
connection.Close();

1
投票

您的问题是您使用的是ExecuteNonQuery(),它本质上会忽略您可能会获取的任何数据。您需要在过程中添加输出参数,或者使用SqlCommand.ExecuteReader找回数据读取器,然后从中读取信息。


0
投票

使用以下方法进行管理

SqlCommand.ExecuteReader
© www.soinside.com 2019 - 2024. All rights reserved.