sqlserver中字符串相加为null

我写了这样一段代码,理想的结果是输出一段相连接的字符串,但是结果并不是如此,最后输出的结果是null

create function GetStudentInfoByFirstname(@firstname nchar(1)) returns nvarchar(200)
begin
    declare @result nvarchar(200);
    declare @sname nchar(5),@sex nchar(1),@height numeric(4,2),@birthDate datetime, @address nvarchar(20);
    declare @totalHeight float = 0, @count int = 0;
    declare student_cursor cursor for
    select sname,sex,height,birth,address from student where left(sname,1)=@firstname;
    open student_cursor;
    fetch next from student_cursor into @sname,@sex,@height,@birthDate,@address;
    while @@FETCH_STATUS=0
    begin
        if @sex='男'
        begin
            set @result = @result + @sname + ', ' + @sex + ', 身高: ' + convert(nvarchar(5),@height) + '; ';
        end
        else
        begin
            set @result = @result + @sname + ', ' + @sex + ', 出生日期: ' + convert(nvarchar(10), @birthDate, 23) + ', 地址: ' + @address + '; '; 
        end
        set @totalHeight = @totalHeight + @height;
        set @count = @count + 1;
        fetch next from student_cursor into @sname,@sex,@height,@birthDate,@address;
    end
    close student_cursor;
    deallocate student_cursor;
    if @count>0
    begin
        set @result = @result + ' 平均身高: ' + convert(nvarchar(20),@totalHeight / @count);
    end
    else
    begin
        set @result = @result + ' 无此姓氏的学生。';    
    end
    return @result
end

 

结果是null让我很迷惑,找了半天的问题,最后发现是因为我的result也就是我返回的字符串没有进行初始化。

代码中有一个小错误,可能导致 @result 变量最后返回 null。这是因为在 SQL Server 中,null 值与任何其他值(包括空字符串)相连接都会返回 null。在这段代码中,在未初始化的 @result 变量(默认为 null)后加入字符串,导致最后的结果也为 null。

只需要将声明result的那行代码改为:

declare @result nvarchar(200) = '';

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值