Check record before inserting into table

Analyst_SQL 3,576 Reputation points
2021-06-05T07:41:36.32+00:00

Below is query i want to make it check before inserting into table,if (PID is null or PID=1) in #Probale table ,then record Update in #Probale table otherwise doesn't and
then Insert query in #tbl_Packdetail will execute

--Insert

        IF NOT EXISTS 
(
   SELECT *
   FROM Probale
   WHERE   Prdno=10000001 and (PID is null or PID=1)
)
Begin

   Update   Probale  set PID=111  where Prdno=10000001


   Begin

   INSERT  INTO tbl_PckDetail (PID,Codeitem,QTY,Orderno,Prdno) Values(111,111,1,111,10000001)
   end
   end


   Create table #Proble (Prdno int ,PID int)
   Create table #tbl_PackDetail (PID int,Codeitem int,qty int, Orderno int,Prdno int )
Developer technologies Transact-SQL
SQL Server Other
{count} votes

Accepted answer
  1. EchoLiu-MSFT 14,621 Reputation points
    2021-06-07T01:50:07.133+00:00

    Hi @Analyst_SQL ,

    According to your description, it seems that you only need to replace NOT EXISTS with EXISTS:

    Create table #Proble (Prdno int ,PID int)  
    Create table #tbl_PackDetail (PID int,Codeitem int,qty int, Orderno int,Prdno int )  
    Insert into #Proble values (10000001,Null)  
    Insert into #Proble values (10000001,1)  
    Insert into #Proble values (10000002,1)  
          
      
    SELECT * FROM #Proble    
    SELECT * FROM #tbl_PackDetail   
      
      
    IF EXISTS   
      (  
         SELECT *  
         FROM #Proble  
         WHERE   Prdno=10000001 and (PID is null or PID=1)  
      )  
    BEGIN  
              
         UPDATE  #Proble    
      SET PID=111    
      WHERE Prdno=10000001  
              
         BEGIN  
              
         INSERT  INTO #tbl_PackDetail (PID,Codeitem,QTY,Orderno,Prdno)   
      VALUES(111,111,1,111,10000001)  
         END  
    END  
    

    Output:
    102786-image.png

    Regards
    Echo

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Ronen Ariely 15,206 Reputation points
    2021-06-07T04:27:13.58+00:00

    Please do not open duplicate questions!

    I removed the duplicated question so people will be able to participate in the same discussion and not to have duplicate discussions

    Note: redirect from one thread to other is not a good idea here since it leave us with the other thread in the list of question which seems like no one respond to => therefore people keep checking the thread in order to answer it but they redirected to the other thread while the original will stay without answer for ever

    102863-image.png

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.