Search code examples
sql-server-2014

Delete and Insert data data if data if day exists and insert data if day does not exist


I have the below script that works however I need some help modifying it.

What I now need to do are the following 1. If the day already exists I need to delete all data from that day and insert the new data for the day. 2. if the day does not exist I need to insert the data for the day.

My date format is written as yyyy-mm-dd hh:mm:ss In it's current form it only inserts data if the current day is greater than the previous day.

Declare @Date As Date
SET @Date = (SELECT Max(CONVERT(char(10),[Date],102)) FROM [dbo].[ESOEmail_Monthly$])
INSERT INTO [dbo].[ESOEmail_Monthly$]
SELECT      [EMP_ID]
       ,[NAME]
       ,[DEPT]
       ,[DATE]
       ,[End Time]
       ,[LOGOUT]
       ,[ESO]
       ,[Team Manager]
       ,[Senior Manager]
       ,[SITE]
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                     'Excel 12.0;Database=\\VF_RSOSDCNASUDA\fidopost\National_Command\National Command Centre\SQL\ESO\ESO.xlsm;HDR=YES',
                     'SELECT * FROM [ESOEmail$]')
WHERE (CONVERT(char(10),[Date],102) > CONVERT(DATETIME, @Date, 102))

Solution

  • After digging around and finding some help I was able to find a solution that worked for me. I've posted the solution.

    Declare @Date As DATE
    
    IF OBJECT_ID('Tempdb..#1','U') IS NOT NULL
    DROP TABLE #1
    
    SELECT      [EMP_ID]
       ,[NAME]
       ,[DEPT]
       ,[DATE]
       ,[End Time]
       ,[LOGOUT]
       ,[ESO]
       ,[Team Manager]
       ,[Senior Manager]
       ,[SITE]
    INTO #1
    FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                     'Excel 12.0;Database=\\VF_RSOSDCNASUDA\fidopost\National_Command\National Command Centre\SQL\ESO\ESO.xlsm;HDR=YES',
                     'SELECT * FROM [ESOEmail$]');
    
    SELECT TOP 1 @Date=[DATE] FROM #1
    
    --DELETE
    DELETE [dbo].[ESOEmail_Monthly$] WHERE CONVERT(char(10),[Date],102)=@Date;
    
    --INSERT
    INSERT INTO [dbo].[ESOEmail_Monthly$]
    SELECT      [EMP_ID]
       ,[NAME]
       ,[DEPT]
       ,[DATE]
       ,[End Time]
       ,[LOGOUT]
       ,[ESO]
       ,[Team Manager]
       ,[Senior Manager]
       ,[SITE]
    FROM #1
    DROP TABLE #1