Question : T-SQL If statement

Hello,

I am running SQL Server 2000.  I made a T-SQL job that is supposed to count the number of results for a given query and if the result = 0 execute a select statement.  It seems to be executing the select statement even when the result is not equal to 0.  I cut out the query in the IF statement and ran it separately, the result is 38.  Why does 38 = 0 !

The result I am getting when i run it is "Inside the BEGIN"
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
Declare @FarmName NVarChar
 
Set @FarmName = 'x'
 
If (SELECT Count(*) FROM [RDA Prod Pen Master] As pm LEFT JOIN (SELECT l.[Location ID],Farm,Convert(int, SubString(Convert(NVarChar, [Pen Scan]), 3, 4)) As [Pen Number] FROM [RDA Prod Pen Totals] As pt INNER JOIN Location As l ON Convert(int, SubString(Convert(NVarChar, [Pen Scan]), 1, 2)) = l.House) As totals ON pm.[Location ID] = totals.[Location ID] AND	pm.[Pen Number] = totals.[Pen Number] INNER JOIN Location As l ON pm.[Location ID] = l.[Location ID] WHERE totals.[Location ID] Is Null AND l.Farm = @FarmName) = 0
BEGIN
	Print 'Inside the BEGIN'
END
ELSE
	Print 'Inside the ELSE'

Answer : T-SQL If statement

I glad you mentioned it because I never noticed it...you need a size on your varchar...this should work.


Declare @FarmName NVarChar(50)
 
Set @FarmName = 'Pomeroy'
 
If  exists(SELECT 1 FROM [RDA Prod Pen Master] As pm LEFT JOIN (SELECT l.[Location ID],Farm,Convert(int, SubString(Convert(NVarChar, [Pen Scan]), 3, 4)) As [Pen Number] FROM [RDA Prod Pen Totals] As pt INNER JOIN Location As l ON Convert(int, SubString(Convert(NVarChar, [Pen Scan]), 1, 2)) = l.House) As totals ON pm.[Location ID] = totals.[Location ID] AND  pm.[Pen Number] = totals.[Pen Number] INNER JOIN Location As l ON pm.[Location ID] = l.[Location ID] WHERE totals.[Location ID] Is Null AND l.Farm = @FarmName)
BEGIN
        Print 'Inside the BEGIN'
END
ELSE
        Print 'Inside the ELSE'
Random Solutions  
 
programming4us programming4us