我有以下示例数据:
create table num_test
(
numb int,
names varchar(20)
);
insert into num_test values(123456,'ABC');
insert into num_test values(12345,'DCD');
insert into num_test values(1234567,'ECD');
insert into num_test values(123456789,'BCD');
我有输入值:
declare @num int = 123456
我要搜索left
6或5个整数。如果与left 6
匹配,则应忽略left 5
,否则应显示left 5
。
所以预期结果应该是:
numb names
-----------------
123456 ABC
查询:
declare @num int = 123456
SELECT * FROM num_test
where numb = LEFT(@num,6) or numb = LEFT(@num,5)
答案 0 :(得分:2)
您可以按numb
的长度对结果进行排序,并排在最前面:
SELECT TOP 1 *
FROM num_test
WHERE numb IN (LEFT(@num,6), LEFT(@num,5))
ORDER BY LEN(numb) DESC