在SQL中的特定字符之间抓取多个子字符串

时间:2018-09-04 14:45:50

标签: sql-server

我要提取最后一个“-”和最后一个“,”之间的四位数数字到其自己的列中。然后我想将月份和年份提取到另外两列中。

以下是我从我想推送到另外3列的列中获得的数据的示例:

“捕获的信用卡:Visa,xxxx-xxxx-xxxx-1234,12 / 20。设置为默认值。”

我希望输出为:

抄送:1234 月:12 年:20

对此有任何帮助。

2 个答案:

答案 0 :(得分:0)

如果您的字符串将采用上述一致的格式,请尝试以下内容。

DECLARE @string VARCHAR(MAX) = 'Captured Credit Card: Visa, xxxx-xxxx-xxxx-1234, 12/20. Set as Default.'

SELECT Column1 = 'CC:' + RIGHT(REPLACE(@string, RIGHT(@string, CHARINDEX(',', REVERSE(@string))),''), CHARINDEX('-', REVERSE(REPLACE(@string, RIGHT(@string, CHARINDEX(',', REVERSE(@string))),''))) -1),
    Column2 = 'Month: ' + SUBSTRING(@string,CHARINDEX('/', @string)-2,2),
    Column3 = 'Year: ' + SUBSTRING(@string,CHARINDEX('/', @string)+1,2)

答案 1 :(得分:0)

我尝试使用 <View style={{ flex: 1, flexDirection: 'row' }}> <View> <Text> Spaceship building </Text> <Text> Piano </Text> </View> <View style={{ flex: 1 }}> <Text style={{ marginLeft: 5 }}> • John F. Kennedy </Text> <Text style={{ marginLeft: 5 }}> • Francis Dunget </Text> </View> </View> 翻转字符串,然后使用REVERSE()从字符串末尾查找char位置。

然后,使用CHARINDEX()和减法,最后一个字符的位置就是它在原始(未翻转)字符串中的位置。

LEN()

对于函数中使用的正确索引,我必须加或减1或2。

产生输出:

DECLARE @temp varchar(1000) = 'Captured Credit Card: Visa, xxxx-xxxx-xxxx-1234, 12/20. Set as Default.'

SELECT 'CC: '
      + SUBSTRING(@temp
                 , LEN(@temp) - CHARINDEX('-', REVERSE(@temp), 0) + 2
                 , LEN(@temp) - CHARINDEX(',', REVERSE(@temp), 0) --find the last ','
                  -(LEN(@temp) - CHARINDEX('-', REVERSE(@temp), 0)) --find the last '-')
                  -1
                )
      + ' Month: '
      + SUBSTRING(@temp, CHARINDEX('/', @temp, 0) -2, 2)
      + ' Year: '
      + SUBSTRING(@temp, CHARINDEX('/', @temp, 0) + 1, 2)
      AS [output]
相关问题