开发者

SQL Where if else

开发者 https://www.devze.com 2023-04-13 01:36 出处:网络
How do i do translate this linq code into sql? if (storeId > 1) { query = from p in query where (p.StoreId == storeId)

How do i do translate this linq code into sql?

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

If storeId > 1 i don't want to do a WHERE comparison in SQL.

UPDATE Here is what i would like to do in 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


Looking at your code, it looks like you WANT To retrieve a specific storeId record if storeId > 1. I am also assuming that you meant you do NOT WANT a where clause if storeId <=1. If my assumptions are correct, the SQL you are after is probably as below:

Select * from p where (@storeId > 1 and p.storeId = @storeId) or @storeId <= 1

After looking at your update to the question, this SQL should work for you:

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

Please note that if @storeId <=1, it will return all the records that match the City and Price. If this is not what you want and do not want any records returned when @storeId <= 1, then you can remove the last OR condition as below:

 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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号