我有一列包含ASCII精简数字,无论如何将其转换为string(text)
?
例如,我在一列中有114097102097101108
,而我希望下一列是“ rafael”(从ASCII转换为文本)。
链接以转换http://www.unit-conversion.info/texttools/ascii/
。
答案 0 :(得分:0)
如果我理解正确,则可以使用递归CTE:
with cte as (
select '0' + convert(varchar(max), ascii(left(col, 1))) as rafael, stuff(col, 1, 1, '') as rest, 1 as lev, id, col
from t
union all
select rafael + ' 0' + convert(varchar(max), ascii(left(rest, 1))), stuff(rest, 1, 1, ''), lev + 1, id, col
from cte
where rest <> ''
)
select top (1) with ties id, col, rafael
from cte
order by row_number() over (partition by id order by lev desc);
Here是db <>小提琴。
答案 1 :(得分:0)
如果您有更大的字符串,则可以使用计数表的另一种方法:
WITH N AS(
SELECT N
FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL)) N(N)),
Tally AS(
SELECT TOP 8000 ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
FROM N N1, N N2, N N3, N N4),
Parts AS(
SELECT V.CatNum,
T.I
FROM (VALUES('114097102097101108'))V(CatNum)
JOIN Tally T ON LEN(V.CatNum) >= T.I
WHERE T.I % 3 = 0)
SELECT V.CatNum,
(SELECT CHAR(SUBSTRING(P.CatNum,LAG(P.I,1,0) OVER (ORDER BY P.I)+1,3))
FROM Parts P
WHERE P.CatNum = V.CatNum
FOR XML PATH(''),TYPE).value('.','varchar(8000)') AS NewString
FROM (VALUES('114097102097101108'))V(CatNum)
答案 2 :(得分:0)
您可以创建一个函数来完成此操作。这将处理最长3万个字符的字符串,并将其转换为1万个字符串。
CREATE FUNCTION dbo.ConvertASCIItoCHAR(
@String varchar(MAX)
)
RETURNS TABLE WITH SCHEMABINDING
AS RETURN
WITH
E(n) AS(
SELECT n FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))E(n)
),
E2(n) AS(
SELECT a.n FROM E a, E b
),
E4(n) AS(
SELECT a.n FROM E2 a, E2 b
),
cteTally(n) AS(
SELECT TOP( LEN(@String)/3) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) -1 n
FROM E4
)
SELECT ( SELECT CHAR(SUBSTRING( @String, n*3+1, 3))
FROM cteTally
FOR XML PATH(''), TYPE).value('./text()[1]', 'varchar(max)') AS String
现在您唯一需要做的就是调用该函数。
SELECT c.String
FROM dbo.ConvertASCIItoCHAR( '114097102097101108') c
或
SELECT c.String
FROM SomeTable st
CROSS APPLY dbo.ConvertASCIItoCHAR( st.SomeString) c