如何在SQL服务器中封装Between语句

How to encapsulate Between statement in SQL server

如何在SQL服务器中封装Between语句。

我有很多代码需要重构,其中包含一长串带有相同 Between 语句且具有幻数的 where 子句,我想重构它。可以封装BETWEEN.

示例:查询有类似这样的内容,不可能加入这只是一个基本示例,表明我想在 WHERE 中包含一些不重复 BETWEEN

的内容
SELECT ...
FROM Table0
WHERE Id BETWEEN 3456 AND 15500;

...

SELECT ...
FROM Table1
WHERE Id BETWEEN 3456 AND 15500;

...
SELECT ...
FROM Table2
WHERE Id BETWEEN 3456 AND 15500;

你可以试试

SELECT *
FROM
(
  SELECT ....
  FROM   table1
  UNION ALL
  SELECT ....
  FROM   table2
  UNION ALL
  SELECT ....
  FROM   table3
)
WHERE Id BETWEEN 3456 AND 15500;

正如@Rion 所说,要么创建变量,要么使用单独的 table

CREATE TABLE check_range
    ("range_id" int, "begin" int, "end" int)
;

INSERT INTO check_range
    ("range_id", "begin", "end")
VALUES
    (1, 3456, 15500)
;

那么您的查询应该是

SELECT ...
FROM Table0
CROSS JOIN check_range cr
WHERE Id BETWEEN cr.begin AND cr.end;

如果你想要一个功能,你可以做到。

create function dbo.isValid(val int)
returns int
as
begin
if val BETWEEN 3456 AND 15500
   return 1
return 0
end

以及明显的用法:

select * from table1
where dbo.isValid(id) = 1