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
When I have ADO.NET code that calls this procedure and does this:
return Convert.ToBoolean(sproc.ExecuteScalar());
Either true or false is returned.
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() returns null. If I try sproc.ExecuteNonQuery() instead, -1 is returned.
How do I get the result of a stored procedure with a RETURN in ADO.NET?
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
I tried the other solutions with my setup and they did not work but I'm using VB6 & ADO 6.x. I also want to point out that a proc return of 0 indicates successful. Don't forget there are functions available too which don't have that convention. Found this on MSDN and it did work for me:
The results will appear in the immediate window when running this (Debug.Print)
ExecuteScalar returns the first column of the first row. Since you were no longer selecting, and creating a resultset, that is why it was returning null. Just as FYI. John Saunders has the correct answer.
If you are planing on using it like the example below AccountExists might be better off as a function.
Otherwise you should still be able to get the result of the stored procedure by calling it from another one by doing a select on the result.
Several ways are possible to get values back using VBA:
My code demonstrates all four. Here is a stored procedure that returns a value:
Here is the sub I use in Excel VBA. You'll need reference to Microsoft ActiveX Data Objects 2.8 Library.
Just some advice, but by default, a Stored Procedure returns 0 unless you specify something else. For this reason, 0 is often used to designate success and non-zero values are used to specify return error conditions. I would go with John's suggestion, or use an
output parameter
Add a parameter, using
ParameterDirection.ReturnValue
. The return value will be present in the paramter after the execution.