20

我正在创建一个带有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)

我收到错误

消息 512,级别 16,状态 1,第 11 行
子查询返回超过 1 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的。

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

我只想在

  1. AreaSubscription公司已通过特定区域的订阅入口@AreaId
  2. AreaSubscription没有订阅条目,然后AreaId(SELECT [@Areas].AreaId FROM @Areas)
4

4 回答 4

27

这可能会对您有所帮助。

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)
)
于 2013-08-07T09:35:52.210 回答
0

如果可以解决问题,请尝试将 SELECT top 1 [@Areas].AreaId FROM @Areas ..

于 2013-08-07T09:30:40.433 回答
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
于 2013-08-07T09:32:10.730 回答
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)
于 2013-08-07T09:38:09.237 回答