如何获取存储过程的返回值 [英] How to get Return Value of a Stored Procedure
问题描述
可能是一个容易回答的问题.我有这个程序:
Probably an easy-to-answer question. I have this procedure:
CREATE PROCEDURE [dbo].[AccountExists]
@UserName nvarchar(16)
AS
IF EXISTS (SELECT Id FROM Account WHERE UserName=@UserName)
SELECT 1
ELSE SELECT 0
当我有调用此过程并执行此操作的 ADO.NET 代码时:
When I have ADO.NET code that calls this procedure and does this:
return Convert.ToBoolean(sproc.ExecuteScalar());
返回 true 或 false.
Either true or false is returned.
当我将存储过程更改为 RETURN 1 或 0 而不是 SELECT 时:
When I change the stored procedure to RETURN 1 or 0 instead of SELECT:
ALTER PROCEDURE [dbo].[AccountExists]
@UserName nvarchar(16)
AS
IF EXISTS (SELECT Id FROM Account WHERE UserName=@UserName)
RETURN 1
ELSE RETURN 0
sproc.ExecuteScalar() 返回 null.如果我改为尝试 sproc.ExecuteNonQuery(),则返回 -1.
sproc.ExecuteScalar() returns null. If I try sproc.ExecuteNonQuery() instead, -1 is returned.
如何在 ADO.NET 中获取带有 RETURN 的存储过程的结果?
我需要 AccountExists 来 RETURN 而不是 SELECT 以便我可以有另一个存储过程调用它:
I need AccountExists to RETURN instead of SELECT so I can have another stored procedure call it:
--another procedure to insert or update account
DECLARE @exists bit
EXEC @exists = [dbo].[AccountExists] @UserName
IF @exists=1
--update account
ELSE
--insert acocunt
推荐答案
添加参数,使用 ParameterDirection.ReturnValue
.执行后返回值会出现在参数中.
Add a parameter, using ParameterDirection.ReturnValue
. The return value will be present in the paramter after the execution.
这篇关于如何获取存储过程的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!