表行计数

时间:2012-07-03 15:27:07

标签: sql sql-server sql-server-2008

我正在运行以下查询并检查它是否返回任何结果,如果不是,我需要在我的sp中实现一些逻辑。我从我的sp。

下面给了几个代码块
select * from temp
where (select * table1 where Id='4728')=0

如果table1没有任何记录,它不应该返回任何结果,我需要知道我是否正确检查。

INSERT INTO #companies
    SELECT DISTINCT c.Company_Id
    FROM COMPANY C
        INNER JOIN Request_Summary rs ON c.Company_ID=rs.Company_ID
        WHERE
            rs.IsMember_Ind <> 0            
            AND (SELECT COUNT(*) FROM Monitor_Request mr WHERE mr.Company_ID=c.Company_ID)< 5
                       -- I am checking it here
            AND EXISTS(SELECT COUNT(*) FROM Monitor_Request mr2 WHERE mr2.Company_ID=c.Company_ID)
            AND NOT EXISTS(
                SELECT * FROM TaskAction ta WHERE 
                ta.FirstActionTypeId = @firstActionTypeId and 
                ta.TaskTypeId = @taskTypeId and 
                ta.NextActionTypeId is not null and
                ta.EntityId = c.Company_ID and
                ta.EntityTypeId = 1)

4 个答案:

答案 0 :(得分:3)

如果表1没有任何记录,则不应返回任何结果

由于您处于存储过程中,您可能只想这样做

IF Exists(select * table1 where Id='4728')
BEGIN 
     Select...

END 

答案 1 :(得分:2)

改为使用WHERE EXISTS

SELECT * 
FROM temp 
WHERE EXISTS
(
    SELECT * 
    FROM table1 
    WHERE Id='4728'
)

答案 2 :(得分:2)

这是另一种解决方案:

IF (SELECT COUNT(1) FROM table1 WHERE Id='4728') = 0
BEGIN
    SELECT * FROM temp
END

又是另一种解决方案,由Aaron在评论中提出:

IF EXISTS(SELECT 1 FROM table1 WHERE Id='4728')
BEGIN 
     SELECT * FROM temp
END 

答案 3 :(得分:0)

嗯,我想我会将查询重组为这样的事情:

INSERT INTO #companies
SELECT c.company_Id  -- presumes that company_Id is DISTINCT initially
FROM Company c
WHERE EXISTS (SELECT '1'
              FROM Request_Summary s
              WHERE s.company_Id = c.company_Id
              AND s.isMember_Ind <> 0)
AND EXISTS (SELECT '1'
            FROM Monitor_Request m
            WHERE m.company_Id = c.company_Id
            GROUP BY m.company_Id
            HAVING COUNT(*) < 5)
AND NOT EXISTS (SELECT '1'
                FROM TaskAction t
                WHERE ta.FirstActionTypeId = @firstActionTypeId 
                AND t.TaskTypeId = @taskTypeId 
                AND t.NextActionTypeId IS NOT NULL 
                AND t.EntityId = c.Company_ID 
                AND t.EntityTypeId = 1)

不要在SELECT COUNT(*)子句中使用WHERE EXISTS,因为优化器可能计算所有行(即使我们只关心一行)。如果JOIN为您提供了多行,但您只是检查是否存在(即,您不需要任何数据),请使用EXISTS子句。

我实际上对您的整个SP感到好奇,而不仅仅是这个查询 - 尤其是当您插入会话/临时表时。这是应该变成CTE的东西吗?