简体   繁体   中英

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 operation 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM