sql - 我可以在 Firebird POSITION 函数中使用通配符吗

标签 sql firebird text-parsing firebird2.1

我正在使用 Firebird 2.1。

我的工作订单号可能包含 1 或 2 个字母字符,然后是 4 或 5 个数字,然后可能是包含 1 个字母字符和 2 个数字的前缀。

我想提取中间的4-5位数字。

我尝试了以下方法来查找数字字符,但它返回 0:

POSITION('%[0-9]%',JOBHEADER.ORDERNUMBER,1) AS“第一个数字”

我不确定是否可以在 POSITION 函数中使用通配符。我想我可以尝试检查第二个或第三个字符的数字,但我确实需要通配符功能,然后在找到第一个数字的位置后找到下一个阿尔法。或者也许还有另一种解决方案来提取数字。

我发现了一些类似的东西:

CASE WHEN SUBSTRING(ordernumber FROM 2 FOR 5) SIMILAR TO '[0-9]+'
     THEN SUBSTRING(ordernumber FROM 2 FOR 5)
     ELSE SUBSTRING(ordernumber FROM 3 FOR 5)
END as PROJECTNUMBER

但是由于数字可能从前 5 个字符开始,因此 if/case 语句开始变得相当大。

最佳答案

不,你不能使用POSITION来做到这一点。 Position 搜索给定字符串中的确切子字符串。但是,对于 Firebird 3,您可以使用 SUBSTRING用正则表达式提取值,例如:

substring(ordernumber similar '%#"[[:DIGIT:]]+#"%' escape '#')

正则表达式必须覆盖整个字符串,而 #" 包含要提取的术语(# 是显式定义的转义符号)。您可能需要使用更复杂的模式,如 [^[:DIGIT:]]*#"[[:DIGIT:]]+#"([^[:DIGIT:]]%)? 以避免边缘情况出于贪婪。

如果您知道模式始终是要提取的 1 或 2 个字母、4 或 5 个数字,可能后跟 1 个字母和 2 个数字,您也可以使用 [[:ALPHA:]]{1, 2}#"[[:DIGIT:]]{4,5}#"([[:ALPHA:]][[:DIGIT:]]{1,2})?。如果模式不匹配,则返回 null

另请参阅:

请注意,Firebird 支持的 SQL 标准正则表达式语法有点奇怪,并且不如其他语言中常见的正则表达式强大。

使用 PSQL

要使用 PSQL 解决此问题,在 Firebird 2.1 下,您可以使用以下内容:

create or alter procedure extract_number(input_value varchar(50)) 
    returns (output_value bigint)
as
declare char_position integer = 0;
declare number_string varchar(20) = '';
declare current_char char(1);
begin
  while (char_position < char_length(input_value)) do
  begin
    char_position = char_position + 1;
    current_char = substring(input_value from char_position for 1);
    if ('0' <= current_char and current_char <= '9') then
    begin
      number_string = number_string || current_char;
    end
    else if (char_length(number_string) > 0) then
    begin
      -- switching from numeric to non-numeric, found first number occurrence in string
      leave;
    end
  end
  output_value = iif(char_length(number_string) > 0, cast(number_string as bigint), null);
end

关于sql - 我可以在 Firebird POSITION 函数中使用通配符吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60921758/

相关文章:

SQL外部表列长度问题

c# - FireBird .net 提供商 64 位

delphi - 使用TIBDatabase连接到Delphi XE3上的Firebird 2.1数据库

ruby - 我如何在 Ruby 中标记这个字符串?

android - AutoCompleteTextView 建议未显示

sql - 如何将格式传递给 postgresql 中的 to_timestamp?

java - 如何解析Java Swing文本框中输入的磁条卡数据?

javascript - 如何将 XML 等文本解析为 javascript 对象

sql - 检索 Oracle 最后插入的 IDENTITY

database - 计算 Firebird 3.0 bigint 与 Firebird 2.5 整数