TSQL:substring包含0-9之间的所有数字,除了5

Hip*_*ray 2 sql t-sql sql-server

我在案例陈述中使用子字符串函数来返回'B0' - 'B9'之间的所有数字

WHEN SUBSTRING (postcode, 1, 2) like 'B[0-9]'
Run Code Online (Sandbox Code Playgroud)

但我不想在此列表中返回数字'B5'.我可以这样工作

WHEN SUBSTRING (postcode, 1, 2) like 'B[0-4]'
WHEN SUBSTRING (postcode, 1, 2) like 'B[6-9]'
Run Code Online (Sandbox Code Playgroud)

但有没有办法将其添加到如下所示的一行?

WHEN SUBSTRING (postcode, 1, 2) like 'B[0-9]' and not like 'B5'
Run Code Online (Sandbox Code Playgroud)

编辑:

如果你处理0-100之间的数字,你会怎么做,所以sql会是这样的

WHEN SUBSTRING (postcode, 1, 3) like 'B[0-9][0-9]'
Run Code Online (Sandbox Code Playgroud)

但你不想包括16和17?

Tim*_*ner 7

WHEN SUBSTRING (postcode, 1, 2) like 'B[012346789]' -- No "5"
Run Code Online (Sandbox Code Playgroud)

喜欢的模式很棒.迷你正则表达,如果你愿意的话.

为了完成这一点的十位以上的数字,你可能要考虑把这些值,您可以使用一个表join,existsin.

或者,因为我们将此列的数字部分视为数字而不是字符串,这表明它们可能更好地存储为两列:一列用于alpha,一列用于数字.

除非您对架构进行任何更改,否则您可能会删除特殊字母字符,以便将它们与一系列数字进行比较,例如:

where cast(replace(postcode, 'B', '') as int) between 0 and 15
    or cast(replace(postcode, 'B', '') as int) between 18 and 100

where cast(right(postcode, len(postcode) - 1) as int) between 0 and 15
    or cast(right(postcode, len(postcode) - 1) as int) between 18 and 100
Run Code Online (Sandbox Code Playgroud)

这些只是几种可能性.您最了解如何按摩数据.

  • 那时,我想在表格中将这些值用于连接/存在/中.您还可以使用多个where条件,如其他答案和评论所述.我将添加一个例子. (2认同)