Thursday, January 11, 2007

get RETURN VALUE from SYBASE stored procedure [Also apply to MSSQL2000]

http://forums.asp.net/thread/1333707.aspx

I can handle the returned value base on the storedProcedure conduct in MSSQL2000 with the following code:
ASP.NET
try
{
storedProcCommand.CommandType = CommandType.StoredProcedure;
storedProcCommand.Parameters.Add("@userid", Session["UserName"].ToString());
storedProcCommand.Parameters.Add("@buddyid", tbNewBuddy.Text);
cn.Open();

if (Convert.ToString(storedProcCommand.ExecuteScalar()) == "Success")
{
lbDisplay.Text = "New buddy added. / />
}
else
{
lbDisplay.Text = "Sorry, there is no such buddy. / />
}
}// end try
catch (Exception ex)
{
lbDisplay.Text = ex.ToString() + @" / />
}
finally
{
cn.Close();
}

Stored Procedure in SQL2000
CREATE PROCEDURE userBuddyAdd
@userid nvarchar(50),
@buddyid nvarchar(50)

With Recompile
AS
Declare
@intCheckBuddyExist int,
@intCheckAdd int,
@intSameUserId int
-- Check if buddy exist in the userinfo
Select @intCheckBuddyExist = count(*) from userinfo where userid = @buddyid

-- Check if the buddy id is user id
Select @intSameUserId = count(*) from userbuddy where userid = @userid and userid = @buddyid

-- Check if buddy already added
Select @intCheckAdd = count(*) from userbuddy where userid = @userid and buddyid = @buddyid

-- Add Buddy only if not been added
if @intCheckBuddyExist = 1 and @intCheckAdd = 0 and @intSameUserId = 0
begin
INSERT INTO userbuddy VALUES(@userid,@buddyid)
if @@Error = 0 Goto SUCCESS
end

-- Return addition fail if the buddy does not exist in the list
if @intCheckBuddyExist = 0
Goto PROBLEM
Return 0

PROBLEM:
Select 'Fail'
Return 1

SUCCESS:
Select 'Success'
Return 2

GO

No comments: