use sifdata if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fgtagcode]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) DROP TABLE [dbo].[fgtagcode] CREATE TABLE [dbo].[fgtagcode]( ; [id] [int] IDENTITY(1,1) NOT NULL,; [fgwhtagid] [int] NOT NULL,; [pashipid] [int] not null,; [packdate] [datetime] null,; [cancode] [varchar](20) null,; [datecode] [varchar](20) null,; [qty] [decimal](20,4) null default(0),; [remark] [text] NULL,; [AddBy] [int] NULL,; [AddWhen] [datetime] NULL default(getdate()),; [DelBy] [int] NULL,; [DelWhen] [datetime] NULL,; CONSTRAINT [pkfgtagcode] PRIMARY KEY CLUSTERED ([id]) ) if not exists (select id from sifsystem.dbo.dbtables where name='fgtagcode'and dbname='sifdata' and applicationid=1) insert sifsystem.dbo.dbtables (name,dbname,applicationid) values ('fgtagcode','sifdata',1) if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fgtagtrn]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) DROP TABLE [dbo].[fgtagtrn] CREATE TABLE [dbo].[fgtagtrn]( ; [id] [int] IDENTITY(1,1) NOT NULL,; [fromfgtagcodeid] [int] null,; [tofgtagcodeid] [int] null,; [qty] [decimal](20,4) null default(0),; [remark] [text] NULL,; [AddBy] [int] NULL,; [AddWhen] [datetime] NULL default(getdate()),; [DelBy] [int] NULL,; [DelWhen] [datetime] NULL,; CONSTRAINT [pkfgtagtrn] PRIMARY KEY CLUSTERED ([id]) ) if not exists (select id from sifsystem.dbo.dbtables where name='fgtagtrn'and dbname='sifdata' and applicationid=1) insert sifsystem.dbo.dbtables (name,dbname,applicationid) values ('fgtagtrn','sifdata',1) insert fgtagcode (fgwhtagid,pashipid,packdate,cancode,datecode,qty,addby) select fgwhtagid,pashipid,packdate,cancode,datecode,sum(fgcans),1 from fgtagbasket where delby is null group by fgwhtagid,pashipid,packdate,cancode,datecode