在何时使用存在语句的情况

时间:2013-08-07 09:21:31

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

我正在创建一个包含WHERE CASE WHEN语句的SQL查询。我做错了什么并且得到了错误。

我的SQL语句就像

DECLARE @AreaId INT = 2
DECLARE @Areas Table(AreaId int)

INSERT INTO @Areas SELECT AreaId
FROM AreaMaster
WHERE CityZoneId IN (SELECT CityZoneId FROM AreaMaster WHERE AreaId = @AreaID)

SELECT * 
FROM dbo.CompanyMaster
WHERE AreaId IN
     (CASE WHEN EXISTS (SELECT BusinessId
                        FROM dbo.AreaSubscription
                        WHERE AreaSubscription.BusinessId = CompanyMaster.BusinessId) 
             THEN @AreaId 
             ELSE (SELECT [@Areas].AreaId FROM @Areas)
      END)

我收到错误

  

Msg 512,Level 16,State 1,Line 11
  子查询返回的值超过1。子查询时不允许这样做   follow =,!=,<,< =,>,> =或者当子查询用作   表达

请帮助您成功运行查询。我的逻辑是为每一行检查(语句)中的条件AreaId

我只想在

时选择行
  1. 公司已为AreaSubscription
  2. 传递的特定区域订阅了@AreaId
  3. AreaSubscription没有订阅条目,然后评估AreaId中的(SELECT [@Areas].AreaId FROM @Areas)

4 个答案:

答案 0 :(得分:20)

这可能会对你有帮助。

SELECT * FROM dbo.CompanyMaster
WHERE AreaId=
(CASE WHEN EXISTS (SELECT BusinessId
                   FROM dbo.AreaSubscription
                   WHERE AreaSubscription.BusinessId = CompanyMaster.BusinessId) 
      THEN @AreaId ELSE AreaId END)
AND  AreaId IN (SELECT [@Areas].AreaId FROM @Areas)

还有一个解决方案是

SELECT * FROM dbo.CompanyMaster A 
LEFT JOIN @Areas B ON A.AreaId=B.AreaID
WHERE A.AreaId=
(CASE WHEN EXISTS (SELECT BusinessId
                   FROM dbo.AreaSubscription
                   WHERE AreaSubscription.BusinessId = CompanyMaster.BusinessId) 
      THEN @AreaId ELSE B.AreaId END)
)

答案 1 :(得分:0)

如果它解决了问题,请尝试将SELECT top 1 [@Areas] .AreaId FROM @Areas放入..

答案 2 :(得分:0)

试试这个

DECLARE @AreaId INT = 2
DECLARE @Areas Table(AreaId int)

INSERT INTO @Areas 
SELECT AreaId FROM AreaMaster
WHERE CityZoneId IN (SELECT CityZoneId FROM AreaMaster WHERE AreaId = @AreaID)

    IF EXISTS (SELECT BusinessId
        FROM dbo.AreaSubscription
        WHERE AreaSubscription.BusinessId = CompanyMaster.BusinessId) 
    BEGIN
        SELECT * FROM dbo.CompanyMaster
        WHERE AreaId IN (@AreaId) 
    END
    ELSE
    BEGIN
        SELECT * FROM dbo.CompanyMaster
        WHERE AreaId IN (SELECT [@Areas].AreaId FROM @Areas)
    END

答案 3 :(得分:0)

试试这个;

    DECLARE @AreaId INT = 2
    DECLARE @Areas Table(AreaId int)

    INSERT INTO @Areas SELECT AreaId
    FROM AreaMaster
    WHERE CityZoneId IN (SELECT CityZoneId FROM AreaMaster WHERE AreaId = @AreaID)

    INSERT INTO @Areas 
    SELECT AreaSubscription.BusinessId
        FROM dbo.AreaSubscription INNER join CompanyMaster
        ON AreaSubscription.BusinessId = CompanyMaster.BusinessId   

    SELECT * FROM dbo.CompanyMaster
    WHERE AreaId IN (SELECT DISTINCT [@Areas].AreaId FROM @Areas)