Monday, May 23, 2022

.::: Simple Archive data table in SQL :::.

 1. Main table will be archive  
USE [teguhth]
GO
select @@servername as ServerName, db_name() as DBName,* from pembelian -- original data from table
select @@servername as ServerName, db_name() as DBName,* from pembelian where TANGGAL_PEMBELIAN < '2020-07-02 00:00:00' -- original data will archive from table
 

2. Checking existing table
USE [teguhth]
GO
CREATE TABLE [dbo].[pembelian](
    [KODE_PEMBELIAN] [char](10) NOT NULL,
    [KODE_BARANG] [char](6) NOT NULL,
    [KODE_CUSTOMER] [char](6) NOT NULL,
    [TANGGAL_PEMBELIAN] [date] NULL,
    [JUMLAH_PEMBELIAN] [decimal](4, 0) NULL,
PRIMARY KEY CLUSTERED
(
    [KODE_PEMBELIAN] ASC,
    [KODE_BARANG] ASC,
    [KODE_CUSTOMER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[pembelian]  WITH CHECK ADD FOREIGN KEY([KODE_BARANG])
REFERENCES [dbo].[barang] ([KODE_BARANG])
GO

ALTER TABLE [dbo].[pembelian]  WITH CHECK ADD FOREIGN KEY([KODE_CUSTOMER])
REFERENCES [dbo].[customer] ([KODE_CUSTOMER])
GO

3. create table archive example table pembelian_archive
USE [teguhth]
GO

CREATE TABLE [dbo].[pembelian_archive](
    [ServerName] [nvarchar](128) NULL,
    [DBName] [nvarchar](128) NULL,
    [KODE_PEMBELIAN] [char](10) NOT NULL,
    [KODE_BARANG] [char](6) NOT NULL,
    [KODE_CUSTOMER] [char](6) NOT NULL,
    [TANGGAL_PEMBELIAN] [date] NULL,
    [JUMLAH_PEMBELIAN] [decimal](4, 0) NULL
) ON [PRIMARY]
GO

4. Archive from table pembelian to table pembelian_archive

insert into teguhth.dbo.pembelian_archive select @@servername as ServerName, db_name() as DBName,*
--- into teguhth.dbo.pembelian_archive
from pembelian where TANGGAL_PEMBELIAN < '2020-07-02 00:00:00' -- original data will archive from table


5. check table pembelian_archive (destination)
select @@servername as ServerName, db_name() as DBName,* from teguhth.dbo.pembelian_archive


6. delete data from pembelian / source
delete from teguhth.dbo.pembelian where TANGGAL_PEMBELIAN < '2020-07-02 00:00:00'

7. compare table from pembelian & pembelian archive

select @@servername as ServerName, db_name() as DBName,*,'-- original data from table' from pembelian -- original data from table pembelian;

select @@servername as ServerName, db_name() as DBName,*,'-- data archive from table from pembelian_archive' from teguhth.dbo.pembelian_archive -- data archive from table from pembelian_archive;

select *,'-- data archive from table from pembelian_archive' from teguhth.dbo.pembelian_archive -- data archive from table from pembelian_archive


No comments:

Post a Comment

Popular Posts