2016-03-01 46 views
1

看來我無法計算出如何在字符串中交換兩個彼此的varchar字符串。例如:mssql bcd字符串操作 - 交換字符串中的2位數

string : 6806642004683587 (varchar) end : 8660460240865378

它應該這樣工作:68 06 64 20 04 68 35 87和翻轉它們像86 60 46 ...

是否有在SQL函數,它BCD字符串操作?

謝謝

回答

2

你可以在一個函數把這個包,但這裏的基本代碼:

DECLARE @VAL NVARCHAR(16) = N'6806642004683587'; 
DECLARE @OUT NVARCHAR(16); 

;WITH A(N, S) AS (
    SELECT 1 N, SUBSTRING(@VAL, 1, 2) S 
    UNION ALL 
    SELECT N+2 N, SUBSTRING(@VAL, N+2, 2) S FROM A WHERE N+2 < LEN(@VAL) 
) 
SELECT @OUT = COALESCE(@OUT + '', '') + REVERSE(S) FROM A; 

SELECT @VAL, @OUT; 

---------------- ---------------- 
6806642004683587 8660460240865378 
1

能否使用while循環。

查詢

declare @str as varchar(max); 
declare @len as int; 
declare @i as int; 
declare @ii as int; 
declare @res as varchar(max); 
declare @res1 as varchar(max); 
set @str = '6806642004683587'; 
set @len = len(@str)/2; 
set @i = 1; 
set @ii = 1; 
set @res = ''; 

while @len >= @i 
begin 
    set @res1 = substring(@str, @ii, 2) 
    set @ii = @ii + 2; 
    set @i = @i + 1; 
    set @res += reverse(@res1) 
end 

select @str as [actual string], @res as [updated string]; 

結果

+------------------+------------------+ 
| actual string | updated string | 
+------------------+------------------+ 
| 6806642004683587 | 8660460240865378 | 
+------------------+------------------+ 

如果字符串len爲奇數,如果您還需要串聯的最後一個字符。然後將while @len >= @i更改爲while @len >= @i - 1

1

你可以使用一個數字表,無需任何循環,也可以

;with cte 
    as 
    (
    select 
    reverse(substring(@nn,n,2)) as n 
    from numbers 
    where n<=len(@nn) 
    and (n%2=0 or n=1) 
    ) 
    select 
    replace(stuff((SELECT ','+n 
    FROm cte 
     FOR XML PATH(''), TYPE).value('.', 'varchar(max)'),1,1,''),',','')