How can I output text until it is ascii in SQL?
Here is what I am trying to do:
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
But in the end I am getting an empty string. Why? What am I missing here?
I am expecting the value of the @output
to be 'text'
in the end of the script.
UPDATE
If I update the script to the
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-z]'
BEGIN
SET @output = @output + CHAR(ASCII(SUBSTRING(@input, @index, 1)))
SET @index = @index + 1
END
SELECT @output
It will work as expected. But here I just shrinked the set from all printable ascii characters to only small letters. Why does the shrinked set [a-z]
include the text
characters and the extended set [ -~]
does not?