简体   繁体   English

整理声明的SQL变量

[英]Collate declared SQL variable

I've been looking at this code, reproduced below, that looks for non-ASCII characters... 我一直在看这个代码,下面转载,寻找非ASCII字符......

select line,
  patindex('%[^ !-~]%' COLLATE Latin1_General_BIN, Line) as [Position],
  substring(Line, patindex('%[^ !-~]%' COLLATE Latin1_General_BIN, Line), 1) as [InvalidCharacter],
  ascii(substring(line, patindex('%[^ !-~]%' COLLATE Latin1_General_BIN, Line), 1)) as [ASCIICode]
from staging.APARMRE1
where patindex('%[^ !-~]%' COLLATE Latin1_General_BIN, Line) > 0

and it just strikes me that I'd want to declare a variable for '%[^ !-~]%' COLLATE Latin1_General_BIN instead of writing it out every time, but 我只想告诉我,我想要为'%[^ !-~]%' COLLATE Latin1_General_BIN声明一个变量'%[^ !-~]%' COLLATE Latin1_General_BIN而不是每次'%[^ !-~]%' COLLATE Latin1_General_BIN ,但是

declare @regex varchar(20) = '%[^ !-~]%' COLLATE Latin1_General_BIN;

select line,
  patindex(@regex, Line) as [Position],
  substring(Line, patindex(@regex, Line), 1) as [InvalidCharacter],
  ascii(substring(line, patindex(@regex, Line), 1)) as [ASCIICode]
from staging.APARMRE1
where patindex(@regex, Line) > 0

just doesn't do the same thing. 只是不做同样的事情。 Am I just missing some syntax? 我只是缺少一些语法? Is it impossible? 这不可能吗?

It is normal. 这是正常的。 When you create a variable it takes default collation for database. 创建变量时,它会对数据库采用默认排序规则。

DECLARE @regex varchar(20) = '%[^ !-~]%' COLLATE Latin1_General_BIN;

Your string with COLLATE Latin1_General_BIN is implicitly casted to string with your database default collation. 使用COLLATE Latin1_General_BIN字符串将隐式地转换为具有数据库默认排序COLLATE Latin1_General_BIN字符串。


For example database is Case-Insensitive . 例如,数据库是Case-Insensitive I use your syntax to create case-sensitive one and check metadata of it: 我使用您的语法创建区分大小写的并检查它的元数据:

╔══════╦══════════════════════════════╗
║ name ║        collation_name        ║
╠══════╬══════════════════════════════╣
║ @v1  ║ SQL_Latin1_General_CP1_CI_AS ║
╚══════╩══════════════════════════════╝

LiveDemo

Output: 输出:

 ╔══════╦══════════════════════════════╗ ║ name ║ collation_name ║ ╠══════╬══════════════════════════════╣ ║ @v1 ║ SQL_Latin1_General_CP1_CI_AS ║ ╚══════╩══════════════════════════════╝ 

Variables(excluding columns in table variables) do not allow to define collation so there is no syntax like: 变量(表变量中的列除外)不允许定义排序规则,因此没有类似的语法:

 DECLARE @v1 varchar(100) COLLATE Latin1_General_CS_AS = 'ABC' ; -- Incorrect syntax near the keyword 'COLLATE'. 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM