Question

I have a table Transaction_tbl with these columns:

transactid   Tbarcode     dtime

1            100          2013-04-16 14:15:47.243
2            101          2013-05-10 10:15:47.243
3            102          2014-02-20 02:15:48.000

In this table, transactid is the primary key.

I have one more table KHanger_tbl with these columns:

transactid   Hbarcode
1             21
2             22
3             23

in my KHanger_tbl this transactid is the foregin key

I want to move date range <=2013-12-30 data from Transaction table to another table called Transaction2013.. (i mean data in the 2013)

so i wrote query like this:

First query

SELECT * 
INTO   transaction2013 
FROM   transaction_tbl 
WHERE  dtime <= '2013-12-30' 

Second Query

    SELECT k.transactid, 
       k.tid, 
       k.requested, 
       k.hbarcode, 
       k.reqloc, 
       k.delivered 
INTO   khanger2013 
FROM   khanger_tbl k 
       INNER JOIN transaction_tbl t 
               ON t.transactid = k.transactid 
WHERE  t.dtime <= '2013-12-30' 

then i want to delete corresponding 2013 data from Khanger_tbl and Transaction_tbl so first i wrote query like this:

    DELETE FROM khanger_tbl 
WHERE  EXISTS (SELECT 1 
               FROM   khanger_tbl 
                      INNER JOIN transaction_tbl 
                              ON transaction_tbl.transactid = 
                                 khanger_tbl.transactid 
                                 AND transaction_tbl.dtime <= '2013-12-30'); 

but this is deleted my entire KHanger_tbl ..what is wrong with my query?

Was it helpful?

Solution

Your DELETE query deletes all rows because you don't have relation with inner subquery so for each row from KHandler_tbl subquery exists. Try to use the following:

DELETE T1
FROM KHanger_tbl T1
INNER JOIN Transaction_tbl T2
  ON T1.transactid = T2.transactid
Where T2.dtime <='2013-12-30'

Or just

  DELETE FROM KHanger_tbl 
        WHERE transactid IN (SELECT transactid 
                              FROM Transaction_tbl 
                              WHERE dtime <='2013-12-30')

OTHER TIPS

You don't need to use the Oracle syntax to delete records in SQL Server. SQL Server allows you do this:

DELETE FROM khanger_tbl a
INNER JOIN transaction_tbl b on a.transactid = b.transactid
WHERE b.dtime <= '2013-12-30'; 

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top