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

Stored Procedure | Check for IF Exists using Joins in 3 tables and update

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

Table 1 - plan_info : 来源 table 1.Has 一个 ID

Table 2 - estimates_info : 来源 table 2. ID 与 Table1[=11 相同=]

Table 3 - admin_info : 加入 Table1 和 Table2 与 ID 链接的数据。通常这个 table 是将 Table1 和 Table2 与其各自的 ID 连接起来的结果。 Table 3 的 ID 为 Table1 & 2

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

如果 Table2 的每个 ID 在 Table 3 中都有匹配的行,我不必执行任何操作,否则 Table 3 必须插入Table2 中存在多余的 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

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

你可以这样做

    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