开发者

SQL IF ELSE with output params stored proc help

I have a stored proc (SS2008) that takes a couple int ids and needs to look up if they exist in a table before adding a record. I have an int output param I would like to return and set its value based on what occrured. I have this so far, but it always returns 1. Can someone point me in the right direction?

BEGIN TRY

IF EXISTS
(
    SELECT * FROM tbMap WHERE (cId= @CId)
)
    SET @result = -1; -- This C User is already mapped

ELSE IF EXISTS
(
    SELECT * 开发者_Python百科FROM tbMap WHERE (dId = @DId)

)

    SET @result = -2; -- This D User is already mapped

ELSE
    INSERT INTO tbMap (
        Login
        , Email
        , UserName
        , CId
        , DId)
    SELECT 
            @UserName
            , usr.EmailAddress
            , usr.UserName
            , @CId
            , @DId
        FROM tbUser usr WHERE usr.iUserID = @DId

    SET @result = 1;
RETURN

END TRY

What am I missing? Thanks for any tips.

Cheers, ~ck in San Diego


Put the multiple statements for the last ELSE in a BEGIN/END block otherwise the last SET is always executed.

ELSE
BEGIN
    INSERT INTO tbMap (
        Login
        , Email
        , UserName
        , CId
        , DId)
    SELECT 
            @UserName
            , usr.EmailAddress
            , usr.UserName
            , @CId
            , @DId
        FROM tbUser usr WHERE usr.iUserID = @DId

    SET @result = 1;
    RETURN
END
END TRY


Have you tried using SELECT @result instead of SET? Also, I'm assuming the calling code has the @result parameter marked as Output?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜