将SQL字符串的一部分移动到另一个变量中

时间:2013-01-31 09:53:16

标签: sql sql-server

我有一个带有sql函数的项目有问题:

DECLARE @Var1 varchar(8000) = '{strong} this is strong{/strong} this is not strong.';

DECLARE @Var2 varchar(8000)

如果我想将'{strong}''{/strong}'之间的字符串移到@Var2以获得此结果

@Var1 = 'this is not strong.' 
@Var2 = '{strong} this is strong {/strong}' 

我该怎么办?

PS:我还是sql的新手:(

谢谢

3 个答案:

答案 0 :(得分:2)

尝试以下查询...它会帮助你......

declare @var1 varchar(8000)
declare @var2 varchar(8000)
set @var1 ='{strong} this is strong{/strong} this is not strong.'
select @var2 = substring(@var1,charindex('{strong}',@var1)+len('{strong}'),charindex('{/strong}',@var1)-charindex('{strong}',@var1)-len('{strong}'))
SET @var1 = REPLACE(@var1,'{strong}' + @var2 + '{/strong}','')
select @var1 as Var1,@var2 as Var2

答案 1 :(得分:0)

Sql不是做这样的事情的最佳选择

如果必须,就像有人用枪指着我的孩子一样

我会做这样的事情,可能需要调整你选择的sql风格

这是T-SQL

Declare v1 VarChar(255)
Declare v2 VarChar(255)


set v1 = '{Strong}$REPLACE${/Strong}'
set v2 = 'This is strong'

Select Replace(v1,'$REPLACE$',v2)

另一种方法是使用CharIndex来查找'} {/' 然后使用Substring来切断V1(作为'{Strong} {/ Strong}'),然后将它们与v2连接起来

答案 2 :(得分:0)

使用LEFTRIGHTCHARINDEX作为;

declare @start varchar(50)='{strong}', @end varchar(50)='{/strong}' 

select @var2 = left(@var1,charindex(@end,@var1,1)+len(@end)), 
       @var1= right(@var1,len(@var1)-(charindex(@end,@var1,1)+len(@end)))

SQL DEMO 1

这有点疯狂但是通用,并且也适用于一些文本before '{strong}' tag

declare 
@var1 varchar(100)= 'front text{strong} this is strong{/strong} this is not strong', 
@var2 varchar(100)= ''

declare @start varchar(50)='{strong}', @end varchar(50)='{/strong}' 

select @var2 = substring(myString,ci1,ci2+len(@end)-ci1), 
       @var1 = right(myString,len(myString) - (ci2+ len(@end)))
from (
    select @var1 myString, charindex(@start,@var1,1) ci1, 
           charindex(@end,@var1,charindex(@start,@var1,1)) ci2
) T  

select @var2 var2 ,@var1 var1

SQL DEMO 2

--Results
VAR2                                VAR1
{strong} this is strong{/strong}    this is not strong