Search code examples
sqlsql-serverdatabasestored-proceduresentity-attribute-value

Stored Procedure for multiple inserts with exiting if one fails


I have an EAV table, for each separate attribute I have a new row, something like this:

PersonID AtributeName AtributeValue
-----------------------------------
1         Name           John
1         Gender         Male
1         Height         170

The problem is that if I want to insert a new Person (with ID 2, name Jack, Male, Height 180) I need 3 more inserts, and there are changes that one ore more could fail. I was thinking of including all this inserts in a stored procedures with parameters (ID, Name, Gender, Height, etc..).

My question is, doing something like this:

CREATE PROCEDURE dbo.InserSubject 
    @ID int, 
    @Name varchar(50), 
    @Gender varchar(50), 
    @Height int
AS
    INSERT INTO Subjects 
    VALUES (1, 'Name', 'John'),
           (1, 'Gender', 'Male'),  
           (1, 'Height', 170); 

Will fail if one of the inserts fail? Is that kind of implementation for this kind of database/table?


Solution

  •  CREATE PROCEDURE dbo.InserSubject @ID int, @Name varchar(50), @Gender     varchar(50), @ Height int
        AS
      BEGIN TRY
          INSERT into Subjects Values (1,'Name','John'),(1,'Gender','Male'),  
           (1,'Height',170); 
      END TRY
      BEGIN CATCH
          error_message()
      END CATCH