简体   繁体   English

使用输出参数在ASP.NET中调用SQL存储过程

[英]Call a SQL stored procedure in ASP.NET with an output parameter

I'm attempting to call my sql stored procedure which takes RaceDate as an input and returns Location as an OUTPUT. 我正在尝试调用将RaceDate作为输入并返回Location作为输出的sql存储过程。 I'm not sure how to call my code in ASP.NET, this is what I have thus far. 我不确定如何在ASP.NET中调用我的代码,这就是我到目前为止所拥有的。

DateTime RaceDate = Calendar1.SelectedDate;
    // string RaceDate = TxtBoxCalendar.Text;

    TxtBoxCalendar.ReadOnly = true;

    SqlConnection con = new SqlConnection();
    con.ConnectionString = ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ToString(); 

    con.Open();
    SqlCommand Command = new SqlCommand();

    Command.CommandType = System.Data.CommandType.StoredProcedure; 
    Command.CommandText = "CheckRaceCalendarDates";

    Command.Parameters.Add("@RaceDate", SqlDbType.DateTime, RaceDate);
    Command.Parameters.Add("@Location", SqlDbType.String).Direction = ParameterDirection.Output;

    Command.Parameters.Add("@Location",SqlDbType.String).Direction = ParameterDirection.Output;

    Command.ExecuteNonQuery();
    con.Close(); 

I think i may also run into a problem with datatypes. 我认为我也可能会遇到数据类型问题。 RaceDate is a date the user clicks through a calendar and has to be converted to a string however the SQL parameter RaceDate is of type date. RaceDate是用户单击日历的日期,必须将其转换为字符串,但是SQL参数RaceDate的类型为date。

CREATE PROCEDURE [dbo].[CheckRaceCalendarDates]
@RaceDates DATE,
@Location NVARCHAR(50) OUTPUT
AS
IF EXISTS 
    (
SELECT 
    RaceCalendar.RaceDates,
    Locations.LocationName 
FROM 
    Locations
INNER JOIN RaceCalendar ON locations.LocationId = RaceCalendar.LocationId
WHERE 
    RaceCalendar.RaceDates = @RaceDates
    )

    BEGIN
SELECT 
    @Location = Locations.LocationName 
FROM 
    Locations
INNER JOIN RaceCalendar ON locations.LocationId = RaceCalendar.LocationId
WHERE 
    RaceCalendar.RaceDates = @RaceDates
    END

Your problem about using parameter name ; 您有关使用参数名称的问题; you have used @RaceDates on stored procedure but you try to use @RaceDate on code.. They should be same. 您在存储过程中使用了@RaceDates ,但是您尝试在代码中使用@RaceDate 。。它们应该相同。

Also, you need to add second parameter to your code like this ; 同样,您需要像这样在代码中添加第二个参数;

Command.Parameters.Add("@Location",SqlDbType.String).Direction = ParameterDirection.Output;

And after cmd.ExeCuteNonQuery(); 然后在cmd.ExeCuteNonQuery();之后cmd.ExeCuteNonQuery();

string location = Command.Parameters["@Location"].Value.ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM