【问题标题】:Define Range in SQL Query using Regular ExpressionDefine Range in SQL Query using Regular Expression
【发布时间】:2022-12-02 06:27:27
【问题描述】:

I have the following values

ABCD_AB_1234
ABCD_ABC_2345
ABCD_ABCD_5678

and a regular expression to match them

ABCD_[A-Z]{2-4}_[0-9]{4}

Now I am looking to convert that regular expression to a SQL query so I can get those records back from the database.

Right now I have following where clause

where [columnName] like 'ABCD_[A-Z][A-Z]%[_][0-9][0-9][0-9][0-9]%'

The problem is that I cannot define a range in the SQL query as I did in the regular expression, like {2-4}, what I am doing now is to set the minimum range only.

Is there any solution?

【问题讨论】:

  • Don't confuse pattern matching for full regex, SQL Server does not (natively) support it.

标签: sql-server tsql


【解决方案1】:

Assuming you are explaining the full picture the easiest way is probably to create 3 conditions to cover your scenarios e.g.

where [columnName] like 'ABCD_[A-Z][A-Z][_][0-9][0-9][0-9][0-9]%'
   or [columnName] like 'ABCD_[A-Z][A-Z][A-Z][_][0-9][0-9][0-9][0-9]%'
   or [columnName] like 'ABCD_[A-Z][A-Z][A-Z][A-Z][_][0-9][0-9][0-9][0-9]%'

Its not optimal but SQL Server doesn't have any regex support so if you have to do it in SQL this is one way.

【讨论】:

    猜你喜欢
    • 2022-12-26
    • 2022-12-02
    • 2021-11-18
    • 2021-02-02
    • 2017-06-24
    • 2022-12-02
    • 2011-04-18
    • 2022-12-02
    • 1970-01-01
    相关资源
    最近更新 更多