Sql选择与计数联合

时间:2012-10-03 19:47:35

标签: sql sql-server

我有一个存储过程,它返回带有一堆联合的行。我想要做的是查看select语句是否不产生任何行,如果是,则执行另一个脚本。

这是我在存储过程中使用的当前sql选择。请让我知道如何实现这一目标。

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 

1 个答案:

答案 0 :(得分:1)

使用ROWCOUNT函数检查返回的行是否为

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'