TSQL:特殊(国家)字符检测(SQL Server2016)

时间:2018-03-29 15:46:01

标签: tsql

我发现很多技术可以检测到特殊字符($%@#)在英语键盘上有用,但是我看到一些像á这样的国家字符的工作方式不同,虽然我的LIKE条件应该得到它,因为它应该选择任何东西但是a-z1-9,这里的诀窍是什么:在下面的示例中,我想念我的特殊á。我在TSQL 2016上使用默认设置在美国。

    ;WITH cte AS (SELECT 'Euro a€'  St UNION  SELECT 'adgkjb$' St UNION SELECT 'Bravo Endá' St)
    SELECT * FROM cte WHERE St LIKE '%[^a-zA-Z0-9 ]%'

        St
        adgkjb$
        Euro a€
   SELECT CAST(N'€' AS VARBINARY(8))    --0xAC20
   SELECT CAST(N'á' AS VARBINARY(8))    --0xE100

1 个答案:

答案 0 :(得分:1)

由于默认排序规则,SQL Server似乎帮助包含字符范围。如果您明确列出了所有有效字符,它将按预期工作。或者,您可以对模式匹配强制进行排序,这不会解释包含非ASCII字符的模式。

-- Explicit pattern for "bad" characters.
declare @InvalidCharactersPattern as VarChar(100) = '%[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ]%';

-- Query some sample data with the explicit pattern and an explicitly specified collation.
select Sample,
  case when Sample like @InvalidCharactersPattern then 'Bad Character' else 'Okay' end as ExplicitStatus,
  case when Sample like '%[^a-zA-Z0-9 ]%' collate Latin1_General_100_BIN
    then 'Bad Character' else 'Okay' end as CollationStatus
  from ( values ( 'a' ), ( 'A' ), ( 'á' ), ( 'Foo' ), ( 'F&o' ), ( '$%^&' ) ) as Samples( Sample );

-- Server collation.
select ServerProperty( 'collation' ) as ServerCollation;

-- Available collations.
select name, description
  from sys.fn_helpcollations()
  order by name;