Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

IF statement not raising error as expected

Assume @Ref <> 0 in first condition. Therefore my code will not reach the declaration of @XYZ (line 2).

I think it must raise an error in the second IF because of @XZY was not declared.

But I’m surprised that there is no error raised.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

IF @Ref = 0 
BEGIN
    DECLARE @XYZ int

    SELECT @XYZ = RISKGROUP
    FROM POLCONT WITH (NOLOCK, NOWAIT) 
    WHERE CONT = 555
END

IF @RISKGROUP <> @XYZ  
BEGIN
    -- do something ...
END

For example.

In python it raises this error:

Error: local variable ‘XYZ’ referenced before assignment

>Solution :

You need to declare your variable with a type before you can use it

declare @xyz int -- assuming the datatype of column riskgroup is also int

select @xyz = riskgroup
from   polcont
where  polcont = 555

EDIT

You altered your question since I have posted my answer, now your problem is you declare the variable in the wrong scope.

DECLARE @XYZ int

if @Ref = 0 
begin 
   SELECT @XYZ = RISKGROUP
   FROM   POLCONT --WITH (NOLOCK, NOWAIT) don't do nolock everywhere !
   WHERE  CONT = 555
end

if @RISKGROUP <> @XYZ  
begin
   -- do something ...
end

EDIT 2

As to your question why it does not give any error, that is strange indeed

See this DBFiddle
I would indeed expect an error, but it somehow does not

This is explained in the documents as normal per design, though in my mind it is a flaw.
Also see this Question about the same subject

EDIT 3

So it seems that is does not matter much in TSQL where you declare your variables, but as a programmer I find this looking weird, so I prefer to put my variables in what is for me the correct scope.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading