如何在 SQL 中输出文本直到它是 ascii?

How can I output text until it is ascii in SQL?

如何在 SQL 中将文本输出为 ascii?

这是我正在尝试做的事情:

DECLARE @input VARCHAR(20)
SET @input = 'text'

DECLARE @index INT
SET @index = 1

DECLARE @output VARCHAR(32)
SET @output = ''

WHILE CHAR(ASCII(SUBSTRING(@input, @index, 1))) LIKE '[ -~]'
BEGIN
    SET @output = @output + CHAR(ASCII(SUBSTRING(@input, @index, 1)))
    SET @index = @index + 1
END

SELECT @output

但最后我得到一个空字符串。为什么?我在这里错过了什么?

我希望脚本末尾 @output 的值是 'text'

更新

如果我将脚本更新为

DECLARE @input VARCHAR(20)
SET @input = 'text'

DECLARE @index INT
SET @index = 1

DECLARE @output VARCHAR(32)
SET @output = ''

WHILE CHAR(ASCII(SUBSTRING(@input, @index, 1))) LIKE '[a-b]'
BEGIN
    SET @output = @output + CHAR(ASCII(SUBSTRING(@input, @index, 1)))
    SET @index = @index + 1
END

SELECT @output

它将按预期工作。但在这里我只是将所有可打印的 ascii 字符集缩小到只有小字母。为什么收缩集 [a-b] 包含 text 个字符而扩展集 [ -~] 不包含?

A space 不是有效的范围分隔符,因此 LIKE [ -~] 将不起作用。这成为仅对这三个字符的测试。

您可以直接查看 ASCII 码,而不是使用 LIKE:

DECLARE @input VARCHAR(20)
SET @input = 'text'

DECLARE @index INT
SET @index = 1

DECLARE @output VARCHAR(32)
SET @output = ''

WHILE ASCII(SUBSTRING(@input, @index, 1)) BETWEEN 32 AND 126
BEGIN
    SET @output = @output + CHAR(ASCII(SUBSTRING(@input, @index, 1)))
    SET @index = @index + 1
END

SELECT @output

demo

旁注:可以得到 unexpected resultsLIKE 范围,因为比较是排序规则感知的。


从数据库管理员 duplicate question 上复制的答案