I wanted to create a small cte for the chars [az]. However if I use the char()-function for the recursive part like this:
with cte(chars)
as (
select cast('a' as char) as chars
union all
select char(ascii(chars) + 1 ) from cte
where chars < 'z'
)
select *
from cte
the data-types don't match even tho char() returns a char(1). But if the char()-function is casted to char(1), it runs perfectly fine:
with cte(chars)
as (
select cast('a' as char) as chars
union all
select cast(char(ascii(chars) + 1 ) as char) from cte
where chars < 'z'
)
select *
from cte
Am I missing something?
In SQL Server, never use char()
(and related types) without a length. The default length varies by context -- and who wants to keep track of such things?
The following works:
with cte(chars) as (
select cast('a' as char(1)) as chars
union all
select char(ascii(chars) + 1 ) from cte
where chars < 'z'
)
select *
from cte;
In other words, the default length for a char()
in a cast()
is different from the default length in a declare
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.