SQL LIKE not/^ operator and multiple characters
So.. I thought I knew mssql fairly well but this one query asked of me today has me perplexed. Basically a piece of code somewhere uses the LIKE clause to determine how to filter certain values. I must point out that this cannot be changed, we cannot modify the query to use NOT LIKE. But what if that's what I want to do? Consider this example:
select * from
(
select '1.2A' as num
union
select '1.3A' as num
union
select '1.4A' as num
union开发者_运维技巧
select '1.4B' as num
union
select '1.5A' as num
) as test
where num like '1.[^4]_'
Now.. how can the WHERE be modified to return everything except 1.4A? You can't do [^4A] or even [^4][^A] for obvious reasons. Is this something which is simply impossible to do without using NOT LIKE? Or am I missing something here and just too Friday'd up to realise it?
If you can only change the expression after LIKE, then you can't do this with simple LIKE.
You'd need NOT LIKE or OR at least. You'd need the matching power of Regular Expression which is not available easily in SQL Server.
Is the code SQL-injection safe? Because I see injection as the only way to do that. Usually, only _
and %
have a meaning in the LIKE
operands.
If it really is just the 4A you're looking to exclude, then:
select * from
(
select '1.2A' as num
union
select '1.3A' as num
union
select '1.4A' as num
union
select '1.4B' as num
union
select '1.5A' as num
) as test
where num like '1.[0-9]_'
and RIGHT(num,2)<> '4A'
精彩评论