SQL Server插入到不存在的位置

时间:2014-10-29 18:40:24

标签: sql sql-server-2012

我试图在表中插入值尚不存在的值。

这就是我现在所拥有的:

insert into UToolDb.dbo.MQ_MESSAGES_NEW (ENVId, QueueName, CorrelationId, MessageId, MessageContent) 
   select 
      E.ENVId,
      'RO00.GAT1.STUB_OPVANG_1.AI',
      '323031333130303431313533343933383438363739353032',
      'C3E2D840E2D8F1F24040404040404040CC0F7930FE822942', 
      'TEST Content'
   from 
      UToolDb.dbo.ENVIRONMENTS E 
   where 
      E.EnvironmentName = 'KETEN1' 
      and not exists (select 
                         EE.ENVId, 
                         'RO00.GAT1.STUB_OPVANG_1.AI',
                         '323031333130303431313533343933383438363739353032',
                         'C3E2D840E2D8F1F24040404040404040CC0F7930FE822942', 
                         'TEST Content'
                      from 
                         UToolDb.dbo.ENVIRONMENTS EE 
                      where 
                         EE.EnvironmentName = 'KETEN1'      
                         and EE.EnvironmentName = E.EnvironmentName)

由于某种原因,它没有插入:

 (0 row(s) affected).

表中不存在插入的值。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您从ENVIRONMENTS获取一行,并再次检查同一表中是否存在相同的行。

如果行已存在于MQ_MESSAGES_NEW而不是ENVIRONMENTS

中,则可能是您想要的

答案 1 :(得分:0)

找到解决方案:

insert into UToolDb.dbo.MQ_MESSAGES_NEW (
   ENVId,
   QueueName,
   CorrelationId,
   MessageId,
   MessageContent
) 
select 
   E.ENVId,
   ?,
   ?,
   ?, 
   ?
from UToolDb.dbo.ENVIRONMENTS E 
where E.EnvironmentName = 'KETEN1' 
and not exists(
   select 
      E.ENVId,
      M.*
   from UToolDb.dbo.ENVIRONMENTS E 
   left join UToolDb.dbo.MQ_MESSAGES_NEW M
   on E.ENVId = M.ENVId
   where E.EnvironmentName = 'KETEN1' 
   and QueueName = ?
   and CorrelationId = ?
   and MessageId = ?
   and MessageContent = ?
)