我在mssql数据库中工作。我有以下情况,
我的行中的值为
... 2-5,10-12,67-89
我需要一个sql查询来仅获取那些包含至少一个包含用户输入的范围的行。
对于ex,如果用户输入为4,则应至少有一个包含4的范围,如(1-5)。
单一查询是否可以实现相同目的。
答案 0 :(得分:3)
试试这个:
DECLARE @numberToFind INT = 4;
;WITH CTE
AS
(
SELECT
arange,
SUBSTRING(arange, 1, CHARINDEX('-', arange,1) - 1) "From",
SUBSTRING(arange,
CHARINDEX('-', arange,1) + 1,
LEN(arange) - CHARINDEX('-', arange,1) + 1) "To"
FROM @ranges
)
SELECT arange
FROM CTE
WHERE @numberToFind BETWEEN "From" AND "To";
如果这些范围存储为单个varchar字符串,则必须先解析这些逗号分隔的范围,如下所示:
DECLARE @ranges VARCHAR(100) = ('2-5,10-12,67-89');
declare @numberToFind INT = 4;
DECLARE @Xml xml = CONVERT(xml,
'<root><s>' +
REPLACE(@ranges, ',', '</s><s>') +
'</s></root>');
;WITH ParsedRanges
AS
(
SELECT arange = T.c.value('.','varchar(20)')
FROM @Xml.nodes('/root/s') T(c)
), CTE
AS
(
SELECT
arange,
SUBSTRING(arange, 1, CHARINDEX('-', arange,1) - 1) "From",
SUBSTRING(arange,
CHARINDEX('-', arange,1) + 1,
LEN(arange) - CHARINDEX('-', arange,1) + 1) "To"
FROM ParsedRanges
)
SELECT arange
FROM CTE
WHERE @numberToFind BETWEEN "From" AND "To";