How to declare in stored procedure that a row does not exist?









up vote
0
down vote

favorite












I want to know if a certain QuestionID and EmployeeID exist; if they do, they need to be inserted like here below (that's working fine).



But if they don't exist, I want a good error for the user, so that he knows that the QuestionID or the EmployeeID or both do not exist. Also maybe a rollback of the transaction? Now I can add every number, but the stored procedure still completed the commands...



I have this code (I'm using SQL Server):



CREATE PROCEDURE Contentment
@employeeID INT,
@questionid INT
AS
BEGIN
IF EXISTS (SELECT questionid
FROM question
WHERE questionid = @questionid)
IF EXISTS (SELECT employeeID
FROM employee
WHERE employeeid = @employeeID)
BEGIN
INSERT INTO contentment (employeeid, questionid, date, score, comment)
VALUES (@employeeID, @questionid, null, null, null)
END
ELSE
IF @employeeID = 0
RAISERROR ('-certain error-', 16, 1, @employeeid)

IF @questionid = 0
RAISERROR ('-certain error-', 16, 1, @questionid)
END









share|improve this question



























    up vote
    0
    down vote

    favorite












    I want to know if a certain QuestionID and EmployeeID exist; if they do, they need to be inserted like here below (that's working fine).



    But if they don't exist, I want a good error for the user, so that he knows that the QuestionID or the EmployeeID or both do not exist. Also maybe a rollback of the transaction? Now I can add every number, but the stored procedure still completed the commands...



    I have this code (I'm using SQL Server):



    CREATE PROCEDURE Contentment
    @employeeID INT,
    @questionid INT
    AS
    BEGIN
    IF EXISTS (SELECT questionid
    FROM question
    WHERE questionid = @questionid)
    IF EXISTS (SELECT employeeID
    FROM employee
    WHERE employeeid = @employeeID)
    BEGIN
    INSERT INTO contentment (employeeid, questionid, date, score, comment)
    VALUES (@employeeID, @questionid, null, null, null)
    END
    ELSE
    IF @employeeID = 0
    RAISERROR ('-certain error-', 16, 1, @employeeid)

    IF @questionid = 0
    RAISERROR ('-certain error-', 16, 1, @questionid)
    END









    share|improve this question

























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I want to know if a certain QuestionID and EmployeeID exist; if they do, they need to be inserted like here below (that's working fine).



      But if they don't exist, I want a good error for the user, so that he knows that the QuestionID or the EmployeeID or both do not exist. Also maybe a rollback of the transaction? Now I can add every number, but the stored procedure still completed the commands...



      I have this code (I'm using SQL Server):



      CREATE PROCEDURE Contentment
      @employeeID INT,
      @questionid INT
      AS
      BEGIN
      IF EXISTS (SELECT questionid
      FROM question
      WHERE questionid = @questionid)
      IF EXISTS (SELECT employeeID
      FROM employee
      WHERE employeeid = @employeeID)
      BEGIN
      INSERT INTO contentment (employeeid, questionid, date, score, comment)
      VALUES (@employeeID, @questionid, null, null, null)
      END
      ELSE
      IF @employeeID = 0
      RAISERROR ('-certain error-', 16, 1, @employeeid)

      IF @questionid = 0
      RAISERROR ('-certain error-', 16, 1, @questionid)
      END









      share|improve this question















      I want to know if a certain QuestionID and EmployeeID exist; if they do, they need to be inserted like here below (that's working fine).



      But if they don't exist, I want a good error for the user, so that he knows that the QuestionID or the EmployeeID or both do not exist. Also maybe a rollback of the transaction? Now I can add every number, but the stored procedure still completed the commands...



      I have this code (I'm using SQL Server):



      CREATE PROCEDURE Contentment
      @employeeID INT,
      @questionid INT
      AS
      BEGIN
      IF EXISTS (SELECT questionid
      FROM question
      WHERE questionid = @questionid)
      IF EXISTS (SELECT employeeID
      FROM employee
      WHERE employeeid = @employeeID)
      BEGIN
      INSERT INTO contentment (employeeid, questionid, date, score, comment)
      VALUES (@employeeID, @questionid, null, null, null)
      END
      ELSE
      IF @employeeID = 0
      RAISERROR ('-certain error-', 16, 1, @employeeid)

      IF @questionid = 0
      RAISERROR ('-certain error-', 16, 1, @questionid)
      END






      sql sql-server






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 11 at 11:09









      marc_s

      567k12810961247




      567k12810961247










      asked Nov 11 at 10:16









      DutchFatBoys

      406




      406






















          3 Answers
          3






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          I'd try to do it like this - check for the existence of both parameters in a single statement - if not, then provide an error:



          CREATE PROCEDURE dbo.Contentment
          @employeeID INT,
          @questionid INT
          AS
          BEGIN
          -- check for *both* conditions at once
          IF EXISTS (SELECT * FROM dbo.question WHERE questionid = @questionid) AND
          EXISTS (SELECT * FROM dbo.employee WHERE employeeid = @employeeID)
          BEGIN
          -- if OK --> insert
          INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
          VALUES (@employeeID, @questionid, null, null, null)
          END
          ELSE
          BEGIN
          -- if NOT OK --> provide error
          RAISERROR ('@EmployeeID or @QuestionID do not exist', 16, 1, null)
          END
          END



          Also maybe a rollback of the transaction?




          Since you're not really doing anything (no INSERT happening in either of the two ID's doesn't exist), there's really no transaction to roll back at this point....






          share|improve this answer





























            up vote
            0
            down vote













            you can use an error message parameter like that :



             CREATE PROC dbo.Usp_Contentment 
            AS
            begin
            declare @ErrMsg NVARCHAR(MAX) = ''
            IF not exists (select 1 from dbo.Question where QuestionId= @QuestionId)
            set @ErrMsg = 'Some msg'
            if not exists (select 1 from dbo.Employee where Employee Id= @EmployeeId)
            set @ErrMsg =@ErrMsg + 'some msg'

            IF @msg=''
            INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
            VALUES (@employeeID, @questionid, null, null, null)
            else
            RAISERROR(@ErrMsg,16,1)
            end


            don't use ROLLBACK because you handled the NULL Values






            share|improve this answer




















            • Could you maybe explain what you are doing with 'set @ErrMsg = @ErrMsg'? And with 'if @msg='') Thanks.
              – DutchFatBoys
              Nov 16 at 10:34










            • error message parameter's initial value is blank , if the first select was not exits fill parameter's with some message like 'could not find this question' if found question the parameter's value is still blank , then if could not find both of Question and Employee parameter will be somethings like this :'could not find Question' + 'could not find Employee' and after that if parameter is still blank , that means everything is ok and ready for insert
              – masoud
              Nov 18 at 9:09










            • Thanks, but if@MSG has to be @ErrMsg isn't it ?
              – DutchFatBoys
              Nov 20 at 13:21










            • oh sorry ,you are right
              – masoud
              Nov 21 at 14:40

















            up vote
            0
            down vote













            I would let the database do the work. Declare the table to have proper foreign key relationships:



            alter table contentment add constraint fk_conententment_question
            foreign key (questionid) references question(questionid);

            alter table contentment add constraint fk_conententment_employee
            foreign key (employeeid) references employee(employeeid);


            Then write the procedure as:



            CREATE PROCEDURE dbo.usp_Contentment (
            @employeeID INT,
            @questionid INT
            ) AS
            BEGIN
            INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
            VALUES (@employeeID, @questionid, null, null, null)
            END; -- usp_Contentment


            The database will generate an error that the foreign key relationship fails -- if there is no matching key.



            This approach is much better than doing the test yourself for several reasons:



            • The database ensures the data integrity, so you know the relationships are maintained regardless of where the data changes occur.

            • The integrity applies to both inserts and updates. There is no need to put checks in multiple places.

            • The integrity check is thread-safe, so if rows are being modified in the reference tables, the integrity check works.

            If you really want a customized message, you can catch the error in a try/catch block and have a customized error.






            share|improve this answer




















              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53247733%2fhow-to-declare-in-stored-procedure-that-a-row-does-not-exist%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              0
              down vote



              accepted










              I'd try to do it like this - check for the existence of both parameters in a single statement - if not, then provide an error:



              CREATE PROCEDURE dbo.Contentment
              @employeeID INT,
              @questionid INT
              AS
              BEGIN
              -- check for *both* conditions at once
              IF EXISTS (SELECT * FROM dbo.question WHERE questionid = @questionid) AND
              EXISTS (SELECT * FROM dbo.employee WHERE employeeid = @employeeID)
              BEGIN
              -- if OK --> insert
              INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
              VALUES (@employeeID, @questionid, null, null, null)
              END
              ELSE
              BEGIN
              -- if NOT OK --> provide error
              RAISERROR ('@EmployeeID or @QuestionID do not exist', 16, 1, null)
              END
              END



              Also maybe a rollback of the transaction?




              Since you're not really doing anything (no INSERT happening in either of the two ID's doesn't exist), there's really no transaction to roll back at this point....






              share|improve this answer


























                up vote
                0
                down vote



                accepted










                I'd try to do it like this - check for the existence of both parameters in a single statement - if not, then provide an error:



                CREATE PROCEDURE dbo.Contentment
                @employeeID INT,
                @questionid INT
                AS
                BEGIN
                -- check for *both* conditions at once
                IF EXISTS (SELECT * FROM dbo.question WHERE questionid = @questionid) AND
                EXISTS (SELECT * FROM dbo.employee WHERE employeeid = @employeeID)
                BEGIN
                -- if OK --> insert
                INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
                VALUES (@employeeID, @questionid, null, null, null)
                END
                ELSE
                BEGIN
                -- if NOT OK --> provide error
                RAISERROR ('@EmployeeID or @QuestionID do not exist', 16, 1, null)
                END
                END



                Also maybe a rollback of the transaction?




                Since you're not really doing anything (no INSERT happening in either of the two ID's doesn't exist), there's really no transaction to roll back at this point....






                share|improve this answer
























                  up vote
                  0
                  down vote



                  accepted







                  up vote
                  0
                  down vote



                  accepted






                  I'd try to do it like this - check for the existence of both parameters in a single statement - if not, then provide an error:



                  CREATE PROCEDURE dbo.Contentment
                  @employeeID INT,
                  @questionid INT
                  AS
                  BEGIN
                  -- check for *both* conditions at once
                  IF EXISTS (SELECT * FROM dbo.question WHERE questionid = @questionid) AND
                  EXISTS (SELECT * FROM dbo.employee WHERE employeeid = @employeeID)
                  BEGIN
                  -- if OK --> insert
                  INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
                  VALUES (@employeeID, @questionid, null, null, null)
                  END
                  ELSE
                  BEGIN
                  -- if NOT OK --> provide error
                  RAISERROR ('@EmployeeID or @QuestionID do not exist', 16, 1, null)
                  END
                  END



                  Also maybe a rollback of the transaction?




                  Since you're not really doing anything (no INSERT happening in either of the two ID's doesn't exist), there's really no transaction to roll back at this point....






                  share|improve this answer














                  I'd try to do it like this - check for the existence of both parameters in a single statement - if not, then provide an error:



                  CREATE PROCEDURE dbo.Contentment
                  @employeeID INT,
                  @questionid INT
                  AS
                  BEGIN
                  -- check for *both* conditions at once
                  IF EXISTS (SELECT * FROM dbo.question WHERE questionid = @questionid) AND
                  EXISTS (SELECT * FROM dbo.employee WHERE employeeid = @employeeID)
                  BEGIN
                  -- if OK --> insert
                  INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
                  VALUES (@employeeID, @questionid, null, null, null)
                  END
                  ELSE
                  BEGIN
                  -- if NOT OK --> provide error
                  RAISERROR ('@EmployeeID or @QuestionID do not exist', 16, 1, null)
                  END
                  END



                  Also maybe a rollback of the transaction?




                  Since you're not really doing anything (no INSERT happening in either of the two ID's doesn't exist), there's really no transaction to roll back at this point....







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 11 at 11:10

























                  answered Nov 11 at 10:55









                  marc_s

                  567k12810961247




                  567k12810961247






















                      up vote
                      0
                      down vote













                      you can use an error message parameter like that :



                       CREATE PROC dbo.Usp_Contentment 
                      AS
                      begin
                      declare @ErrMsg NVARCHAR(MAX) = ''
                      IF not exists (select 1 from dbo.Question where QuestionId= @QuestionId)
                      set @ErrMsg = 'Some msg'
                      if not exists (select 1 from dbo.Employee where Employee Id= @EmployeeId)
                      set @ErrMsg =@ErrMsg + 'some msg'

                      IF @msg=''
                      INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
                      VALUES (@employeeID, @questionid, null, null, null)
                      else
                      RAISERROR(@ErrMsg,16,1)
                      end


                      don't use ROLLBACK because you handled the NULL Values






                      share|improve this answer




















                      • Could you maybe explain what you are doing with 'set @ErrMsg = @ErrMsg'? And with 'if @msg='') Thanks.
                        – DutchFatBoys
                        Nov 16 at 10:34










                      • error message parameter's initial value is blank , if the first select was not exits fill parameter's with some message like 'could not find this question' if found question the parameter's value is still blank , then if could not find both of Question and Employee parameter will be somethings like this :'could not find Question' + 'could not find Employee' and after that if parameter is still blank , that means everything is ok and ready for insert
                        – masoud
                        Nov 18 at 9:09










                      • Thanks, but if@MSG has to be @ErrMsg isn't it ?
                        – DutchFatBoys
                        Nov 20 at 13:21










                      • oh sorry ,you are right
                        – masoud
                        Nov 21 at 14:40














                      up vote
                      0
                      down vote













                      you can use an error message parameter like that :



                       CREATE PROC dbo.Usp_Contentment 
                      AS
                      begin
                      declare @ErrMsg NVARCHAR(MAX) = ''
                      IF not exists (select 1 from dbo.Question where QuestionId= @QuestionId)
                      set @ErrMsg = 'Some msg'
                      if not exists (select 1 from dbo.Employee where Employee Id= @EmployeeId)
                      set @ErrMsg =@ErrMsg + 'some msg'

                      IF @msg=''
                      INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
                      VALUES (@employeeID, @questionid, null, null, null)
                      else
                      RAISERROR(@ErrMsg,16,1)
                      end


                      don't use ROLLBACK because you handled the NULL Values






                      share|improve this answer




















                      • Could you maybe explain what you are doing with 'set @ErrMsg = @ErrMsg'? And with 'if @msg='') Thanks.
                        – DutchFatBoys
                        Nov 16 at 10:34










                      • error message parameter's initial value is blank , if the first select was not exits fill parameter's with some message like 'could not find this question' if found question the parameter's value is still blank , then if could not find both of Question and Employee parameter will be somethings like this :'could not find Question' + 'could not find Employee' and after that if parameter is still blank , that means everything is ok and ready for insert
                        – masoud
                        Nov 18 at 9:09










                      • Thanks, but if@MSG has to be @ErrMsg isn't it ?
                        – DutchFatBoys
                        Nov 20 at 13:21










                      • oh sorry ,you are right
                        – masoud
                        Nov 21 at 14:40












                      up vote
                      0
                      down vote










                      up vote
                      0
                      down vote









                      you can use an error message parameter like that :



                       CREATE PROC dbo.Usp_Contentment 
                      AS
                      begin
                      declare @ErrMsg NVARCHAR(MAX) = ''
                      IF not exists (select 1 from dbo.Question where QuestionId= @QuestionId)
                      set @ErrMsg = 'Some msg'
                      if not exists (select 1 from dbo.Employee where Employee Id= @EmployeeId)
                      set @ErrMsg =@ErrMsg + 'some msg'

                      IF @msg=''
                      INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
                      VALUES (@employeeID, @questionid, null, null, null)
                      else
                      RAISERROR(@ErrMsg,16,1)
                      end


                      don't use ROLLBACK because you handled the NULL Values






                      share|improve this answer












                      you can use an error message parameter like that :



                       CREATE PROC dbo.Usp_Contentment 
                      AS
                      begin
                      declare @ErrMsg NVARCHAR(MAX) = ''
                      IF not exists (select 1 from dbo.Question where QuestionId= @QuestionId)
                      set @ErrMsg = 'Some msg'
                      if not exists (select 1 from dbo.Employee where Employee Id= @EmployeeId)
                      set @ErrMsg =@ErrMsg + 'some msg'

                      IF @msg=''
                      INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
                      VALUES (@employeeID, @questionid, null, null, null)
                      else
                      RAISERROR(@ErrMsg,16,1)
                      end


                      don't use ROLLBACK because you handled the NULL Values







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 11 at 11:54









                      masoud

                      11




                      11











                      • Could you maybe explain what you are doing with 'set @ErrMsg = @ErrMsg'? And with 'if @msg='') Thanks.
                        – DutchFatBoys
                        Nov 16 at 10:34










                      • error message parameter's initial value is blank , if the first select was not exits fill parameter's with some message like 'could not find this question' if found question the parameter's value is still blank , then if could not find both of Question and Employee parameter will be somethings like this :'could not find Question' + 'could not find Employee' and after that if parameter is still blank , that means everything is ok and ready for insert
                        – masoud
                        Nov 18 at 9:09










                      • Thanks, but if@MSG has to be @ErrMsg isn't it ?
                        – DutchFatBoys
                        Nov 20 at 13:21










                      • oh sorry ,you are right
                        – masoud
                        Nov 21 at 14:40
















                      • Could you maybe explain what you are doing with 'set @ErrMsg = @ErrMsg'? And with 'if @msg='') Thanks.
                        – DutchFatBoys
                        Nov 16 at 10:34










                      • error message parameter's initial value is blank , if the first select was not exits fill parameter's with some message like 'could not find this question' if found question the parameter's value is still blank , then if could not find both of Question and Employee parameter will be somethings like this :'could not find Question' + 'could not find Employee' and after that if parameter is still blank , that means everything is ok and ready for insert
                        – masoud
                        Nov 18 at 9:09










                      • Thanks, but if@MSG has to be @ErrMsg isn't it ?
                        – DutchFatBoys
                        Nov 20 at 13:21










                      • oh sorry ,you are right
                        – masoud
                        Nov 21 at 14:40















                      Could you maybe explain what you are doing with 'set @ErrMsg = @ErrMsg'? And with 'if @msg='') Thanks.
                      – DutchFatBoys
                      Nov 16 at 10:34




                      Could you maybe explain what you are doing with 'set @ErrMsg = @ErrMsg'? And with 'if @msg='') Thanks.
                      – DutchFatBoys
                      Nov 16 at 10:34












                      error message parameter's initial value is blank , if the first select was not exits fill parameter's with some message like 'could not find this question' if found question the parameter's value is still blank , then if could not find both of Question and Employee parameter will be somethings like this :'could not find Question' + 'could not find Employee' and after that if parameter is still blank , that means everything is ok and ready for insert
                      – masoud
                      Nov 18 at 9:09




                      error message parameter's initial value is blank , if the first select was not exits fill parameter's with some message like 'could not find this question' if found question the parameter's value is still blank , then if could not find both of Question and Employee parameter will be somethings like this :'could not find Question' + 'could not find Employee' and after that if parameter is still blank , that means everything is ok and ready for insert
                      – masoud
                      Nov 18 at 9:09












                      Thanks, but if@MSG has to be @ErrMsg isn't it ?
                      – DutchFatBoys
                      Nov 20 at 13:21




                      Thanks, but if@MSG has to be @ErrMsg isn't it ?
                      – DutchFatBoys
                      Nov 20 at 13:21












                      oh sorry ,you are right
                      – masoud
                      Nov 21 at 14:40




                      oh sorry ,you are right
                      – masoud
                      Nov 21 at 14:40










                      up vote
                      0
                      down vote













                      I would let the database do the work. Declare the table to have proper foreign key relationships:



                      alter table contentment add constraint fk_conententment_question
                      foreign key (questionid) references question(questionid);

                      alter table contentment add constraint fk_conententment_employee
                      foreign key (employeeid) references employee(employeeid);


                      Then write the procedure as:



                      CREATE PROCEDURE dbo.usp_Contentment (
                      @employeeID INT,
                      @questionid INT
                      ) AS
                      BEGIN
                      INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
                      VALUES (@employeeID, @questionid, null, null, null)
                      END; -- usp_Contentment


                      The database will generate an error that the foreign key relationship fails -- if there is no matching key.



                      This approach is much better than doing the test yourself for several reasons:



                      • The database ensures the data integrity, so you know the relationships are maintained regardless of where the data changes occur.

                      • The integrity applies to both inserts and updates. There is no need to put checks in multiple places.

                      • The integrity check is thread-safe, so if rows are being modified in the reference tables, the integrity check works.

                      If you really want a customized message, you can catch the error in a try/catch block and have a customized error.






                      share|improve this answer
























                        up vote
                        0
                        down vote













                        I would let the database do the work. Declare the table to have proper foreign key relationships:



                        alter table contentment add constraint fk_conententment_question
                        foreign key (questionid) references question(questionid);

                        alter table contentment add constraint fk_conententment_employee
                        foreign key (employeeid) references employee(employeeid);


                        Then write the procedure as:



                        CREATE PROCEDURE dbo.usp_Contentment (
                        @employeeID INT,
                        @questionid INT
                        ) AS
                        BEGIN
                        INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
                        VALUES (@employeeID, @questionid, null, null, null)
                        END; -- usp_Contentment


                        The database will generate an error that the foreign key relationship fails -- if there is no matching key.



                        This approach is much better than doing the test yourself for several reasons:



                        • The database ensures the data integrity, so you know the relationships are maintained regardless of where the data changes occur.

                        • The integrity applies to both inserts and updates. There is no need to put checks in multiple places.

                        • The integrity check is thread-safe, so if rows are being modified in the reference tables, the integrity check works.

                        If you really want a customized message, you can catch the error in a try/catch block and have a customized error.






                        share|improve this answer






















                          up vote
                          0
                          down vote










                          up vote
                          0
                          down vote









                          I would let the database do the work. Declare the table to have proper foreign key relationships:



                          alter table contentment add constraint fk_conententment_question
                          foreign key (questionid) references question(questionid);

                          alter table contentment add constraint fk_conententment_employee
                          foreign key (employeeid) references employee(employeeid);


                          Then write the procedure as:



                          CREATE PROCEDURE dbo.usp_Contentment (
                          @employeeID INT,
                          @questionid INT
                          ) AS
                          BEGIN
                          INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
                          VALUES (@employeeID, @questionid, null, null, null)
                          END; -- usp_Contentment


                          The database will generate an error that the foreign key relationship fails -- if there is no matching key.



                          This approach is much better than doing the test yourself for several reasons:



                          • The database ensures the data integrity, so you know the relationships are maintained regardless of where the data changes occur.

                          • The integrity applies to both inserts and updates. There is no need to put checks in multiple places.

                          • The integrity check is thread-safe, so if rows are being modified in the reference tables, the integrity check works.

                          If you really want a customized message, you can catch the error in a try/catch block and have a customized error.






                          share|improve this answer












                          I would let the database do the work. Declare the table to have proper foreign key relationships:



                          alter table contentment add constraint fk_conententment_question
                          foreign key (questionid) references question(questionid);

                          alter table contentment add constraint fk_conententment_employee
                          foreign key (employeeid) references employee(employeeid);


                          Then write the procedure as:



                          CREATE PROCEDURE dbo.usp_Contentment (
                          @employeeID INT,
                          @questionid INT
                          ) AS
                          BEGIN
                          INSERT INTO dbo.contentment (employeeid, questionid, date, score, comment)
                          VALUES (@employeeID, @questionid, null, null, null)
                          END; -- usp_Contentment


                          The database will generate an error that the foreign key relationship fails -- if there is no matching key.



                          This approach is much better than doing the test yourself for several reasons:



                          • The database ensures the data integrity, so you know the relationships are maintained regardless of where the data changes occur.

                          • The integrity applies to both inserts and updates. There is no need to put checks in multiple places.

                          • The integrity check is thread-safe, so if rows are being modified in the reference tables, the integrity check works.

                          If you really want a customized message, you can catch the error in a try/catch block and have a customized error.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 11 at 11:55









                          Gordon Linoff

                          748k34285391




                          748k34285391



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.





                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                              Please pay close attention to the following guidance:


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53247733%2fhow-to-declare-in-stored-procedure-that-a-row-does-not-exist%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              這個網誌中的熱門文章

                              Barbados

                              How to read a connectionString WITH PROVIDER in .NET Core?

                              Node.js Script on GitHub Pages or Amazon S3