当我运行此SQL代码时:
declare @a as int=0;
declare @b as int=1;
declare @c as char(4)='c'
declare @d as varchar(4)='d'
set @c = @c + cast(@a as char(1)) + cast(@b as char(1))
select @c
set @d = @d + cast(@a as char(1)) + cast(@b as char(1))
select @d
它返回
c
d01
有没有办法成功将数字转换为char并添加到char(n)
变量?
我也想知道为什么会这样。
答案 0 :(得分:1)
来自MSDN
char [(n)]
固定长度的非Unicode字符串数据。 n定义了 字符串长度,必须是1到8,000之间的值。存储 大小是n个字节。
@a
变量已占用4个字节,因此您无法再添加任何字符。
declare @c as char(4)='c'
这里已经@c
占用了四个字节,即使您只传递了一个字节c
。
当您使用@c
分配@c + cast(@a as char(1)) + cast(@b as char(1))
时
转换为4 + 1 + 1 = 6 @c
无法容纳。
答案 1 :(得分:0)
试试这个:
declare @a as int=0;
declare @b as int=1;
declare @c as char(4)='c' -- here @c = 'c '
declare @d as varchar(4)='d'
set @c = RTrim( @c ) + cast(@a as char(1)) + cast(@b as char(1))
select @c
set @d = @d + cast(@a as char(1)) + cast(@b as char(1))
select @d
如果你不修剪@c,已经满了(有3个空格),所以其他所有动作都会被截断。