如何在单个select语句中替换多个字符串?

时间:2016-06-03 22:00:11

标签: sql sql-server sql-server-2012

我试图替换表中的字符串,但无法得到我需要的东西。下面是我尝试替换strigns的示例代码。

问题:我需要更换字符串' CV7 + CV8'具有完全匹配的值。

例如:如果我有像CV7 1998,CV8 1998这样的值,需要替换为CV7 1998 + CV8 1998而没有任何重复。所以我想要的ouptut应该是

CV7 1998 + CV8 1998
CV7 1999 + CV8 1999
.
.

如何在单个selece声明中实现此目的?

 Begin
Declare @variable as varchar(50)
set @variable = 'CV7 + CV8'

CREATE TABLE #CVtableforallyears
(
Outcomedestination Varchar(160),
TimeDimensionDatefromCV date
)
 Insert into #CVtableforallyears values 
('CV7 1998','1998-01-01'),
('CV7 1999','1999-01-01'),
('CV7 2000','2000-01-01'), 
('CV7 2001','2001-01-01'),   
('CV7 2002','2002-01-01'),
('CV8 1998','1998-01-01'),
('CV8 1999','1999-01-01'),
('CV8 2000','2000-01-01'), 
('CV8 2001','2001-01-01'), 
('CV8 2002','2002-01-01')

Select Replace(REPLACE(@variable,'CV7',LTRIM (RTRIM (Outcomedestination))),'CV8',Outcomedestination) from #CVtableforallyears
Drop table #CVtableforallyears
END

2 个答案:

答案 0 :(得分:1)

这应该是你:

SELECT DISTINCT
  substring(
   (SELECT 
      DISTINCT ' + ' + t2.Outcomedestination
    FROM #CVtableforallyears t2 
    WHERE t2.TimeDimensionDatefromCV = t1.TimeDimensionDatefromCV
    FOR XML Path ('')  
    )
  ,4,1000) --just to omit the first ' + '
FROM #CVtableforallyears t1; 
END

适用于单人简历和超过2个。

编辑以减少不必要的内容。下面的示例演示如何使用FOR XML PATH,然后如何在完整查询中使用它。

基本上我们将整个查询连接成一个字符串,但使用''来分割自然<row>的位置;我们将每个结果与' + '连接起来。然后,使子查询仅选择与父查询匹配。使用DISTINCT来避免重复。不幸的是,TSQL中没有LISTAGG所以我们使用这种方法。

Here is an example

答案 1 :(得分:0)

您不需要使用REPLACE语句来执行此操作。

WITH cv7 AS
(
    SELECT 
        Outcomedestination,
        TimeDimensionDatefromCV,
        RIGHT(LTRIM(RTRIM(Outcomedestination)), 4) AS year
    FROM #CVtableforallyears
    WHERE LEFT(LTRIM(RTRIM(Outcomedestination)), 3) = N'CV8'
),
cv8 AS
(
    SELECT 
        Outcomedestination,
        TimeDimensionDatefromCV,
        RIGHT(LTRIM(RTRIM(Outcomedestination)), 4) AS year
    FROM #CVtableforallyears
    WHERE LEFT(LTRIM(RTRIM(Outcomedestination)), 3) = N'CV8'
)
SELECT cv7.Outcomedestination + N' + ' + cv8.Outcomedestination
FROM cv7
INNER JOIN cv8
ON cv7.year = cv8.year

结果如下:

CV8 1998 + CV8 1998
CV8 1999 + CV8 1999
CV8 2000 + CV8 2000
CV8 2001 + CV8 2001
CV8 2002 + CV8 2002