SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[HKIMLIKSUBE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[HKIMLIKSUBE](
	[HKIMLIKSUBEID] [int] IDENTITY(1,1) NOT NULL,
	[SUBEID] [int] NOT NULL,
	[HKIMLIKID] [int] NOT NULL,
	[HASTAARSIVNO] [int] NULL,
 CONSTRAINT [PK_HKIMLIKSUBE] PRIMARY KEY CLUSTERED 
(
	[HKIMLIKSUBEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[HKIMLIKSUBE]') AND name = N'IX_HKIMLIKSUBE_HKIMLIKID_SUBEID')
CREATE NONCLUSTERED INDEX [IX_HKIMLIKSUBE_HKIMLIKID_SUBEID] ON [dbo].[HKIMLIKSUBE] 
(
	[HKIMLIKID] ASC,
	[SUBEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[HKIMLIKSUBE]') AND name = N'IX_HKIMLIKSUBE_SUBEID_HKIMLIKID')
CREATE NONCLUSTERED INDEX [IX_HKIMLIKSUBE_SUBEID_HKIMLIKID] ON [dbo].[HKIMLIKSUBE] 
(
	[SUBEID] ASC,
	[HKIMLIKID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

INSERT INTO [dbo].[HKIMLIKSUBE]
           ([SUBEID]
           ,[HKIMLIKID]
           ,[HASTAARSIVNO])
SELECT     HDOSYA.SUBEID, HKIMLIK.HKIMLIKID, HKIMLIK.ARSIVSIRANO
FROM         HKIMLIK INNER JOIN
                      HDOSYA ON HDOSYA.HKIMLIKID = HKIMLIK.HKIMLIKID
WHERE     (HKIMLIK.ARSIVSIRANO IS NOT NULL) AND (HDOSYA.HDOSYAID =
                          (SELECT     MAX(HDOSYAID) AS SONHDOSYAID
                            FROM          HDOSYA AS H
                            WHERE      (HKIMLIKID = HKIMLIK.HKIMLIKID))) AND (NOT EXISTS
                          (SELECT     HKIMLIKSUBEID, SUBEID, HKIMLIKID, HASTAARSIVNO
                            FROM          HKIMLIKSUBE
                            WHERE      (HKIMLIKID = HKIMLIK.HKIMLIKID) AND (SUBEID = HDOSYA.SUBEID) AND (HASTAARSIVNO IS NOT NULL)))
GO