SQL Server(T-SQL)如果不存在则插入

时间:2010-02-01 17:46:05

标签: sql insert

问题

如何更改下面的SQL代码以确保只有在“dbo.tblBootStrapperInstruments”尚不存在时才会插入?

代码

INSERT INTO dbo.tblBootStrapperInstruments (CCY, Instrument, Tenor)
SELECT CCY,Instrument,Gridpoint FROM dbo.Feed_Murex_Intraday_DF mx WHERE NOT EXISTS 
(SELECT * FROM dbo.tblBootStrapperInstruments bs
WHERE bs.CCY = mx.CCY
AND bs.Instrument = mx.Instrument
AND bs.Tenor = mx.Gridpoint) 

3 个答案:

答案 0 :(得分:1)

我是这样做的。

INSERT INTO dbo.tblBootStrapperInstruments (CCY, Instrument, Tenor) 
SELECT mx.CCY,mx.Instrument,mx.Gridpoint FROM dbo.Feed_Murex_Intraday_DF mx
LEFT OUTER JOIN dbo.tblBootStrapperInstruments bs 
ON bs.CCY = mx.CCY 
AND bs.Instrument = mx.Instrument 
AND bs.Tenor = mx.Gridpoint
WHERE bs.CCY IS NULL

答案 1 :(得分:0)

您使用的是什么RDBMS? MySQL的? MSSQL? SQLite的?

在MySQL中你有两个选择。您可以在插入值上添加唯一索引,并选择REPLACE statement或使用ON DUPLICATE KEY UPDATE

答案 2 :(得分:0)

如果您的数据库风格和版本支持MERGE,您可以使用它(MERGE已添加到SQL Server 2005)。语法有点笨拙,因为它实际上是通过从另一个表中选择来加载数据。

这个例子使用了Oracle(因为这就是我所拥有的)。

SQL> merge into customer
  2      using ( select 6 as id
  3                     , 'Ella' as forename
  4                     , 'Chip' as surname
  5                     , '1234 Telepath Drive' as address_1
  6                     , 'Milton Lumpky' as address_2
  7                     , 'ML1 4KJ' as postcode
  8                    ,  add_months (sysdate, -235) as date_of_birth
  9               from dual ) t
 10      on (t.id = customer.id )
 11  when not matched then
 12      insert (id, forename, surname, address_1, address_2, postcode, date_of_birth)
 13      values (t.id, t.forename, t.surname, t.address_1, t.address_2, t.postcode, t.date_of_birth)
 14  /

1 row merged.

SQL> commit;

Commit complete.

SQL>

如果我们再次运行相同的查询(ID是主键)它不会失败,它只会合并一行......

SQL> merge into customer
  2      using ( select 6 as id
  3                     , 'Ella' as forename
  4                     , 'Chip' as surname
  5                     , '1234 Telepath Drive' as address_1
  6                     , 'Milton Lumpky' as address_2
  7                     , 'ML1 4KJ' as postcode
  8                    ,  add_months (sysdate, -235) as date_of_birth
  9               from dual ) t
 10      on (t.id = customer.id )
 11  when not matched then
 12      insert (id, forename, surname, address_1, address_2, postcode, date_of_birth)
 13      values (t.id, t.forename, t.surname, t.address_1, t.address_2, t.postcode, t.date_of_birth)
 14  /

0 rows merged.

SQL>  

与光头INSERT进行比较和对比......

SQL>   insert into customer (id, forename, surname, address_1, address_2, postcode, date_of_birth)
  2  values ( 6, 'Ella', 'Chip', '1234 Telepath Drive', 'Milton Lumpky', 'ML1 4KJ',add_months (sysdate, -235) )
  3  /
    insert into customer (id, forename, surname, address_1, address_2, postcode, date_of_birth)
*
ERROR at line 1:
ORA-00001: unique constraint (APC.CUS_PK) violated


SQL>