我试图从C#中的存储过程中获取返回值,但它总是返回{}。我的代码如下:
SqlCommand cmd = new SqlCommand ( );
cmd.CommandText = "EXEC dbo.verifyEmailDomain @Domain, @RESULT";
cmd.Connection = con;
SqlParameter domain_p = new SqlParameter ( "@Domain", SqlDbType.NVarChar );
domain_p.Value = domain;
cmd.Parameters.Add ( domain_p );
SqlParameter ret = new SqlParameter("@RESULT", SqlDbType.Int);
ret.Direction = ParameterDirection.Output;
cmd.Parameters.Add ( ret );
con.Open ( );
cmd.ExecuteNonQuery ( );
var value = cmd.Parameters ["@RESULT"].Value;
con.Close ( );
我也试图设置“ret.Direction = ParamaterDirection.ReturnValue”无济于事
存储过程如下:
ALTER PROCEDURE [dbo].[verifyEmailDomain]
-- Add the parameters for the stored procedure here
@Domain nvarchar(200),
@RESULT INT OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT @RESULT = COUNT(*)
FROM Josh.dbo.refDomains
WHERE LOWER(EMAIL_DOMAIN)=LOWER(@Domain)
RETURN @RESULT
END
答案 0 :(得分:2)
如果使用输出参数调用存储过程,则需要告诉它:
cmd.CommandText = "EXEC dbo.verifyEmailDomain @Domain, @RESULT OUTPUT";
只需指定程序名称即可省去麻烦:
cmd.CommandText = "dbo.verifyEmailDomain";
cmd.CommandType = CommandType.StoredProcedure;
答案 1 :(得分:1)
不是创建另一个名为return的变量,为什么不直接返回select语句?
ALTER PROCEDURE [dbo].[verifyEmailDomain]
-- Add the parameters for the stored procedure here
@Domain nvarchar(200),
AS
BEGIN
SET NOCOUNT ON;
RETURN(SELECT COUNT(*)
FROM Josh.dbo.refDomains
WHERE LOWER(EMAIL_DOMAIN)=LOWER(@Domain))
END
然后更改此代码:
SqlCommand cmd = new SqlCommand ( );
cmd.CommandText = "EXEC dbo.verifyEmailDomain @Domain, @RESULT";
cmd.Connection = con;
看起来像这样:
SqlCommand cmd = new SqlCommand ( );
cmd.CommandText = "dbo.verifyEmailDomain";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
而且:
SqlParameter ret = new SqlParameter("@RESULT", SqlDbType.Int);
ret.Direction = ParameterDirection.Output;
cmd.Parameters.Add ( ret );
看起来像这样:
SqlParameter ret = new SqlParameter();
ret.Direction = ParameterDirection.ReturnValue;
ret.ParameterName = "@RESULT";
cmd.Parameters.Add(ret);
此时,你的sql返回@Return的值和返回值,它们都是同一个东西。我觉得有点无意义:)。