LIKE not working in TSQL

2020-03-28 16:55发布

问题:

Consider this TSQL:

declare @b varchar(100)

set @b = 'BANK-41'

IF @b LIKE 'BANK_%'
BEGIN
    print 'Wrong Matching'
END

Why does the TSQL match the string "BANK-" and "BANK_"?

回答1:

In TSQL the underscore is a wildcard representing a single char.

In order to escape in you need to wrap it with square brackets, like this:

'BANK[_]%'

See this page: http://www.dirigodev.com/blog/web-development-execution/escaping-percent-and-underscore-characters-in-t-sql-like-clause/



回答2:

An underscore in SQL Server is reserved for a wild card character, I think. You need to escape it.I think you can put it in brackets:

%[_]%


回答3:

You need to escape the "_". It is a special character for the Like statement. You can enclose it in [].

See LIKE (Transact-SQL).