使用if语句检查记录是否存在不在sqlserver中工作

时间:2018-05-20 08:34:20

标签: sql sql-server

我正在尝试检查其他表中是否存在记录。它必须执行插入并仅对该条目执行更新,而不是对该表中的任何现有项执行更新。 这就是我试过的:

IF NOT exists (SELECT *
                    FROM dbo.Log  s inner join #results r on s.Number = r.Number)
   BEGIN
       insert into  //if it doesn't exist enter the row dbo.Log(Number,FirstName,LastName,Mobile,MessageContent,MessageStatus)
       select Number
             ,FirstName
             ,LastName
             ,MobileNumber
             ,MessageContent
             ,MessageStatus
       from #results r
 update r //then only update that row that was inserted
    set TextNumb = v.TextNumber
    from 
    (select r.*, row_number() over (order by newid()) as seqnum
      from [dbo].[Log] r where MessageStatus=0
     ) r join
     (select v.*, row_number() over (order by newid()) as seqnum
      from dbo.TextNUMBERS v
      where Flag=0
     ) v
     on r.seqnum = v.seqnum;
     update dbo.TextNUMBERS
            set flag =1
     from  [dbo].[Log] re 
 where re.TextNumb=dbo.TextNumbers.TextNumber
 END 

所以在上面我试过,如果记录不存在,那么只插入和更新该记录,但它不起作用,它只在我运行时第一次插入在另一个表中没有值的查询,但如果我第二次运行查询,则不会插入任何新记录。

我也尝试过:

insert into 
    dbo.Log(Number,FirstName,LastName,Mobile,MessageContent,MessageStatus)
           select Number
                 ,FirstName
                 ,LastName
                 ,MobileNumber
                 ,MessageContent
                 ,MessageStatus
           from #results r
where not exists (select 1
from dbo.log s
where s.Number=r.Number)

上面的工作是检查记录是否存在并且它是否插入,但问题是我不能只更新插入的记录,因为它最终更新了所有内容日志表。

那么如何让我的if语句起作用?我做错了吗?

0 个答案:

没有答案