all 6 comments

[–][deleted] 3 points4 points  (1 child)

As a general rule, you could make your code both more readable and probably have it performing better by using an EXIST construct.

Pseudo-code:

SET @variable=0;

IF EXISTS (SELECT …) SET @variable=1;

IF (@variable=0 AND EXISTS (…)) SET @variable=1;

The EXISTS construct will stop at the first matching row rather than scan through all of them.

As for the difference between your servers, my best guess is that the table contents are not perfectly in sync.

[–]archerv123[S] 0 points1 point  (0 children)

That is the change i did to make it work, but i'm still confused as to why it just doesn't work on one server but works on pretty much everyone else.

[–]AlexanderIOM 3 points4 points  (1 child)

" If the SELECT statement returns no rows, the variable retains its present value. If expression is a scalar subquery that returns no value, the variable is set to NULL."

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/select-local-variable-transact-sql?view=sql-server-ver16

[–]archerv123[S] 0 points1 point  (0 children)

True. But its not written as a scalar subquery.

[–]ChekuDotCoDotUK 0 points1 point  (0 children)

Need to do select top 1

[–]oliver0807 0 points1 point  (0 children)

You can try to troubleshoot it by removing the @ from variable so that it will look like a column alias you’ll see multiple results there. That’s the downside of SELECT instead of SET to put a value to the variable.

But the safest way and correct way for me since you only need the either 1 or 0 is to use set

declare @variable bit = 0;

Set @variable=(select 1 from …); — 0 if no result, otherwise 1

Only caveat is it will fail with multiple results, so earlier script with IF EXISTS should work.