2014-01-21 50 views
-3

我有一个存储过程,它可以获取具有特定ID的表中的所有行。我想要做的就是从该表中获取所有行如果STORE_ID 0如果id为0,则通过id或所有行获取行

这是我的代码使用权现在:

SELECT store_id, SUM(traffic) FROM traffic 
WHERE store_id = @store_id AND year = @year 
GROUP BY store_id 

我想改变这个查询,以便它返回的所有行无论store_id在@store_id = 0时

+0

还等什么是你的问题? –

+0

如何更改查询以返回所有行,而不管@store_id为0时的store_id – Jerodev

+0

您可以尝试'WHERE store_id = @store_id或@store_id = 0)AND year = @ year' – praveen

回答

2

尝试以下

SELECT store_id, SUM(traffic) FROM traffic 
WHERE (store_id = @store_id OR @store_id = 0) AND year = @year 
GROUP BY store_id 
+2

你只比nicky +1快了20秒 – Dhaval

+0

即使当一个非0值传递给@ store_id变量时,这个查询是否会返回所有行'where store_id = 0'? – Raj

+1

不,因为它表示“@ store_id”,而不是“store_id” – NickyvV

0

在提出请求前测试您的store_id。如果store_id == 0,则发出另一个请求以获取关于store_id的所有信息。

0

试试这个,如果@store_id也可能是NULL然后执行以下操作

SELECT store_id, SUM(traffic) FROM traffic 
WHERE (store_id = @store_id OR ISNULL(@store_id, 0) = 0) 
AND year = @year 
GROUP BY store_id 
1
IF @store_id = 0 
BEGIN 
SELECT store_id, SUM(traffic) FROM traffic 
WHERE year = @year 
GROUP BY store_id 
END 
ELSE 
BEGIN 
SELECT store_id, SUM(traffic) FROM traffic 
WHERE store_id = @store_id AND year = @year 
GROUP BY store_id 
END