【问题标题】:IF record DOES NOT EXIST in Table1, UPDATE Table2, ELSE IF record EXISTS UPDATE Table2 with column from Table1IF 记录在 Table1 中不存在,更新 Table2,ELSE IF 记录 EXISTS UPDATE Table2 与 Table1 中的列
【发布时间】:2014-10-20 00:37:28
【问题描述】:

我将在STORED PROCEDUREin T-SQL 中执行以下操作。

Table1 包含一些任意的行。表 2 比表 1 包含更多的行,但存在的行是相同的,除了一个包含日期的列。

如果Table2中存在Table1中的一行,我想更新Table2的日期列。
如果 Table2 中的行在 Table1 中不存在,我也想更新 Table2 的日期列。

我终其一生都无法弄清楚实现这一点的语法,因为这个存储过程不会接受任何参数或输出任何参数。

【问题讨论】:

  • 如果表 1 中不存在记录,那么您将在表 2 中更新什么值
  • @Pradeep 和存在一样,只是我将日期设置为今天的日期,而不是Table1返回的日期。

标签: sql-server tsql azure-sql-database


【解决方案1】:

首先你应该得到表的差异。检查以下内容:

set nocount on
declare @t1 table (id int, datecolumn datetime)
declare @t2 table (id int, datecolumn datetime, fk_on_t1 int)

declare @diff table(t1_id int, t2_id int)

insert into @diff(t1_id,t2_id)
select
t1.Id
,t2.ID 
from @t1 t1 
full join @t2 t2 on t1.id = t2.fk_on_t1

现在您可以了解一个或另一个表中存在哪些行。您可以使用这样的查询来更新您的案例的日期列:

update t2
set datecolumn = getdate()
from @t2 t2
inner join @diff d on d.t2_id = t2.ID
where d.t2_id is not null 

通常,您可以只进行一次查询,而不是我的两次。检查这个:

update t1
set datecolumn = getdate()
from @t1 t1
full join @t2 t2 on t1.id = t2.fk_on_t1
where t2.ID is not null 

【讨论】:

    【解决方案2】:
    update table1
       set table1.date = insull(table2.date, getdate()) 
      from table1 
      left jion table2 
        on table2.ID = table1.ID 
    

    【讨论】:

    • 谢谢,这正是我想要的! :) 你知道我应该读什么来复习 SQL 语法吗?我觉得这没有必要,我根本无法绕开它。再次感谢您!
    • 我知道它是 Sql Server 6.5 所以没有。从那时起,我就有了文档。
    【解决方案3】:

    试试这个

    UPDATE A 
    SET    A.datecol= CASE 
                      WHEN EXISTS (SELECT 1 
                                   FROM   Table1 B 
                                   WHERE  B.cola = A.cola) THEN c.Datecol
                      ELSE getdate() 
                    END 
    FROM   Table2 A 
           JOIN Table1 C 
             ON a.cola = c.cola 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多