使用CASE插入语句以避免重复行插入

时间:2012-06-12 04:19:03

标签: sql-server sql-server-2008 sql-server-2005

在将行插入表之前,我编写了以下存储过程来检查重复项。

但我无法在INSERT内写下CASE语句。

如何编写用于检查@Ordername值的存储过程,如果不存在则应将其插入数据库中。

       CREATE PROCEDURE [Test Procedure ]
          (
          @section varchar(70), 
          @mark varchar(70),
          @qty decimal(18,2),
          @Weight decimal(18,2),
          @dateupdateremark int,
          @OrderName varchar(70)
           )
          AS
       BEGIN
   SET NOCOUNT ON;

       select case(@OrderName)
       when (select OrderName from dbo.tbl_insertxmldetails 
       where(@OrderName) not in (select OrderName from tbl_insertxmldetails))

       then 
       insert into dbo.tbl_insertxmldetails 
       (Section, Mark, QTY,Weight,Dateupdateremark ,OrderName,SystemDate)
       values
       (@Section, @Mark, @QTY,@Weight, @Dateupdateremark,@OrderName,GETDATE())
       else 'File already Exists'
 end

2 个答案:

答案 0 :(得分:2)

使用If not exists子句而不是将解决问题的case语句

CREATE PROCEDURE [Test Procedure ]
          (
          @section varchar(70), 
          @mark varchar(70),
          @qty decimal(18,2),
          @Weight decimal(18,2),
          @dateupdateremark int,
          @OrderName varchar(70)
           )
          AS
       BEGIN
   SET NOCOUNT ON;


      if not exists (select OrderName from dbo.tbl_insertxmldetails 
       where(@OrderName) not in (select OrderName from tbl_insertxmldetails))

      Begin

         insert into dbo.tbl_insertxmldetails 
         (Section, Mark, QTY,Weight,Dateupdateremark ,OrderName,SystemDate)
         values
         (@Section, @Mark, @QTY,@Weight, @Dateupdateremark,@OrderName,GETDATE())

      End

       else
           Select 'File already Exists'

答案 1 :(得分:1)

无需使用NOT IN,您可以这样做

 IF NOT EXISTS(select OrderName from dbo.tbl_insertxmldetails Where OrderName=@OrderName)
 BEGIN

   insert into dbo.tbl_insertxmldetails 
   (Section, Mark, QTY,Weight,Dateupdateremark ,OrderName,SystemDate)
   values
   (@Section, @Mark, @QTY,@Weight, @Dateupdateremark,@OrderName,GETDATE())
END
   ELSE
     'File already Exists'