从给定范围字符串中提取和评估范围
Extract and evaluate range from a give range string
我有一个存储产品的 table。下面是带有数据的架构。
我想要实现的是我将 ProductId、Tenure 和 Range 作为参数传递,它会选择匹配的记录。
例如,如果我有我的参数 ProductId = 21
、Tenure=Duration=1
和 Range =14678
,那么它应该给我 Id=4
作为我的预期输出。因为给出的范围是10001-15000.
您可以将 parsename()
与 try_convert()
一起使用
例子
Declare @YourTable Table ([ID] varchar(50),[ProductID] int,[Price_Range] varchar(50),[Duration] int)
Insert Into @YourTable Values
(1,21,'0 - 5000',1)
,(2,21,'5001 - 10000',1)
,(4,21,'10001 - 15000',1)
,(5,21,'15001 - 20000',1)
Select *
From @YourTable
Where ProductID = 21
and Duration = 1
and 14678 between try_convert(int,parsename(replace(Price_Range,'-','.'),2))
and try_convert(int,parsename(replace(Price_Range,'-','.'),1))
Returns
ID ProductID Price_Range Duration
4 21 10001 - 15000 1
注意: try_convert()
可能不是必需的。不知道你的数据的全部范围,最好避免误报。
我认为将 parsename()
用于此类目的是令人作呕的——聪明,但令人作呕。 SQL服务器确实应该提供相应的功能。
所以,我会使用:
14678 >= try_convert(int, left(price_range, charindex(' ', price_range))) and
14678 <= try_convert(int, stuff(price_range, 1, charindex('-', price_range) + 1, ''))
我有一个存储产品的 table。下面是带有数据的架构。
我想要实现的是我将 ProductId、Tenure 和 Range 作为参数传递,它会选择匹配的记录。
例如,如果我有我的参数 ProductId = 21
、Tenure=Duration=1
和 Range =14678
,那么它应该给我 Id=4
作为我的预期输出。因为给出的范围是10001-15000.
您可以将 parsename()
与 try_convert()
例子
Declare @YourTable Table ([ID] varchar(50),[ProductID] int,[Price_Range] varchar(50),[Duration] int)
Insert Into @YourTable Values
(1,21,'0 - 5000',1)
,(2,21,'5001 - 10000',1)
,(4,21,'10001 - 15000',1)
,(5,21,'15001 - 20000',1)
Select *
From @YourTable
Where ProductID = 21
and Duration = 1
and 14678 between try_convert(int,parsename(replace(Price_Range,'-','.'),2))
and try_convert(int,parsename(replace(Price_Range,'-','.'),1))
Returns
ID ProductID Price_Range Duration
4 21 10001 - 15000 1
注意: try_convert()
可能不是必需的。不知道你的数据的全部范围,最好避免误报。
我认为将 parsename()
用于此类目的是令人作呕的——聪明,但令人作呕。 SQL服务器确实应该提供相应的功能。
所以,我会使用:
14678 >= try_convert(int, left(price_range, charindex(' ', price_range))) and
14678 <= try_convert(int, stuff(price_range, 1, charindex('-', price_range) + 1, ''))