SQL Server中的存储过程多次插入相同的数据

时间:2018-05-27 19:30:03

标签: sql-server

我正忙于编写存储过程,但是当我运行该过程时,它会多次插入相同的数据,而我只希望它插入一次。我该如何阻止这种情况发生?

我的SQL代码:

CREATE PROCEDURE InsertEmployeeRecord
     (@EMP_NUM VARCHAR(3),  
      @Emp_LNAME VARCHAR(200), 
      @Emp_FNAME VARCHAR(200),  
      @EMP_INITIAL VARCHAR(50), 
      @EMP_HIREDATE DATETIME,  
      @JOB_CODE VARCHAR(20),  
      @EMP_YEARS INT)  
AS  
BEGIN
    INSERT INTO EMPLOYEE (EMP_NUM, EMP_LNAME, Emp_FNAME, EMP_INITIAL, EMP_HIREDATE, JOB_CODE, EMP_YEARS)    
    VALUES (@emp_num, @Emp_LNAME, @Emp_FNAME, @EMP_INITIAL, @EMP_HIREDATE, @JOB_CODE, @EMP_YEARS)  
END

EXEC InsertEmployeerecord   
        @emp_num = '119',  
        @Emp_LNAME = 'Lucas',  
        @Emp_FNAME = 'Khoza',   
        @EMP_INITIAL = 'L',   
        @EMP_HIREDATE = '2019-02-02',  
        @JOB_CODE = '526',   
        @EMP_YEARS = '2'; 

以下是发生的事情:

enter image description here

1 个答案:

答案 0 :(得分:1)

我的错误是单击执行按钮而不突出显示

<Timecode>

相反,我运行了整个代码:

    CREATE Procedure InsertEmployeerecord
 (  @EMP_NUM varchar (3),  
 @Emp_LNAME Varchar(200), 
  @Emp_FNAME  Varchar(200),  
  @EMP_INITIAL    Varchar(50), 
   @EMP_HIREDATE datetime ,  
   @JOB_CODE varchar(20),  
   @EMP_YEARS int  )  



   As  
   Begin    
   Insert into  EMPLOYEE(EMP_NUM,EMP_LNAME, Emp_FNAME, EMP_INITIAL, EMP_HIREDATE,JOB_CODE, EMP_YEARS)    
   Values (@emp_num, @Emp_LNAME, @Emp_FNAME,@EMP_INITIAL,@EMP_HIREDATE,@JOB_CODE,@EMP_YEARS)  
   End 

它以某种方式成倍增加,因此解决方案是首先运行 CREATE Procedure InsertEmployeerecord ( @EMP_NUM varchar (3), @Emp_LNAME Varchar(200), @Emp_FNAME Varchar(200), @EMP_INITIAL Varchar(50), @EMP_HIREDATE datetime , @JOB_CODE varchar(20), @EMP_YEARS int ) As Begin Insert into EMPLOYEE(EMP_NUM,EMP_LNAME, Emp_FNAME, EMP_INITIAL, EMP_HIREDATE,JOB_CODE, EMP_YEARS) Values (@emp_num, @Emp_LNAME, @Emp_FNAME,@EMP_INITIAL,@EMP_HIREDATE,@JOB_CODE,@EMP_YEARS) End EXEC InsertEmployeerecord @emp_num = '119', @Emp_LNAME = 'Lucas', @Emp_FNAME = 'Khoza', @EMP_INITIAL = 'L', @EMP_HIREDATE = '2019-02-02', @JOB_CODE = '526', @EMP_YEARS = '2'; ,然后分别运行CREATE Procedure InsertEmployeerecord