在sql server中的字符串的每个字符后面附加一个特定字符

时间:2014-07-24 08:47:50

标签: sql sql-server

感谢您为以下问题提供建议:

我使用下面的查询来获取列的值:

Select OptionList = case  when isnull(AS_CIS_Code,'') <> '' then AS_CIS_Code   
   else ''  
   end 
from added_services

AS_CIS_Code列是added_services表中的varchar(10)。它包含诸如AB&#39;,&#39; ABC&#39;,&#39; GHKIK&#39; UYTIOPJ&#39;等等代表不同的代码。

现在我必须在修改上述查询后选择这些代码,以便&#39; _&#39;在每个角色后附加。

喜欢它应该被提取为&#39; A_B _&#39;,&#39; A_B_C _&#39;,&#39; G_H_K_I_K _&#39;,&#39; U_Y_T_I_O_P_J _&#39;。

我该如何实施?使用临时表只会降低一列的性能,所以我应该使用while循环还是请建议我更好的替代方案。

4 个答案:

答案 0 :(得分:2)

试试这个:

DECLARE @Input VARCHAR(100) = 'TESTING'
DECLARE @Pos INT = LEN(@Input)
WHILE @Pos > 1
BEGIN

    SET @Input = STUFF(@Input,@Pos,0,'_')
    SET @Pos = @Pos - 1
END

SELECT @Input

<强>输出

T_E_S_T_I_N_G

<强> UDF

CREATE FUNCTION PadStr(@Data VARCHAR(100)) RETURNS VARCHAR(200)
AS
BEGIN
    DECLARE @Input VARCHAR(200) = @Data 
    DECLARE @Pos INT = LEN(@Input)
    WHILE @Pos > 1
    BEGIN

        SET @Input = STUFF(@Input,@Pos,0,'_')
        SET @Pos = @Pos - 1
    END

    RETURN @Input + '_'
END

<强>输出

SELECT dbo.PadStr('TESTING')      -- T_E_S_T_I_N_G_

答案 1 :(得分:0)

试试这个

Create Function Code_Pad
(
    @code varchar(max) 
)
returns varchar(max)
as
begin

Declare @coding varchar(max) =''
Declare @i int = 1

      WHILE(LEN(@Coding)<=2*len(@code)-1)
      begin
        Select @coding = @coding+SUBSTRING(@code,@i,1)+'_'
        set @i=@i+1
      end
return @coding
end

功能结束

Select OptionList = case  when isnull(AS_CIS_Code,'') <> '' then dbo.Code_Pad(AS_CIS_Code)   else ''  
   end 
from added_services

答案 2 :(得分:0)

可能不是最佳解决方案,但使用递归

在一个查询中工作
;WITH valCTE(Replaced,ToBeReplaced,Position)
AS
(
    SELECT CAST(LEFT(AS_CIS_Code,1) + '_' AS VARCHAR(20))
          ,SUBSTRING(AS_CIS_Code,2,LEN(AS_CIS_Code)-1)
          ,1
    FROM added_services

    UNION ALL
    SELECT CAST(Replaced + LEFT(ToBeReplaced,1) + '_' AS VARCHAR(20))
        ,SUBSTRING(ToBeReplaced,2,LEN(ToBeReplaced)-1)
        ,Position+1
    FROM valCTE
    WHERE LEN(ToBeReplaced)>0 
)
SELECT TOP 1 LEFT(Replaced,LEN(Replaced)-1) -- remove last _ 
FROM valCTE
ORDER BY Position DESC

答案 3 :(得分:0)

您可以使用数字表拆分字符串,然后使用for xml path()重建它。

select isnull(C.Value, '') as AS_CIS_Code 
from added_services as A
  cross apply (
              select substring(A.AS_CIS_Code, T.N, 1)+'_'
              from (values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) as T(N)
              where T.N <= len(A.AS_CIS_Code)
              order by T.N
              for xml path('')
              ) as C(Value)

SQL Fiddle