简体   繁体   中英

How to add a condition for INSERT INTO

Every month I run a procedure that creates a table with data for the previous month (#prev_month). After that, the data is added to the table where the history for all months is stored. How to make that if the procedure was run 2 times a month, the data is added to the history table only once.

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

If I understand correctly, you can use not exists :

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

It is unclear what month is. And XXX depends on that. It might be something like datediff(month, month, getdate()) = 1 , if month is a date .

you could try something like this:

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

I would use NOT EXISTS with a correlated subquery

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

You can also think of MERGE statement, which will ensure that only one data exists for the month, irrespective of how many times, the statement is executed.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM