创建sql变量并查询其他表

创建sql变量并查询其他表,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我试图查询一个表,并将结果放入一个变量中。使用变量结果,使用变量详细信息作为过滤器执行另一个select查询 到目前为止: 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

我试图查询一个表,并将结果放入一个变量中。使用变量结果,使用变量详细信息作为过滤器执行另一个select查询

到目前为止:

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
我收到一个错误:

子查询返回了多个值。当子查询在=、!=、=或者当子查询用作表达式时


您的问题是多个存储具有相同的
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
的所有商店


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

除非您特别希望在其他地方使用
@StoreIds
变量,否则您只需将
WHERE
子句修改为:

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

Barry和Adam Wenger有最好的方法,但是为了直接解决错误,您可以确保在使用top 1修饰符设置变量时只得到一个结果。比如:

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

可以通过不同的方式完成:

  • 使用子查询

    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
    
  • 使用联接操作

    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
    

  • 谢谢你,巴里!我不知道我可以在WHERE中创建另一个select语句:(