views:

38

answers:

2

Hi All,

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 * 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

+1  A: 

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

Peter Mourfield
+3  A: 

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
DyingCactus
That worked perfect. Thanks!
Hcabnettek