T-SQL函数用于获取存储的字符的ASCII值

时间:2011-02-14 18:49:48

标签: sql tsql sql-server-2008 dump

我正在使用T-SQL块来获取存储在数据库列中的ascii字符的转储。我知道这可以在Oracle中使用DUMP()函数轻松完成。我并不熟悉SQL Server sytax,但我使用的是这样的东西。

    SET NOCOUNT ON
-- Create the variables for the current character string position 
-- and for the character string.
DECLARE @position int, @string char(15), @output char(1000), @output2 char(2000)
-- Initialize the variables.
SET @position = 1
SET @output2 = 'Start:'
SELECT @string = name from 
location where location_type = 4405 and owner_id = 362
and location_id = 53183
WHILE @position <= DATALENGTH(@string)

       BEGIN
       SELECT @output = CAST(ASCII(SUBSTRING(@string, @position, 1)) AS CHAR)
        + ' ' +      CHAR(ASCII(SUBSTRING(@string, @position, 1)))
        PRINT @output
        --SET @output2 = @output2 + '=' + @output
        SET @position = @position + 1
       END
        --PRINT @output2 
    SET NOCOUNT OFF
    GO

出于某种原因,如果我取消注释与@ output2相关的代码,它将无法正确打印@ output2。 我们的想法是将所有ascii值作为单行返回,而不是为每个字符获取一行。难道我做错了什么?

2 个答案:

答案 0 :(得分:5)

如果您正在寻找单行,这可能是最简单的方法(基于Cyber​​ Kiwi的回答)

DECLARE @string char(15),
@output1 varchar(1000),
@output2 varchar(1000)

SELECT @string = name
from  location
where location_type = 4405 and owner_id = 362
and location_id = 53183

SET @output1 = ''
SET @output2 = ''

select 
    @output1 = @output1 + SUBSTRING(@string, number, 1) + ', ', 
    @output2 = @output2 + cast(ASCII(SUBSTRING(@string, number, 1)) as varchar) + ', '
from master..spt_values
where type='p' and number between 1 and LEN(@string)
order by number

PRINT @output1
PRINT @output2

答案 1 :(得分:2)

将@output和@ output2的数据类型更改为varchar。用Len替换DataLength。 Char是固定长度的,并且在字符串末尾添加字符串时不会增长。