• 5 Subscribers
  • 114 Views
1

I have two tables and a simple stored procedure. I want to use the stored procedure to insert into table1 with one of the parms being the primary key.

Here is where I am having trouble:

I want to have it so that if the parm/primary key the user has entered into the stored procedure and run is already on the table then it writes out the fields to a second table as well as the error description.

How do you capture / output this error information?

Stored procedure (sans the error logging):

CREATE PROCEDURE procedure1
   @Primary                        INT, 
   @Info                   NVARCHAR                   
AS 
BEGIN 
SET NOCOUNT ON 

 INSERT INTO Table1
      ( 
        Primary                  ,
        Info                   
      ) 
 VALUES 
      ( 
        @Primary                    ,
        @Info                   
      ) 

END 

Thanks


1 answers in total

1
Evaldas Buinauskas Posted at 2015-08-27 17:21:05Z
CREATE PROCEDURE dbo.InsertSomething
(
    @PrimaryKey INT
    , @Info NVARCHAR(MAX)
)
AS
BEGIN
    IF EXISTS (SELECT 1 FROM dbo.Table1 WHERE ID = @PrimaryKey)
    BEGIN
        INSERT INTO dbo.Table2 (ID, Info)
        VALUES (@PrimaryKey, @Info);

        RAISERROR (15600,-1,-1, 'Your custom message');
    END
    ELSE
    BEGIN
        INSERT INTO dbo.Table1 (ID, Info)
        VALUES (@PrimaryKey, @Info);
    END
END

All you have to do is a simple check if record already exists in first table, and if it does just insert into it and throw error.

Answer this questsion