【问题标题】:T-SQL Function to get ASCII values of characters stored获取存储字符的 ASCII 值的 T-SQL 函数
【发布时间】:2011-02-14 18:49:48
【问题描述】:

我正在使用 T-SQL 块来获取存储在数据库列中的 ascii 字符转储。我知道这很容易在 Oracle 中使用 DUMP() 函数完成。我对 SQL Server 语法不太熟悉,但我正在使用类似的东西。

    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 值作为单行返回,而不是为每个字符获取一行。难道我做错了什么?

【问题讨论】:

  • 你的意思是不会正确打印@output2?你有什么行为?
  • 是否有一些控制字符写入到 Output2 并且无法打印?
  • @output2 将始终打印“开始:”,这是我将其初始化的内容。我不确定控制字符,因为这是我想要找出的。

标签: sql tsql sql-server-2008 dump


【解决方案1】:

如果您正在寻找单行,这可能是最简单的方法(基于 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

【讨论】:

  • 谢谢。我现在正在尝试从中构建一个函数,以便它可以模仿 Oracle 的 DUMP() 函数
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多