SQL if where else

时间:2011-10-15 21:38:08

标签: c# sql linq

如何将此linq代码翻译成sql?

if (storeId > 1)
            {
                query = from p in query
                        where (p.StoreId == storeId) 
                        select p;
            }

如果storeId> 1我不想在SQL中进行WHERE比较。

UPDATE 以下是我想在SQL中做的事情:

SELECT * FROM test 
WHERE (
  (test.city = @city)
  AND 
  (test.price = @price)
  AND
  (
  IF (@storeId > 1)
    test.storeId = @storeId
  ELSE
    do not do anything 
  )
)

3 个答案:

答案 0 :(得分:3)

Select * from p where p.storeid = @storeid or @storeid > 1

答案 1 :(得分:1)

查看您的代码,看起来您想要检索特定的storeId记录,如果storeId> 1.我还假设你的意思是如果storeId< = 1,你不想要一个where子句。 如果我的假设是正确的,那么你所追求的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&lt; = 1,它将返回与City和Price匹配的所有记录。如果这不是您想要的,并且不希望在@storeId&lt; = 1时返回任何记录,那么您可以删除最后的OR条件,如下所示:

 SELECT * FROM test WHERE  test.city = @city AND test.price = @price 
 AND (@storeId > 1 AND test.storeId = @storeId)

答案 2 :(得分:0)

var queryresult = from p in query
                  where ((p.StoreId == storeId) && (storeId > 1)) 
                        || (storeId <= 1)
                  select p;