user1663996
user1663996

Reputation: 43

Sql select union with count

I have a stored procedure which returns rows with a bunch of unions. What I am trying to do is see if the select statement does not yield any rows, and if so, execute another script.

This is the current sql select I am using in the stored procedure. Please let me know how I can achieve this.

SELECT  name AS [Name],  address1 AS Address1, address2 AS Address2, city AS City,  1 AS DeliveryTypeKey, email AS Email,  
  ( SELECT TOP 1   c_phone_number   
    FROM phone WITH (NOLOCK)  
    WHERE value = @value) AS Fax 
    FROM #Cities x    
 INNER JOIN prov p WITH (NOLOCK) ON x.ckey = p.pkey  
 UNION 
SELECT  name AS [Name], address1 AS Address1, address2 AS Address2, city AS City,  1 AS DeliveryTypeKey, email AS Email,  
  ( SELECT TOP 1 c_phone_number   
    FROM phone WITH (NOLOCK)  
    WHERE value = @value) AS Fax 
    FROM #Cities1 x    
    INNER JOIN prov1 p WITH (NOLOCK) ON x.ckey = p.pkey  
 UNION 
 SELECT  name AS [Name], address1 AS Address1, address2 AS Address2, city AS City,  1 AS DeliveryTypeKey, email AS Email,  
  ( SELECT TOP 1 c_phone_number   
    FROM phone WITH (NOLOCK)  
    WHERE value = @value) AS Fax 
 FROM #Cities2 x    
 INNER JOIN prov2 p WITH (NOLOCK) ON x.ckey = p.pkey 

Upvotes: 0

Views: 204

Answers (1)

Gidil
Gidil

Reputation: 4137

Use the ROWCOUNT function to check if any rows where returned:

DECLARE @table TABLE 
  ( 
     DATA INT 
  ) 

INSERT @table 
VALUES (0) 

SELECT * 
FROM   @table 
WHERE  DATA > 0 

IF @@ROWCOUNT = 0 
  SELECT 'run' 
ELSE 
  SELECT 'Don''t run' 

Upvotes: 1

Related Questions