值范围作为CASE语句中的ELSE子句

时间:2017-09-27 02:03:36

标签: sql sql-server

我有一个存储过程,它应该根据一个整数来过滤结果,该整数可以是<!DOCTYPE html> <html> <head> <style> html, body, #div { height: 100%; width: 100%; margin: 0px; padding: 0px } </style> <script src="html2canvas.js"></script> <script type="text/javascript" src="jquery-3.2.1.min.js"></script> </head> <body> <div id="div"></div> <script> // Some init stuff for div and after completion the following: saveMap(); function saveMap() { var element = $("#div"); html2canvas(element, { useCORS: true, onrendered: function(canvas) { var dataUrl= canvas.toDataURL("image/png"); var a = $("<a>") .attr("href", dataUrl) .attr("download", "test.png") .appendTo("body"); a[0].click(); a.remove(); } }); } </script> </body> </html> ,我需要能够选择与整数匹配的结果或检索所有结果,但我可以&#39;找出&#34; All&#34;的语法。结果部分。查询基本上是这样的:

NULL

我想使用Select * from dbo.TABLE WHERE [IDField] = CASE WHEN ISNULL(@ID, 0) > 0 THEN @ID ELSE ????? END 范围来包含所有值,因为将其设置为IN0将不会返回任何结果,但这不起作用:

Null

或者这个:

Select * from dbo.TABLE 
WHERE [IDField] = 
  CASE 
    WHEN ISNULL(@ID, 0) > 0 THEN @ID 
    ELSE 1 OR 2 OR 3 
  END

1 个答案:

答案 0 :(得分:2)

在没有case的情况下发短语:

SELECT * 
FROM dbo.TABLE 
WHERE @id is null OR IDField = @id;

然后你可以将其扩展为:

SELECT * 
FROM dbo.TABLE 
WHERE (COALESCE(@ID, 0) > 0 AND IDField = @id) OR
      IDField IN (1, 2, 3)