SQL Where if else
本文关键字:else if Where SQL | 更新日期: 2023-09-27 18:11:17
我怎么把这个linq代码翻译成sql?
if (storeId > 1)
{
query = from p in query
where (p.StoreId == storeId)
select p;
}
如果storeId> 1,我不想在SQL中做WHERE比较。
更新以下是我想在SQL中做的:
SELECT * FROM test
WHERE (
(test.city = @city)
AND
(test.price = @price)
AND
(
IF (@storeId > 1)
test.storeId = @storeId
ELSE
do not do anything
)
)
Select * from p where p.storeid = @storeid or @storeid > 1
查看您的代码,如果storeId> 1,看起来您想要检索特定的storeId记录。我也假设你的意思是你不想要一个where子句如果storeId <=1。如果我的假设是正确的,那么您需要的SQL可能如下所示:
Select * from p where (@storeId > 1 and p.storeId = @storeId) or @storeId <= 1
查看您对问题的更新后,此SQL应该为您工作:
SELECT * FROM test WHERE test.city = @city AND test.price = @price
AND ((@storeId > 1 AND test.storeId = @storeId) or @storeId <=1)
请注意,如果@storeId <=1,它将返回与City和Price匹配的所有记录。如果这不是您想要的,并且不希望在@storeId <= 1时返回任何记录,那么您可以删除最后一个OR条件,如下所示:
SELECT * FROM test WHERE test.city = @city AND test.price = @price
AND (@storeId > 1 AND test.storeId = @storeId)
try
var queryresult = from p in query
where ((p.StoreId == storeId) && (storeId > 1))
|| (storeId <= 1)
select p;