【问题标题】:How to add a condition for INSERT INTO如何为 INSERT INTO 添加条件
【发布时间】:2020-09-04 10:38:38
【问题描述】:

每个月我都会运行一个程序来创建一个包含上个月数据的表 (#prev_month)。 之后,数据将添加到存储所有月份历史记录的表中。 如果该过程每月运行 2 次,如何使数据仅添加到历史表中一次。

select month, count (UserID) as Number
into #prev_month
from Compliance
where StatusID=17
and LastRequestDate>dateadd(month,datediff(month,0,getdate()-1)-1,0)  
group by Month


insert into History_tbl
select * from #prev_month

【问题讨论】:

  • 样本数据和期望的结果真的很有帮助。 month 是什么?

标签: sql sql-server sql-insert


【解决方案1】:

如果我理解正确,你可以使用not exists

insert into history (month, number)
    select month, number
    from #prev_month
    where not exists (select 1
                      from history h2
                      where month = XXX
                     );

不清楚month 是什么。 XXX 取决于此。如果monthdate,它可能类似于datediff(month, month, getdate()) = 1

【讨论】:

  • 非常感谢!我会用这个
【解决方案2】:

你可以试试这样的:

insert into History_tbl (month, Number)

select month, count (UserID) as Number

from Compliance
where StatusID=17
and LastRequestDate>dateadd(month,datediff(month,0,getdate()-1)-1,0)  
group by Month

【讨论】:

  • 在这种情况下,如果我运行程序两次,它会插入 History_tbl 2 行,我每月只需要 1 个
【解决方案3】:

我会在相关子查询中使用 NOT EXISTS

insert history([month], number)
select *
from #prev_month pv
where not exists (select 1
                  from history h
                  where h.[month]=pv.[month]);

【讨论】:

    【解决方案4】:

    你也可以想到 MERGE 语句,它会保证当月只存在一个数据,不管语句被执行多少次。

    MERGE into History_tbl AS tgt
    USING (select * from #prev_month) AS src
    ON tgt.Month = src.Month
    WHEN MATCHED THEN
    tgt.number = src.number
    WHEN NOT MATCHED THEN
    INSERT (Month, number)
    VALUES (src.Month, src.number);
    

    【讨论】:

      猜你喜欢
      • 2012-05-21
      • 1970-01-01
      • 2012-12-20
      • 2013-03-20
      • 1970-01-01
      • 2012-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多