简体   繁体   English

T-SQL PATINDEX中双百分号(%%)的意义

[英]Significance of double percent signs (%%) in T-SQL PATINDEX

I ran across a legacy piece of T-SQL that uses a PATINDEX similar to the following to extract a date out of a text column: 我遇到了一个旧的T-SQL,它使用类似于以下内容的PATINDEX从文本列中提取日期:

CAST(SUBSTRING(MyText, PATINDEX('%%-[0-1][0-9]/[0-3][0-9]/[0-9][0-9]%%', DocumentHeaderText)+1, 8) AS DATE)

I can't see the reason for the double percent signs at the beginning and end of the wildcard string, and from Googling around and looking at the PATINDEX documentation it doesn't seem like a double percent sign does anything more than a single percent sign. 我看不到通配符字符串开头和结尾出现双百分号的原因,从谷歌搜索和查看PATINDEX文档来看,看起来双百分号似乎只不过是一个百分号而已。

However, I've been bitten before by hastily "improving" legacy code, finding out the hard way that the original author had a good reason for what they did and having to change it back. 但是,我之前一直急于“改进”旧版代码,发现原来的作者有充分的理由对其所做的工作提出困难的意见,并且不得不将其改回。

So my question is, is there any difference between %% and % in a wildcard string for a T-SQL LIKE or PATINDEX statement? 所以我的问题是,对于T-SQL LIKE或PATINDEX语句,通配符字符串中的%%%之间是否有区别? Can I safely change the code without altering the behavior to: 我可以安全地更改代码而无需将行为更改为:

CAST(SUBSTRING(MyText, PATINDEX('%-[0-1][0-9]/[0-3][0-9]/[0-9][0-9]%', DocumentHeaderText)+1, 8) AS DATE)

The official documentation of PATINDEX states that: PATINDEX官方文档指出:

pattern 图案
Is a character expression that contains the sequence to be found. 是包含要查找的序列的字符表达式。 Wildcard characters can be used; 可以使用通配符; however, the % character must come before and follow pattern (except when you search for first or last characters) 但是, %字符必须位于模式之前和之后(除非您搜索第一个或最后一个字符)

The % wildcard stands for, as written in the official documentation for LIKE : %通配符表示,如LIKE官方文档中所述:

any string of zero or more characters. 零个或多个字符的任何字符串。

The fact that it can stand for any number of characters including zero, means that %% is completely equivalent to % and there for can be safely be changed. 它可以代表任意数量的字符(包括零)的事实,这意味着%%完全等同于%并且可以安全地更改。

Please note that this is not the case with any other T-SQL wildcards - since _ stands for a single char, as well as [] and [^] . 请注意,任何其他T-SQL通配符都不是这种情况-因为_代表单个字符,以及[][^]

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

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