patindex t-sql special characters

梦想的初衷 提交于 2020-01-25 08:33:05

问题


How to check if any of this !@#$%^&*()_-+ special characters exist in a string ?

i tried

SELECT PATINDEX('!@#$%^&*()_-+', 'test-');  
SELECT PATINDEX('[!@#$%^&*()_-+]', 'test-');  
SELECT PATINDEX('%[!@#$%^&*()_-+]%', 'test-');  

but all returns 0, it should return 5, any help ?


回答1:


The - is a special character in the LIKE or PATINDEX() pattern. If it is anywhere other than the first position, it is a range of characters -- such as all digits being represented by [0-9].

You can do what you want by moving the condition:

PATINDEX('%[-!@#$%^&*()_+]%', 'test-'), 

Unfortunately, PATINDEX() patterns don't support an escape character. You can also express this logic as a LIKE and CASE:

(CASE WHEN 'test-' LIKE '%[-!@#$%^&*()_+]%' ESCAPE '$' THEN 1 ELSE 0 END)

Or using a "not" pattern:

(CASE WHEN 'test-' NOT LIKE '%[^0-9a-zA-Z]%' THEN 0 ELSE 1 END)



回答2:


You can use negation:

SELECT PATINDEX('%[^a-Z]%', 'test-');

This will find a character NOT in the range a-Z.




回答3:


SELECT PATINDEX('%[-+!_@()*^#$%&]%', 'test-');  

this solves my issue returns 5 the positon of -.

Apperently order matters.




回答4:


DECLARE @myString VARCHAR(100) ='test-'
IF (@myString LIKE '%[^a-zA-Z0-9]%')
    PRINT 'Contains "special" characters'
ELSE
    PRINT 'Does not contain "special" characters'


来源:https://stackoverflow.com/questions/51241928/patindex-t-sql-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!