将Varchar转换为Ascii

时间:2010-12-20 17:34:04

标签: tsql ssrs-2008

我正在尝试将VARCHAR字段的内容转换为可由第三方轻松引用的唯一编号。

如何将varchar转换为等效的ascii字符串?在TSQL中? ASCII()函数转换单个字符,但我该怎么做才能转换整个字符串?

我尝试过使用

CAST(ISNULL(ASCII(Substring(RTRIM(LTRIM(PrimaryContactRegion)),1,1)),'')AS VARCHAR(3))
+ CAST(ISNULL(ASCII(Substring(RTRIM(LTRIM(PrimaryContactRegion)),2,1)),'')AS VARCHAR(3))

....但这很乏味,看起来很愚蠢,如果我有很长的琴弦就行不通。或者,如果它更好,我将如何在SSRS中做同样的事情?

2 个答案:

答案 0 :(得分:13)

尝试这样的事情:

DECLARE @YourString   varchar(500)

SELECT @YourString='Hello World!'

;WITH AllNumbers AS
(
    SELECT 1 AS Number
    UNION ALL
    SELECT Number+1
        FROM AllNumbers
        WHERE Number<LEN(@YourString)
)
SELECT
       (SELECT
            ASCII(SUBSTRING(@YourString,Number,1))
            FROM AllNumbers
            ORDER BY Number
            FOR XML PATH(''), TYPE
       ).value('.','varchar(max)') AS NewValue
       --OPTION (MAXRECURSION 500) --<<needed if you have a string longer than 100

输出:

NewValue
---------------------------------------
72101108108111328711111410810033

(1 row(s) affected)

只是为了测试它:

;WITH AllNumbers AS
(
    SELECT 1 AS Number
    UNION ALL
    SELECT Number+1
        FROM AllNumbers
        WHERE Number<LEN(@YourString)
)
SELECT SUBSTRING(@YourString,Number,1),ASCII(SUBSTRING(@YourString,Number,1)),* FROM AllNumbers

输出:

                 Number
---- ----------- -----------
H    72          1
e    101         2
l    108         3
l    108         4
o    111         5
     32          6
W    87          7
o    111         8
r    114         9
l    108         10
d    100         11
!    33          12

(12 row(s) affected)

另外,您可能想要使用它:

RIGHT('000'+CONVERT(varchar(max),ASCII(SUBSTRING(@YourString,Number,1))),3)

将所有ASCII值强制为3位数,我不确定是否根据您的使用情况进行此操作。

每个字符使用3位数输出:

NewValue
-------------------------------------
072101108108111032087111114108100033

(1 row(s) affected)

答案 1 :(得分:0)

嗯,我认为解决这个问题的方法会很慢,但我想你可以这样做:

DECLARE @count INT, @string VARCHAR(100), @ascii VARCHAR(MAX)

SET @count = 1
SET @string = 'put your string here'
SET @ascii = ''

WHILE @count <= DATALENGTH(@string)
BEGIN
    SELECT @ascii = @ascii + '&#' + ASCII(SUBSTRING(@string, @count, 1)) + ';'
    SET @count = @count + 1
END

SET @ascii = LEFT(@ascii,LEN(@ascii)-1)
SELECT @ascii

我不是带有数据库引擎的电脑,所以我无法真正测试这段代码。如果可行,那么您可以基于此创建UDF。