开发者

sql function in stored procedure

I have a scalar function for formatting the text into uppercase and remove leading, trailing spaces etc. During an insert ope开发者_高级运维ration in a stored procedure, I'm invoking the function like this:

insert into tablename(col1,col2) values ( dbo.function_name(value1),value2)

Here the col1 is NOT NULL. The above statement is throwing an error "Attempting to set a non-NULL-able column's value to NULL". But if you run the function alone, it return the value properly.

Please help explain where I'm going wrong.


insert into table(Col1,Col2)
values (isnull(dbo.function_name(value1),''),value2)


How about you try placing the value in a variable first and to help when you debug it.

DECLARE @val1 varchar(100)
SET @val1 = dbo.function_name(value1)
PRINT @val1 -- print it to see if we get what we expect.

SET @val1 = isnull(@val1,'') -- We can also check for null

insert into tablename(col1,col2) values ( @val1,value2)

This will at least confirm what is happening during execution and you can confirm the function is operating as you expect.


Could you add a short but complete example that actually demonstrates the problem to your question. The following does not produce any errors, but I'm having to guess in a lot of places:

create table tablename (
    col1 varchar(20) not null,
    col2 varchar(10) null
)
go
create function dbo.function_name (
    @InVal varchar(20)
)
returns varchar(20)
as
begin
    return UPPER(LTRIM(RTRIM(@InVal)))
end
go
create procedure dbo.procname
    @value1 varchar(20),
    @value2 varchar(10)
as
insert into tablename(col1,col2) values ( dbo.function_name(@value1),@value2)
go
exec dbo.procname '   abc   ','def'
go
select * from tablename

Result:

col1   col2
ABC    def
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜