0

我对 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那么它将更新而不是插入。我不确定如何执行此操作,因为我可能会返回多条记录。

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

任何帮助表示赞赏!

谢谢,

4

2 回答 2

0

插入

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
于 2013-11-04T10:39:34.683 回答
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;
于 2013-11-04T10:49:12.073 回答