본문 바로가기
개발/SQL

SQL Insert 전 중복 체크 저장 프로시저

by 혈중마라농도 2022. 1. 15.

아래와 같이 테이블이 있다고 가정한다.

ID PK varchar(30)
Title   nvarchar(250)
Contents   nvarchar(max)
CreatedDate   datetime
IsDeleted   bit
GO  
-- =============================================  
-- Author:      <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
CREATE PROCEDURE [up_Insert_Test]
    @ID varchar(30),
    @TITLE nvarchar(250),
    @CONTENTS nvarchar(max),
    @ISDELETED bit
AS  
BEGIN  
    -- SET NOCOUNT ON added to prevent extra result sets from  
    -- interfering with SELECT statements.  
    SET NOCOUNT ON;  
 
 
  UPDATE 테이블
   SET
    TITLE = @TITLE,
    CONTENTS = @CONTENTS,
    ISDELETED = @ISDELETED
  WHERE ID = @ID
   
  IF @@ROWCOUNT = 0
  BEGIN
 
    INSERT INTO 테이블
    (
      ID,
      TITLE,
      CONTENTS,
      CREATEDDATE,
      ISDELETED
    )
    VALUES
    (
      @ID,
      @TITLE,
      @CONTENTS,
      GETDATE(),
      @ISDELETED
    )
 
  END
   
END  
GO
반응형

댓글