简体   繁体   English

删除@符号之前和之后的文本字符串

[英]Stripping out the text string before and after @ symbol

Am stuck here and would greatly appreciate any help! 卡在这里,将不胜感激任何帮助!

R:£30 AT:63 RT:0 D .ADD £400 @63 WK R:£30 AT:63 RT:0 D .ADD£400 @ 63 WK

SQL Task: SQL任务:

1 - retrieve 400 (find symbol @ and take as many characters going left until reached £ symbol) 1-检索400(找到符号@,并向左移动尽可能多的字符,直到达到£符号)

2 - retrieve 63 (find @ symbol and get as many characters until found " " or "W" 2-检索63(找到@符号并获取尽可能多的字符,直到找到“”或“ W”

just use charIndex and substring. 只需使用charIndex和子字符串。 The example below is assuming that there can be £ after the @ as well. 下面的示例假设@之后也可以有£。 Basically, splitting the string at @, for the 2nd part, i'm going from @ to ' '. 基本上,将字符串拆分为@,对于第二部分,我将从@转到''。 the first part, reserve it, find £, then reverse it back. 第一部分,将其保留,找到£,然后将其取反。

declare @col varchar(500)
set @col = 'R:£30 AT:63 RT:0 D .ADD £400 @63 WK'
declare @p1 varchar(500),@p2 varchar(500) --split col into 2 at @


set @p1 = (reverse(substring(@col,1,CHARINDEX('@',@col)-1))) -- i will reverse here 
set @p2 = (substring(@col,CHARINDEX('@',@col)+1,LEN(@col)))


select @p1 p1, @p2 p2
    ,ltrim(rtrim(reverse(substring(@p1,1,CHARINDEX('£',@p1)-1)))) p1Final  -- do the same thing as we did to p1 and reserse it
    --also do a trim left and right to get rid of extra spaces 
    ,ltrim(rtrim(SUBSTRING(@p2,1,charIndex(' ',@p2)))) p2Final --this one should be self explanatory if you get the first one :)

You can also use the patindex function that can look for a pattern. 您也可以使用patindex函数来查找模式。

declare @col varchar(50)
set @col='R:£30 AT:63 RT:0 D .ADD £400 @63 WK'

--400
select substring(@col,patindex('% £% @%',@col)+2,charindex('@',@col)-(patindex('% £% @%',@col)+3))

--63
select substring(@col,charindex('@',@col)+1,charindex(' ',reverse(@col))-1)

Not sure about the efficiency, but to get you started 不确定效率,但是可以帮助您入门

For 1: I reversed the string and manipulated it and then reversed the result back 对于1:我反转了字符串并进行了处理,然后将结果反转了

declare @s varchar(500) = 'R:£30 AT:63 RT:0 D .ADD £23 £400 @63 WK'
declare @sRev varchar(500) = REVERSE(@s)
declare @stemp varchar(500)

declare @ampIndRev int, @AfterAmpIndRev int
set @ampIndRev = CHARINDEX( '@',@sRev,1)

set @AfterAmpIndRev =  charindex('£',@sRev, @ampIndRev) 

set @stemp = SUBSTRING(@sRev, @ampIndRev + 1, @AfterAmpIndRev-@ampIndRev-1)

set @stemp = REVERSE(Ltrim(@stemp))
select @stemp

For 2 (I assumed that you need to look for W only if there is no space): 对于2(我假设只有在没有空间的情况下才需要查找W):

declare @s varchar(500) = 'R:£30 AT:63 RT:0 D .ADD £400 @63 WK'
declare @ampInd int, @AfterAmpInd int
set @ampInd = CHARINDEX( '@',@s,1)

set @AfterAmpInd = CHARINDEX(' ',@s,@ampInd)
if @AfterAmpInd = 0
    set @AfterAmpInd = CHARINDEX('W',@s,@ampInd)

select SUBSTRING(@s, @ampInd + 1, @AfterAmpInd-@ampInd-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM