IF NOT EXISTS
  (SELECT TOP 1 1
     FROM sys.objects [SO]
    WHERE [SO].[name] = 'DiaryAttachmentOriginalMatterLinks'
      AND [SO].[type] = 'U')
  BEGIN
    EXEC ('CREATE TABLE
       [dbo].[DiaryAttachmentOriginalMatterLinks]
      ([TrackReference]      INT            NOT NULL,
       [OriginalUniqueID]    INT            NOT NULL,
       CONSTRAINT [PK_DAOML]
                  PRIMARY KEY CLUSTERED
                 ([TrackReference]))
    ON [PRIMARY]')
  END
GO

IF EXISTS
  (SELECT TOP 1 1
     FROM sys.objects [SO]
          LEFT OUTER JOIN sys.indexes [SI]
                       ON [SI].object_id = [SO].object_id
                      AND [SI].[name] = 'IDX_UniqueID'
    WHERE [SO].[name] = 'DiaryAttachmentOriginalMatterLinks'
      AND [SO].[type] = 'U'
      AND [SI].[index_id] IS NULL)
  BEGIN
    EXEC ('    CREATE NONCLUSTERED
     INDEX [IDX_UniqueID]
        ON [dbo].[DiaryAttachmentOriginalMatterLinks]
          ([OriginalUniqueID])
           INCLUDE ([TrackReference])')
  END
GO

DELETE [DAT]
  FROM [dbo].[DiaryAttachments] [DAT]
       LEFT OUTER JOIN [dbo].[Diary] [DIA]
                    ON [DIA].[ActionID] = [DAT].[DiaryID]
 WHERE [DIA].[ActionID] IS NULL
GO

INSERT
  INTO [dbo].[DiaryAttachmentOriginalMatterLinks]
      ([TrackReference],
       [OriginalUniqueID])
SELECT [DAT].[TrackReference],
       [MAT].[UniqueID]
  FROM [dbo].[DiaryAttachments] [DAT]
       INNER JOIN [dbo].[matters] [MAT]
               ON [MAT].[Code] = [DAT].[CASECODE]
       LEFT OUTER JOIN [dbo].[DiaryAttachmentOriginalMatterLinks] [DAOML]
                    ON [DAOML].[TrackReference] = [DAT].[TrackReference]
 WHERE [DAOML].[TrackReference] IS NULL
GO




IF OBJECT_ID('DocumentPopups','U') IS NOT NULL
BEGIN
	IF NOT EXISTS(
		SELECT  TOP 1 1 
		FROM    SYS.columns 
		WHERE   OBJECT_NAME(object_id) = 'DocumentPopups' AND
				[name] = 'Title')
	BEGIN
		ALTER TABLE DocumentPopups
		ADD [Title] VARCHAR(100)
	END	
END

GO
