【问题标题】:Extracting a string between a known string and the last character提取已知字符串和最后一个字符之间的字符串
【发布时间】:2019-10-24 19:45:43
【问题描述】:

我正在尝试从已知字符串和最后一个字符之间提取一个字符串。我需要提取两个不同的美元值,没有美元符号。我可以得到第一个,但第二个总是失败。问题是最后一个字符(句点/小数)在数据中多次存在。我的查询将正确返回第一个金额 109.99,但它返回一个空白而不是第二个金额 89.99。此外,美元金额的字符长度可能会有所不同,因此我不能使用固定长度来拉回所需的结果。

DECLARE @string VARCHAR(MAX);

SET @string = 'amount changed from $109.99 to $89.99.';

SELECT

CASE

WHEN CHARINDEX(' to ', @string) - (CHARINDEX('amount changed from $', @string) + LEN('amount changed from $')) < 0 THEN ''

ELSE SUBSTRING(@string, CHARINDEX('amount changed from $', @string) + LEN('amount changed from $'), CHARINDEX(' to ', @string) - (CHARINDEX('amount changed from $', @string) + LEN('amount changed from $')))

END AS Amount_A,

CASE

WHEN CHARINDEX('.', @string) - (CHARINDEX(' to $', @string) + LEN(' to $')) < 0 THEN ''

ELSE SUBSTRING(@string, CHARINDEX(' to $', @string) + LEN(' to $'), CHARINDEX('.', @string) - (CHARINDEX(' to $', @string) + LEN(' to $')))

END AS Amount_B;

【问题讨论】:

  • 您使用的是哪个 dbms? (上面的代码是特定于产品的。)
  • 字符串中有 3 个点 (.) 所以 CHARINDEX('.', @string) - (CHARINDEX(' to $', @string) + LEN(' to $'))

标签: sql substring


【解决方案1】:

这可能并不优雅,但它确实有效。参见 cmets 的解释。 reverse() 在这里有很大帮助。 FTR,这里只需要两个SELECT,其余的只是为了澄清。

DECLARE @string VARCHAR(MAX);
SET @string = 'amount changed from $109.99 to $89.99.';
-- position of first $:
print charindex('$',@string)
-- position of first space after first $:
print charindex(' ', @string,charindex('$',@string))
-- the length between first $ and first space after first $:
print charindex(' ', @string, charindex('$',@string))-charindex('$',@string)-1
-- combine to select the first value:
select substring(@string,charindex('$',@string)+1, charindex(' ', @string, charindex('$',@string))-charindex('$',@string)-1)

-- the second $ sign (first $ after first $), plus 1 cause we don't want the $ itself:
print charindex('$',@string,charindex('$',@string)+1)+1
-- first $ from behind gives us the length of the string from second $ to the end:
print charindex('$',reverse(@string),0)-1
-- we don't want the last dot:
print charindex('$',reverse(@string),0)-2
-- combine to select the first value:
select substring(@string, charindex('$',@string,charindex('$',@string)+1)+1, charindex('$',reverse(@string),0)-2)

【讨论】:

  • 这正是我所需要的。感谢您的协助。
猜你喜欢
  • 2013-07-25
  • 1970-01-01
  • 2020-11-13
  • 2020-11-05
  • 2021-08-03
  • 2019-05-06
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多