I have stored procedure in which I use scope_identity()
Create table table1
id int,
name varchar,
age int
Create procedure details
@id int,
@name varchar,
age int
Select @old_id = id , @name = name ,@age = age
from table1
where id = @id
if @old_id is null
begin
insert into table1(id, name , age)
Select scope_identity(), @name, @age
end
Error I get:
cannot insert null into id column, column does not allow null, insert fail
Any idea how to resolve this? Any help is appreciated.
I'm going to answer the why you're getting a
NULLhere, though it is unlikely that this answer will answer the qusetion you are really asking; of course I can't answer that question and you've never told us what that question is.As explained in all the comments,
SCOPE_IDENTITYreturns the value of the lastIDENTITYvalue generated within the current scope. To quote the documentation:In your procedure there is no prior
INSERT, so there is not prior generated value, thusSCOPE_IDENTITYcan only have the valueNULL. This, as a result, means that theINSERTstatement fails as your columnid(which I assume is actually a foreign key) cannot beNULL.A normal statement with the use of
SCOPE_IDENTITY()would look something like this:Note, as well, that you define your column/parameter
nameas avarchar(1). I would suggest fixing that as there are very few people, if any, who have a single character for their name.