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.
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
CodePudding user response:
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.