插入存储过程,检查行是否存在

时间:2011-03-11 14:52:49

标签: sql-server-2005 stored-procedures insert

我正在使用sql server 2005并希望在数据库表中插入一行,但是我的值语法不正确。而且我想确定我添加的内容已经不存在我认为这是正确的但我有一个语法错误。

 create PROCEDURE [dbo].[directway]
           @tour as varchar(50),
           @tourname as varchar(50),
           @taskname as varchar(50) ,
           @deptdate as varchar(50),
           @tasktype as varchar(50)  ,
           @desc as varchar(50) ,
           @duedate as varchar(50) ,
           @agent as varchar(50),
           @graceperiod as varchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;


INSERT INTO dashboardtasks
           ([tour]
           ,[tourname]
           ,[taskname]
           ,[deptdate]
           ,[tasktype]
           ,[desc]
           ,[duedate]
           ,[agent]
           ,[graceperiod]

     VALUES (@tour,
           @tourname,
           @taskname ,
           @deptdate,
           @tasktype  ,
           @desc ,
           @duedate ,
           @agent ,
           @graceperiod
                  )
WHERE  NOT EXISTS(SELECT *
                  FROM   dashboardtasks
                  WHERE  ( @tour = dashboardtasks.tour
                           and @taskname = dashboardtasks.taskname
                           and @deptdate = dashboardtasks.deptdate
                           and @duedate = dashboardtasks.duedate
                           and  @tourname = dashboardtasks.tourname
                         and @agent = dashboardtasks.agent
                         )
)  

END

1 个答案:

答案 0 :(得分:5)

你刚才有点错误的方式

IF NOT EXISTS(SELECT *
                  FROM   dashboardtasks
                  WHERE  ( @tour = dashboardtasks.tour
                           and @taskname = dashboardtasks.taskname
                           and @deptdate = dashboardtasks.deptdate
                           and @duedate = dashboardtasks.duedate
                           and  @tourname = dashboardtasks.tourname
                         and @agent = dashboardtasks.agent
                         )
)  
BEGIN
  INSERT INTO dashboardtasks
           ([tour]
           ,[tourname]
           ,[taskname]
           ,[deptdate]
           ,[tasktype]
           ,[desc]
           ,[duedate]
           ,[agent]
           ,[graceperiod])

     VALUES (@tour,
           @tourname,
           @taskname ,
           @deptdate,
           @tasktype  ,
           @desc ,
           @duedate ,
           @agent ,
           @graceperiod
                  )

END