简体   繁体   English

无法从存储过程中获取值

[英]Unable to get value from a stored procedure

I am trying to get the value from a stored procedure, below is my code 我试图从存储过程中获取值,下面是我的代码

SqlConnection connection = new SqlConnection("");
connection.Open();
DataTable timeZoneDt = new DataTable();
var sqlCommand = new SqlCommand("GetTimeZoneGMT", connection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add("@TimeZone", SqlDbType.NVarChar).Value = "Asia/Kuala_Lumpur";
//timeZoneDt.Load(sqlCommand.ExecuteReader());
//new SqlDataAdapter(sqlCommand).Fill(timeZoneDt);

var reader2 = sqlCommand.ExecuteReader();


while (reader2.Read())
{
    var ID = int.Parse(reader2[0].ToString());
}
connection.Close();

the following is my stored procedure, 以下是我的存储过程,

/****** Object:  StoredProcedure [dbo].[GetTimeZoneGMT]    Script Date: 23/4/2018 4:05:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


ALTER PROCEDURE [dbo].[GetTimeZoneGMT]
    @TimeZone NVARCHAR(128)
AS
BEGIN
 DECLARE @timeZoneNumber as INT = -20;
 IF @TimeZone ='Pacific/Midway'
 SET @timeZoneNumber = -11
 ELSE IF @TimeZone ='Pacific/Niue'
 SET @timeZoneNumber = -11
 ELSE IF @TimeZone ='Pacific/Pago_Pago'
 SET @timeZoneNumber = -11

 RETURN @timeZoneNumber;
END

I cannot write it all to you all because the timezone have 400 rows, however it is similiar like this. 我不能把它全部写给大家,因为时区有400行,但它类似于此。

However, when i get my c# code, it is empty value, why? 但是,当我得到我的c#代码时,它是空值,为什么? whats wrong with the code 什么错误的代码

截图Visual Studio

You need to declare a parameter for the ReturnValue even if you don't have it in your Stored Procedure declaration. 您需要为ReturnValue声明一个参数,即使您在存储过程声明中没有它也是如此。 You can name the parameter whatever you like but you should mark it as ParameterDirection.ReturnValue . 您可以根据需要为参数命名,但应将其标记为ParameterDirection.ReturnValue

SqlParameter r = cmd.Parameters.Add("@timeZoneNumber", SqlDbType.Int);
r.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();

int result = Convert.ToInt32(r.Value);

Notice that you don't need to call ExecuteReader but just ExecuteNonQuery. 请注意,您不需要调用ExecuteReader,只需要调用ExecuteNonQuery。

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

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