使用“if Not Exists”输入一条记录

时间:2011-09-11 20:28:58

标签: sql not-exists

我正在尝试在Meeting表中找到一条记录,其中包含相同的Modified_user_id,assigned_user_id,Name,date_start,date_end,created_by作为要保存的记录。只有在会议表中不存在新记录时才应添加新记录。

当我运行它时,即使表中已有匹配的记录,也会添加记录。

我错过了什么?

感谢您的帮助。

ALTER PROCEDURE Add_Follow_up_From_Lead
@MODIFIED_USER_ID AS VARCHAR (250) = MODIFIED_USER_ID ,

@ASSIGNED_USER_ID AS VARCHAR (250) =MODIFIED_USER_ID,
@NAME nvarchar (50) = NAME,
@DATE_START AS VARCHAR (250) = DATE_START,
@DATE_END AS VARCHAR (250) = DATE_END,
@CREATED_BY AS VARCHAR (250) = CREATED_BY 

AS
BEGIN
SET NOCOUNT ON;

IF NOT (EXISTS (select name from meetings where name = @name)
AND 
EXISTS (SELECT DATE_START FROM MEETINGS WHERE DATE_START = @DATE_START)
AND 
EXISTS (SELECT DATE_END FROM MEETINGS WHERE DATE_END = @DATE_END)
AND
EXISTS (SELECT CREATED_BY FROM MEETINGS WHERE CREATED_BY = @CREATED_BY)) 


insert into meetings(MODIFIED_USER_ID,ASSIGNED_USER_ID,NAME,
DATE_START ,DATE_END,CREATED_BY ) 
,TIME_START,STATUS,duration_hours,duration_minutes,REMINDER_TIME)
select top 1 l.modified_USER_ID,l.modified_USER_ID,first_name +' '+Last_name +' 'as     NAME,FOLLOW_UP_DATE_C as Date_start,FOLLOW_UP_DATE_C  as Date_end ,L.created_by
from leads_cstm lc
join leads l on l.id = lc.id_c where FOLLOW_UP_DATE_C >getdate()
order by l.date_modified Desc

END  GO

3 个答案:

答案 0 :(得分:1)

您的IF条件未检查与新行具有相同值的一行行。如果这些值中的任何一个存在于表中的任何位置,它将返回true。如果它满足您可能具有的任何其他约束,则最好在Meetings表上创建唯一键(Modified_user_id,assigned_user_id,Name,date_start,date_end,created_by)。然后你可以运行一个简单的插入查询

INSERT IF NOT EXISTS INTO Meetings VALUES(.....)

答案 1 :(得分:1)

If not exists(select name from meetings where(name=@name)and(date_start=@date_start)and....etc)
Begin
  Insert into meetings(...)values(....)
End

答案 2 :(得分:0)

对于SQL Server

让这个错误比先检查更容易,更安全。当NAME, DATE_START, DATE_END, CREATED_BY上存在唯一约束/索引时,会发生错误,其中

BEGIN TRY
   INSERT etc
END TRY
BEGIN CATCH
    IF ERROR_NUMBER() <> 2627
      RAISERROR etc
END CATCH

为什么要传递变量而不使用它们?