在concat文本之后我得到null

zqdjd7g9  于 2021-08-13  发布在  Java
关注(0)|答案(3)|浏览(373)

我尝试concat2字符串并将其反转,但在结果中我得到的是null,而不是ex的文本。第一个字符串“a1”第二个字符串“b2”结果“21ba”

CREATE function addToString(@val1 varchar(100),@val2 varchar(100))
returns varchar(200)
as
begin
    declare @i as int
    declare @output as varchar(200)
    if len(@val1)!=len(@val2)
        set @output='length error: '+cast(len(@val1) as varchar(10))+
        '<>'+cast(len(@val2) as varchar(10)) 
    else
        select @i=len(@val1)-1
        while @i>=0
            begin
                set @output= concat(@output,substring(@val2,@i,1))
                set @output= concat(@output,substring(@val1,@i,1))  
                set @i=@i-1
            end
    return @output
end
go
select dbo.[addToString]('a1','b2') as txt
blpfk2vs

blpfk2vs1#

你需要处理 NULL 价值观。最简单的方法可能是在存储过程的顶部用一个空字符串替换它:

select @val2 = coalesce(@val2, '');

或者,将参数声明为 NOT NULL 所以呢 NULL 不传入值。

jgwigjjp

jgwigjjp2#

您的逻辑错误,并且没有初始化@output:

CREATE function addToString(@val1 varchar(100),@val2 varchar(100))
returns varchar(200)
as
begin
    declare @i as int

 -- declare @output as varchar(200) -- initialized to NULL
    declare @output as varchar(200) = ''

    if len(@val1)!=len(@val2)
        set @output='length error: '+cast(len(@val1) as varchar(10))+
        '<>'+cast(len(@val2) as varchar(10)) 
    else
     -- select @i=len(@val1)-1 -- strips the last char
        select @i=len(@val1)

     -- while @i>=0
        while @i>0

            begin
                set @output= concat(@output,substring(@val2,@i,1))
                set @output= concat(@output,substring(@val1,@i,1))  
                set @i=@i-1
            end
    return @output
end
;
8wtpewkr

8wtpewkr3#

从len函数中删除-1

CREATE function addToString(@val1 varchar(100),@val2 varchar(100))
    returns varchar(200)
    as
    begin
        declare @i as int
        declare @output as varchar(200)
        if len(@val1)!=len(@val2)
            set @output='length error: '+cast(len(@val1) as varchar(10))+
            '<>'+cast(len(@val2) as varchar(10)) 
        else
            select @i=len(@val1)
            while @i>=0
                begin
                    set @output= concat(@output,substring(@val2,@i,1))
                    set @output= concat(@output,substring(@val1,@i,1))  
                    set @i=@i-1
                end
        return @output
    end
    go
    select dbo.[addToString]('a1','b2') as txt

相关问题