2011-11-22 49 views
1

我想查詢一個表格並將結果導入變量。使用變量結果做另一個選擇使用變量細節作爲過濾器的查詢。創建一個sql變量並查詢其他表格

到目前爲止:

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 

我得到一個錯誤:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

回答

2

除非你特別想在其他地方的@StoreIds變量,你可以只修改你的WHERE子句:

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

比ks巴里!我不知道我可以在WHERE內創建另一個選擇語句:( –

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的信息可能對您有幫助。

0

巴里和亞當·溫格擁有最好的辦法,但要直接解決了錯誤,你能保證你在使用頂部1修改器設置變量的同時得到正好一個結果。像:

DECLARE @storeIds int  
SET @storeIds = (SELECT top 1 StoreID FROM Store WHERE ParentStoreID=9) 
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