查询结果中的SQL插入/更新表

时间:2013-11-04 10:35:21

标签: sql sql-server sql-server-2005

我对SQL很陌生,我正在寻找一些帮助我尝试在SQL Server 2005中编写的过程。

我正在尝试使用查询结果插入或更新表。

我已经将INSERT写得很好并且按预期工作但是如果记录已经存在,我想更新而不是插入。

我目前的代码是:

INSERT INTO testTable
    ( field1 ,
      field2 ,
      field3,
      field4,
      field5 ,
    )                                   
select 
    'A000001'
    table2.field2,
    GETDATE() , 
    GETDATE()  ,
    NULL , 
    NULL , 
    0  

from 
    table1
INNER JOIN 
    table2 ON table1.field1 = table2.field1 
INNER JOIN 
    table3 ON table2.field1 = table3.field1 
INNER JOIN 
    table4 ON table3.field1 = table4.field1 
WHERE condition

我想更改此设置,以便如果field2中的testTable已经在{{1}}中,那么它将更新而不是插入。我不知道怎么做,因为我可能会返回多个记录。

我已经看过其他一些问题,但我没有找到答案的问题(或者我不确定如何更改多个记录的答案)

任何帮助表示赞赏!

谢谢,

2 个答案:

答案 0 :(得分:0)

INSERT

INSERT INTO testTable
    ( field1 ,
      field2 ,
      field3,
      field4,
      field5 ,
    )                                   
select 
    'A000001'
    field2,
    GETDATE() , 
    GETDATE()  ,
    NULL , 
    NULL , 
    0  

from 
    table1
INNER JOIN 
    table2 ON table1.field1 = table2.field1 
INNER JOIN 
    table3 ON table2.field1 = table3.field1 
INNER JOIN 
    table4 ON table3.field1 = table4.field1 
WHERE condition and not exists(select * from testable where table1.field2=testable.field2)

更新

UPDATE test
SET
    test.field1='A000001'
    test.field3=GETDATE() , 
    test.field4=NULL , 
    test.field5=0  

from 
    testtable as test inner join table1 on test.field2=table1.field2
INNER JOIN 
    table2 ON table1.field1 = table2.field1 
INNER JOIN 
    table3 ON table2.field1 = table3.field1 
INNER JOIN 
    table4 ON table3.field1 = table4.field1 
WHERE condition

答案 1 :(得分:0)

最好的操作是使用合并。

;with blabla as (select 
    'A000001'
    field2,
    GETDATE() , 
    GETDATE()  ,
    NULL , 
    NULL , 
    0  

from 
    table1
INNER JOIN 
    table2 ON table1.field1 = table2.field1 
INNER JOIN 
    table3 ON table2.field1 = table3.field1 
INNER JOIN 
    table4 ON table3.field1 = table4.field1 
)
merge into test as target
using (select * from blabla) as sources (columnlist...)
on field2 = field2
WHEN MATCHED and Source.Field2 <> Target.Field2 THEN
    UPDATE SET ...
WHEN NOT MATCHED BY TARGET THEN
    INSERT (..) VALUES (..)
WHEN NOT MATCHED BY Source THEN
DELETE;