“Sql pattern like ‘%A[1-9]1[012]%’ (Checking values in a string value A1 to A20)”

huangapple go评论64阅读模式
英文:

Sql pattern like '%A[1-9]1[012]%' (Checking values in a string value A1 to A20)

问题

I tried checking pattern using SELECT * FROM TEST WHERE QUESTION like ''%A[1-9]% E.g A1-A9 (which is correct)

Column A
A1
A2
A3
A4
A5
A6
A7
A8
A9
A10
A11
A12
A13
A14
A15
A16
A17
A18
A19
A20

Is there any solution for 'A1'-'A20'?

I tried SELECT * FROM TEST WHERE QUESTION like ''%A[1-9][2-0]%''

英文:

I tried checking pattern using SELECT * FROM TEST WHERE QUESTION like '%A[1-9]% E.g A1-A9 (which is correct)

Column A
A1
A2
A3
A4
A5
A6
A7
A8
A9
A10
A11
A12
A13
A14
A15
A16
A17
A18
A19
A20

Is there any solution for 'A1'-'A20'?

I tried SELECT * FROM TEST WHERE QUESTION like '%A[1-9][2-0]%'

答案1

得分: 3

显然,正确的解决方案是将问题编号存储在一个数字列中,而不是隐藏在文本列中。 “Sql pattern like ‘%A[1-9]1[012]%’ (Checking values in a string value A1 to A20)”

如果因为查询外部的遗留数据库而无法修改它,我有一个替代建议:

不要将所有内容放在一个复杂的模式中(我认为在SQL Server中甚至不可能实现),而是使用三个简单的模式。如果您需要修改或扩展查询,您会为此感到高兴的。

WHERE question LIKE 'A[1-9]'      -- 1-9
   OR question LIKE 'A1[0-9]'     -- 10-19
   OR question = 'A20'            -- 20

我去掉了尾随的%,因为您不希望A[1-9]匹配A1234,而且我去掉了前导的%,因为它是不必要的(根据您在问题中展示的示例数据)。

对于不超过99的数字,您不应该需要超过三个条件。例如,所有1-45的问题将是A[1-9]A[1-3][0-9]A4[0-5]

英文:

Obviously, the correct solution would be to store the question number in a numeric column instead of hiding it inside a text column. “Sql pattern like ‘%A[1-9]1[012]%’ (Checking values in a string value A1 to A20)”


If that is not possible because you are querying an external legacy database that you cannot modify, I have an alternative suggestion:

Instead of putting it all in one complex pattern (which I don't think is even possible in SQL Server), just use three simple patterns instead. You will thank yourself for it if you ever have to modify or extend the query.

WHERE question LIKE 'A[1-9]'      -- 1-9
   OR question LIKE 'A1[0-9]'     -- 10-19
   OR question = 'A20'            -- 20

I have removed the trailing % because you don't want A[1-9] to match A1234, and I've removed the leading % because it's not necessary (according to the example data you showed in your question).

You should not need more than three conditions for numbers up to 99. For example, all questions 1-45 would be A[1-9], A[1-3][0-9] and A4[0-5].

答案2

得分: 0

如果模式固定,您可以使用 sub 提取数字部分并对其进行条件判断

选择 * 
从 dd 
在哪里 子串( 列A,2,len(列A)-1) 在 1 和 20 之间
英文:

If the pattern is fixed, you can extract the number part with sub and place a condition on it

select * 
from dd 
where SUBSTRING( ColumnA,2,len(ColumnA)-1) between 1 and 20

huangapple
  • 本文由 发表于 2023年5月11日 04:35:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定