Sql server 使用PATINDEX解析SQL中的字符
我正在尝试使用原始sql验证字符串; 尝试使用:Sql server 使用PATINDEX解析SQL中的字符,sql-server,tsql,Sql Server,Tsql,我正在尝试使用原始sql验证字符串; 尝试使用: DECLARE @AlphaNumeric varchar(50) SET @AlphaNumeric = '1017a' SELECT SUBSTRING(@AlphaNumeric, 1, (PATINDEX('%[^0-9]%', @AlphaNumeric) - 1)) AS 'Numeric', SUBSTRING(@AlphaNumeric, PATINDEX('%[^0-9]%', @AlphaNumeric), DATALE
DECLARE @AlphaNumeric varchar(50)
SET @AlphaNumeric = '1017a'
SELECT SUBSTRING(@AlphaNumeric, 1, (PATINDEX('%[^0-9]%', @AlphaNumeric) - 1)) AS 'Numeric',
SUBSTRING(@AlphaNumeric, PATINDEX('%[^0-9]%', @AlphaNumeric), DATALENGTH(@AlphaNumeric)) AS 'Alpha'
但是如果用户键入101a7a,则无法正常工作;我想做的就是;
我希望变量总是,数字+字母数字,长度不重要。
例如:
2303A OK
23A434A NOT OK
A344 NOT OK.
4324AAC正常
如果我可以在正则表达式中执行,这将非常容易,但sql让我头疼:(我认为这可以满足您的要求。至少,它可以在您的示例数据上工作:
with t as (
select '2303A' as col union all
select '23A434A' union all
select 'A344'
)
select *,
(case when col like '%[0-9]%' and
substring(col, patindex('%[A-Z]%', col), len(col)) not like '%[^A-Z]%'
then 'OK'
else 'NOT OK'
end)
from t;
这两个条件是。首先检查字符串的某个位置是否有数字。然后,检查在找到第一个字母后是否只有字母。我假设所有字母都是大写的
编辑:
可能有一种更简单的方法。您可以检查字符串中某个位置的数字后面是否有字母,但字母后面永远不会有数字。为此,您只需要执行以下操作:
select (case when col not like '%[^A-Z0-9]%' and
col like '%[0-9][A-Z]%' and
col not like '%[A-Z][0-9]%'
then 'OK'
else 'NOT OK'
end)
字母后接数字是可以的;数字后接字母则不行;所有字符都必须是字母或数字。因此
select * from yourtable
where yourfield like '%[0-9][a-z]%'
and not (yourfield like '%[a-z][0-9]%')
and not (yourfield like '%[^0-9a-z]%')
我有一个方法应该适用于你的情况。基本上确定最后一个整数的位置,并将其与第一个非整数的位置进行比较。你可以像这样得到最后一个整数的位置
len(@AlphaNumeric) - PATINDEX('%[0-9]%', Reverse(@AlphaNumeric))+1
PATINDEX('%[^0-9]%', @AlphaNumeric)
Where (len(@AlphaNumeric) - PATINDEX('%[0-9]%', Reverse(@AlphaNumeric))+1 ) < PATINDEX('%[^0-9]%', @AlphaNumeric)
你可以得到第一个非整数的位置,就像这样
len(@AlphaNumeric) - PATINDEX('%[0-9]%', Reverse(@AlphaNumeric))+1
PATINDEX('%[^0-9]%', @AlphaNumeric)
Where (len(@AlphaNumeric) - PATINDEX('%[0-9]%', Reverse(@AlphaNumeric))+1 ) < PATINDEX('%[^0-9]%', @AlphaNumeric)
这将使您的where子句(其中所有整数都位于任何非整数之前,如下所示
len(@AlphaNumeric) - PATINDEX('%[0-9]%', Reverse(@AlphaNumeric))+1
PATINDEX('%[^0-9]%', @AlphaNumeric)
Where (len(@AlphaNumeric) - PATINDEX('%[0-9]%', Reverse(@AlphaNumeric))+1 ) < PATINDEX('%[^0-9]%', @AlphaNumeric)
其中(len(@AlphaNumeric)-PATINDEX('%[0-9]',反向(@AlphaNumeric))+1)