Returning different values based on selected data

I have a stored procedure that selects a row based on an id (simple enough), but only returns the actual result if the data satisfies a few conditions, otherwise it returns specific error codes. So when doing nested checks, the code would look similiar to this:

CREATE PROCEDURE GetStuffById
@StuffId int
AS
BEGIN
IF EXISTS (SELECT TOP 1 * FROM [Stuff] WHERE StuffId = @StuffId)
    BEGIN
    DECLARE @IsValid bit
    SET @IsValid = (SELECT IsValid FROM [Stuff] WHERE StuffId = @StuffId)
    IF @IsValid = 1
        BEGIN
        --More nested checks may occur here
        SELECT * FROM [Stuff] WHERE StuffId = @StuffId
        END
    ELSE
        BEGIN
        RETURN -2
        END
    END
ELSE
    BEGIN
    RETURN -1
    END
END

In this approach I already have 3 selects on the same table, which seems redundant and inefficient and another check would mean another select etc. Is there a better pattern to do this (e.g. temp tables)?

UPDATE: edited first check

Upvotes: 3

Views: 216

Answers (1)

Martin Smith
Martin Smith

Reputation: 453243

You can assign to multiple variables in a single select and use @@ROWCOUNT to detect whether a row was found.

DECLARE @IsValid BIT,
        @Foo     INT

SELECT @IsValid = IsValid,
       @Foo = Foo
FROM   [Stuff]
WHERE  StuffId = @StuffId

/*This must be tested immediately after the assignment statement*/
IF @@ROWCOUNT = 0
  RETURN -1

IF ISNULL(@IsValid, 0) = 0
  RETURN -2

SELECT @IsValid AS IsValid,
       @Foo     AS Foo  

Upvotes: 4

Related Questions