存储过程|检查IF存在使用3个表中的连接并更新

时间:2015-04-20 10:06:27

标签: sql stored-procedures join

我有一个场景,我必须根据需要用其他2个表中的数据更新我的table3

表1 - plan_info :Socurce表1.有ID

表2 - estimate_info :源表2.具有与Table1相同的ID

表3 - admin_info :加入Table1和Table2与ID相关联的数据。通常,此表是将Table1和Table2与其各自的ID连接的结果。表3将ID作为表1和表1。 2

我必须编写一个存储过程来检查:

如果表3中的表2的每个ID都有匹配的行,则不必执行任何操作,否则必须插入表3中存在的多余ID,并且不应覆盖之前存在的记录。

我已经记下了以下查询,但它无效。

IF EXISTS ( select * from  estimates_info x , admin_info y where x.ID = y.ID)
BEGIN
--Display all the records
select * from admin_info
END
ELSE
BEGIN
 --insert new record
INSERT INTO admin_info ( 
ID, 
Name,
StartDate, 
AdminFlagged ) 
select a.ID,a.Name, b.StartDate,0
from plan_info a,
estimates_info b
where a.ID = b.ID and  b.StartDate < DATEADD(day, DATEDIFF(day, 0,   GETDATE()), 1)
END

如果有人能帮助我取得突破,将会有很大的帮助。

1 个答案:

答案 0 :(得分:0)

你可以这样做

    If Object_Id('tempdb.dbo.#estimates_info') Is Not Null
Begin
    Drop Table #estimates_info;
End

If Object_Id('tempdb.dbo.#admin_info') Is Not Null
Begin
    Drop Table #admin_info;
End

If Object_Id('tempdb.dbo.#estimates_info') Is Null
Begin
    Create Table #estimates_info
    (
         Id         Int 
        ,Name       Varchar(100)
    )
End

If Object_Id('tempdb.dbo.#admin_info') Is Null
Begin
    Create Table #admin_info
    (
         Id         Int 
        ,Name       Varchar(100)
    )
End


Insert Into #estimates_info(Id, Name) Values
 (1,'ABC')
,(2,'XYZ')
,(3,'PQR');

Insert Into #admin_info(Id, Name) Values
 (1,'ABC')
,(3,'PQR');


If Exists(  Select  1
            From    (
                        Select   Count(x.Id) As xCount
                                ,Sum(Case When y.Id Is Not Null Then 1 Else 0 End) As yCount
                        From    #estimates_info As x With (Nolock)
                                Left Join #admin_info As y With (Nolock) On x.Id = y.Id
                    ) As t
            Where   t.xCount = t.yCount
        )
Begin
    ---- select * from table
End
Else
Begin   
    ---- your insert code
End