【问题标题】:What is correct like pattern for number什么是正确的数字模式
【发布时间】:2018-01-06 08:09:54
【问题描述】:

我正在使用 like 运算符寻找正确的模式。

我的代码:

DECLARE @exp1 varchar(100) = '<<PointBalance , 8>>'
DECLARE @exp2 varchar(100) = '<<PointBalance , 985>>'    
IF (TRIM(REPLACE(@exp1, ' ', '')) LIKE '<<PointBalance,[0-9]>>')
    PRINT 'Matched'

正如预期的那样,if 语句不会为 exp2 打印“匹配”。

位数不一样。我需要一个验证 nDigit 数字的模式。

【问题讨论】:

  • 你能用你想要的结果编辑问题吗?我不清楚。
  • @YogeshSharma 我需要将 '>' 替换为为 exp1 和 exp2 打印 'Matched' 的模式。收到了吗?
  • 对于第二个@exp2 变量,您需要将其检查为IF (trim(REPLACE(@exp2, ' ', '')) LIKE '&lt;&lt;PointBalance,[0-9][0-9][0-9]&gt;&gt;'),因为它的长度变为3 位数。
  • @YogeshSharma 我知道。问题是我不知道这个数字有多少位!

标签: sql sql-server tsql sql-like sql-server-2017


【解决方案1】:

Like 模式无法检查可变长度的数字字符串,但它可以检查子字符串中是否存在数字的任何字符:

-- Sample data.
declare @Samples as Table ( Sample VarChar(32) );
insert into @Samples ( Sample ) values
  ( '<<PointBalance , 1>>' ), ( '<<PointBalance , 12>>' ), ( '<<PointBalance , 123>>' ),
  ( '<<PointBalance , 1234>>' ), ( '<<PointBalance , 1 3 5>>' ), ( '<<PointBalance , 1J3>>' );

with
  Step1 as (
    select Sample,
      -- Extract the substring starting after the comma and trim leading whitespace.
      LTrim( Substring( Sample, CharIndex( ',', Sample ) + 1, 32 ) ) as AfterComma
      from @Samples ),
  Step2 as (
    select Sample, AfterComma,
      -- Extract the substring prior to the first   '>'   and trim trailing whitespace.
      RTrim( Substring( AfterComma, 1, CharIndex( '>', AfterComma ) - 1 ) ) as TargetString
      from Step1 )
select *,
  -- Check the remaining string for any characters that are not digits.
  case when TargetString like '%[^0-9]%' then 0 else 1 end as Numeric
  from Step2;

【讨论】:

    【解决方案2】:

    例如,我想使用 substring()patindex() 函数来读取数值并比较整个字符串

    DECLARE @exp1 varchar(100) = '<<PointBalance , 811111>>'
    DECLARE @exp2 varchar(100) = '<<PointBalance , 489>>'    
    IF (trim(REPLACE(@exp2, ' ', '')) like '<<PointBalance,'+substring(@exp2, patindex('%[0-9]%', @exp2), len(replace(@exp2, ' ', '')) - patindex('%[0-9]%', replace(@exp2, ' ', ''))-1)+'>>')
    PRINT 'Matched'
    

    【讨论】:

    • '&lt;&lt;PointBalance , 6 6 &gt;&gt;''&lt;&lt;PointBalance , 42y9 &gt;&gt;' 是否“匹配”有问题?
    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 2017-11-16
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多