6

I'm wondering if there is a way to check if variable @varChar is NULL and variable @bit is 0.

My attempt:

if ISNULL(@varChar, false) and (@bit = 0) 
begin
    RAISERROR ('varchar was not specified', 16,1);
end

My problem is that ISNULL(check_if_null, replacement_value) does not work like this, and I can not find an alternative.

2 Answers 2

14

You could use IS NULL:

IF @varCHAR IS NULL AND @bit = 0
BEGIN
    RAISERROR ('varchar was not specified', 16,1);
END

Another approach is:

DECLARE @varCHAR VARCHAR(MAX) = NULL;

IF ISNULL(@varCHAR,'false') = 'false' AND @bit = 0
    RAISERROR ('varchar was not specified', 16,1);
Sign up to request clarification or add additional context in comments.

2 Comments

The first solution checks for NULL. The second checks for a magic value that may or may not occur in the data ('false'). Best practice is to avoid magic values.
@HABO I agree that we should avoid "magic" values at all cost and first approach is preferred. I just wanted to show OP that using ISNULL(@varChar, false) is possible.
1

Use IS NULL when checking if a value is null.

IF @varChar IS NULL and @bit = 0 
    RAISERROR ('varchar was not specified', 16,1);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.