0

I'm trying to archive the data into table (EMPTAB_Archive) by deleting the data from Production table (EMPTAB) using the temporary table (##TMP) as a reference.

Note that temporary table contains two fields: empcode and empname, this is a part of code from a stored procedure that isn't working:

SELECT @SQL =          'DELETE ET1
                        FROM EMPDB..EMPTAB ET1 DELETED.*
                        INTO [EMPDB_ARCHIVE]..EMPTAB_Archive
                        INNER JOIN ##TMP TMP1
                        WHERE EMPID IN ##TMP
                        AND TMP1.DOCUMENTID = ET1 .EMPID'
         EXEC(@SQL)

But i'm getting below error message

Msg 102, Level 15, State 1, Line 2 Incorrect syntax near 'DELETED'. Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '##TMP'.

apxcode
  • 7,696
  • 7
  • 30
  • 41
Sreedhar Danturthi
  • 7,119
  • 19
  • 68
  • 111

2 Answers2

1

The problem is in WHERE EMPID IN ##TMP. You have to use join. Also deleting into is also not correct.

WHERE EMPID IN ##TMP must be done by join.

I think that correct SQL should looks like:

SELECT @SQL = 'DELETE ET1 OUTPUT DELETED.* 
INTO [EMPDB_ARCHIVE]..EMPTAB_Archive
FROM EMPDB..EMPTAB ET1 
INNER JOIN ##TMP TMP1 ON 
TMP1.DOCUMENTID = ET1 .EMPID'
EXEC(@SQL)
Bogdan Bogdanov
  • 1,707
  • 2
  • 20
  • 31
0

Also you do not need Dynamic SQL which is in this case subject to SQL Injection. Just use Static SQL

Madhivanan
  • 13,470
  • 1
  • 24
  • 29