I have a destination table TBLA
and a source table TBLB
.
STEP 1: I get the SQL from a table of my database:
-- I ran this process in a cursor such that `@Sql` is a pass-in selected column value:
DECLARE @Sql NVARCHAR(MAX);
SET @Sql = 'SELECT TBLB.coloumA, TBLB.coloumB... into ##TempTable
FROM TBLB
WHERE CONVERT(VARCHAR(10),Date,120)='2011-04-05'';
EXEC sp_ExecuteSql @sql
STEP 2: I delete the destination table data by calling another sp_ExecuteSql
:
DECLARE @CheckClear NVARCHAR(MAX);
SET @CheckClear = 'DELETE FROM TBLA WHERE EXISTS(SELECT * FROM ##TempTable)';
EXEC sp_ExecuteSql @CheckClear ;
-- This section is where the problem starts, described below.
STEP 3: Insert into TBLA by select * from temp table
DECLARE @DumpSql NVARCHAR(MAX);
SET @DumpSql = 'INSERT INTO TBLA
SELECT * FROM ##TempTable';
EXEC sp_ExecuteSql @DumpSql ;
As mentioned at the end of STEP 2, here is the issue:
After performing the delete statement I found that all my data is missing and it seems it just performed the first command only (DELETE FROM TBLA
).
Before I tried the delete statement, I commented out the ##TempTable
value, and it worked and I only had 2011-11-04 data. (TBLA
already had 2011-11-03 and 2011-11-02 data).
I am actually selecting data by a date value. So far it seems to be successful.
But then, I open my TBLA
and see the result only contains 2011-11-04
data...where is the rest?
PLEASE NOTE THAT:
This above SQL is just a part of my dynamic stored prod that used sp_executesql
...
My actual data consists of about 300 tables that I need to process. Each of these tables have different unique identities so I can't use : SELECT * FROM ##Temptable WHERE id=bla
What would be the best way to go about this?