-3

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.

Dale K
  • 25,246
  • 15
  • 42
  • 71

1 Answers1

0

I'm going to answer the why you're getting a NULL here, 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_IDENTITY returns the value of the last IDENTITY value generated within the current scope. To quote the documentation:

Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, if two statements are in the same stored procedure, function, or batch, they are in the same scope.

In your procedure there is no prior INSERT, so there is not prior generated value, thus SCOPE_IDENTITY can only have the value NULL. This, as a result, means that the INSERT statement fails as your column id (which I assume is actually a foreign key) cannot be NULL.

A normal statement with the use of SCOPE_IDENTITY() would look something like this:

INSERT INTO dbo.SomeTable (SomeColumn) --SomeTable has a column with the IDENTITY property
VALUES(@SomeValue);

INSERT INTO dbo.AnotherTable(ForeignKey, AnotherColumn)
VALUES(SCOPE_IDENTITY(), @AnotherValue);

Note, as well, that you define your column/parameter name as a varchar(1). I would suggest fixing that as there are very few people, if any, who have a single character for their name.

Thom A
  • 88,727
  • 11
  • 45
  • 75
  • there's another possibity - if an insert into `SomeTable` is done, but then other inserts are done into a non-identity table before the use of `scope_identity`, it will also be `null` - it should be saved into local variable immediately following the insert. – Stu Apr 09 '21 at 11:02
  • Though true, @Stu , I was simply demonstrating a `INSERT` preceded immediately by another `INSERT`. As we never got the *real* question from the OP, I felt it someone pointless to go completely in depth about the ins and outs of the function; they have a link to the documentation in the answer if they really want to read up on it's full behaviour. – Thom A Apr 09 '21 at 11:07