如何在 SQL 服务器中的两个 varchar 字符串之间找到一个字符串?
How to find a string in between two varchar strings in SQL server?
考虑下面 table,当输入 XYZ-00000001 和 XYZ-00000005 之间的任何值时,我应该能够得到结果 "A" 例如:XYZ-00000003 或 XYZ-00000004
类似地,当输入为 XYZ-00000008 值时,应该得到 "B"。
SELECT [NAME] FROM YourTable WHERE YourValue BETWEEN Val1 AND Val2
使用 SUBSTRING 和 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))
您可以用字符和数字分隔列,然后输入值进行比较。下面的代码将回答 'A' 对于 1 到 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
考虑下面 table,当输入 XYZ-00000001 和 XYZ-00000005 之间的任何值时,我应该能够得到结果 "A" 例如:XYZ-00000003 或 XYZ-00000004
类似地,当输入为 XYZ-00000008 值时,应该得到 "B"。
SELECT [NAME] FROM YourTable WHERE YourValue BETWEEN Val1 AND Val2
使用 SUBSTRING 和 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))
您可以用字符和数字分隔列,然后输入值进行比较。下面的代码将回答 'A' 对于 1 到 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