创建一个sql变量并查询其他表

时间:2011-11-22 23:41:35

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

我正在尝试查询表并将结果转换为变量。使用变量结果,使用变量详细信息作为过滤器,执行另一个选择查询。

到目前为止:

DECLARE @storeIds int    
SET @storeIds = (SELECT StoreID FROM Store WHERE ParentStoreID=9)

--print @storeIds

SELECT c.FirstName, c.LastName, c.CustomerId, r.StoreID
FROM Consumer AS c
    INNER JOIN Purchases AS r ON c.CustomerId= r.CustomerId
WHERE r.StoreID = @storeIds
   -- (r.StoreID = 9) OR
   -- (r.StoreID = 10) OR
   -- (r.StoreID = 11)
GROUP BY c.FirstName, c.LastName, c.CustomerId, r.StoreID
ORDER BY c.FirstName

我收到错误消息:

  

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

4 个答案:

答案 0 :(得分:2)

除非您特别想在其他地方使用@StoreIds变量,否则您只需将WHERE条款修改为:

WHERE r.StoreID IN (SELECT StoreID FROM Store WHERE ParentStoreID = 9)

答案 1 :(得分:1)

您的问题是多个商店具有相同的ParentStoreID,因此在您查询时,您尝试将多个值添加到INT变量中。

你可以看一下尝试:

SELECT c.FirstName, c.LastName, c.CustomerId, p.StoreID
FROM Consumer AS c
INNER JOIN Purchases AS p ON c.CustomerId = p.CustomerId
INNER JOIN Store AS s ON p.StoreId = s.StoreId
WHERE s.ParentStoreID = 9
GROUP BY c.FirstName, c.LastName, c.CustomerId, r.StoreID
ORDER BY c.FirstName

此查询应该为您提供所需的所有商品,来自ParentStoreId = 9的所有商店。

有关JOINS的信息也可能对您有所帮助。

答案 2 :(得分:0)

Barry和Adam Wenger拥有最佳方法,但要直接解决错误,您可以确保在使用top 1修饰符设置变量时获得一个结果。像:

DECLARE @storeIds int     
SET @storeIds = (SELECT top 1 StoreID FROM Store WHERE ParentStoreID=9) 

答案 3 :(得分:0)

可以用不同的方式完成:

  1. 使用子查询

    SELECT c.FirstName, c.LastName, c.CustomerId, r.StoreID
    FROM Consumer AS c
       INNER JOIN Purchases AS r ON c.CustomerId= r.CustomerId
    WHERE r.StoreID = (SELECT StoreID FROM Store WHERE ParentStoreID=9)
    GROUP BY c.FirstName, c.LastName, c.CustomerId, r.StoreID
    ORDER BY c.FirstName
    
  2. 使用加入操作

    SELECT c.FirstName, c.LastName, c.CustomerId, r.StoreID
    FROM Consumer AS c
        INNER JOIN Purchases AS r ON c.CustomerId= r.CustomerId 
        INNER JOIN (SELECT StoreID FROM Store WHERE ParentStoreID=9) AS s(StoreID)
            ON r.StoreID = s.StoreID
    GROUP BY c.FirstName, c.LastName, c.CustomerId, r.StoreID
    ORDER BY c.FirstName