如何比较从左到右的字符串值
Table1 (Column name: Reference)
A123BD
E-.D256
123-D14:
我在table1中有一个参考编号,我想比较表1的参考编号是否与用户输入从左到右匹配。 示例用户可以输入如A123BD398202然后它应该与table1 coumn比较,这里用户输入的左右值与表1列A123BD匹配
user input
A123BD124
E-.D257809
A123-D14:2345
” 对于上述用户输入,预期输出为
Matching (left to right string of table1 column is matching with user input)
Not Matching (left to right string of table1 column is not matching with user input)
Not matching (left to right string of table1 column is not matching with user input)
此外,字符串不是固定长度,用户输入从左到右比较表1列字符串。
如何在SQL查询中实现此目的。任何人都可以帮助我
答案 0 :(得分:2)
简单like
可能适合您。请参阅以下示例。
declare @refs table(reference varchar(50))
insert @refs values
('A123BD'),
('E-.D256'),
('123-D14:')
declare @userInput table (ui varchar(50))
insert @userInput values
('A123BD124'),
('E-.D257809'),
('A123-D14:2345')
select ui,
case when exists(select 1 from @refs where ui like reference+'%') then 'match'
else 'not match' end isMatch
from @userInput
输出:
ui isMatch
A123BD124 match
E-.D257809 not match
A123-D14:2345 not match
答案 1 :(得分:0)
看起来像你想要的,但反之亦然。您可以检查列的长度并检查输入的左X字符。请参阅tsql中的以下示例。
declare @input varchar(50) = 'A123-D14:2345'
/*
A123BD124
E-.D257809
A123-D14:2345
*/
if object_id('tempdb.dbo.#table1') is not null drop table #table1
create table #table1 (Column1 varchar(50))
Insert into #table1 (Column1)
Values('A123BD')
,('E-.D256')
,( '123-D14:')
Select
Column1
,Left(Column1, Len(Column1))
,@input
,Len(column1)
,Len(@input)
,Case when Left(@input, Len(Column1)) = Column1 then 'Matched'
Else 'unmatched'
END as [IsMatched]
from
#table1