Consider below table, I should be able to get result as "A" when input any value between XYZ-00000001 and XYZ-00000005 for eg: XYZ-00000003 or XYZ-00000004
similarly when input is given as XYZ-00000008 value "B" should be resulted.
SELECT [NAME] FROM YourTable WHERE YourValue BETWEEN Val1 AND Val2
Use SUBSTRING AND CHARINDEX:
DECLARE @tblTest AS Table
(
Name VARCHAR(50),
VAl1 VARCHAR(50),
VAl2 VARCHAR(50)
)
INSERT INTO @tblTest VALUES
('A','XYZ-00000001','XYZ-00000005'),
('B','XYZ-00000006','XYZ-00000012'),
('C','XYZ-00000013','XYZ-00000019'),
('D','XYZ-00000020','XYZ-00000025')
DECLARE @SerachText VARCHAR(50)='XYZ-00000021'
SELECT
*
FROM @tblTest
WHERE
SUBSTRING(@SerachText,CHARINDEX('-',@SerachText)+1,LEN(@SerachText)) >=SUBSTRING(VAl1,CHARINDEX('-',VAl1)+1,LEN(VAl1))
AND
SUBSTRING(@SerachText,CHARINDEX('-',@SerachText)+1,LEN(@SerachText)) <=SUBSTRING(VAl2,CHARINDEX('-',VAl2)+1,LEN(VAl2))
You can separate columns in characters and numbers and then input the value for comparison. Below code will answer 'A' for the input number between 1 to 5.
SELECT NAME
FROM
(
select *, left(val1,3) VAL1_ALFA, left(val2,3) VAL2_ALFA,
cast(REPLACE( val1, SUBSTRING( val1, PATINDEX( '%[a-z]%', val1 ), 4 ),'') as int) val1_NUM,
cast(REPLACE( val2, SUBSTRING( val2, PATINDEX( '%[a-z]%', val2 ), 4 ),'') as int) val2_NUM from Your_Table
) A
WHERE
4 BETWEEN val1_NUM AND VAL2_NUM
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.