我写了这样一段代码,理想的结果是输出一段相连接的字符串,但是结果并不是如此,最后输出的结果是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) = '';