views:

91

answers:

5

I have to write a query to delete form 2 tables

DELETE FROM [Policies],[BackupSpec] WHERE [PolicyID] = @original_PolicyID

PloicyID is PK in Policies and FK in Backupspec

any suggestions??

   SqlConnection conn = new SqlConnection();
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["SumooHAgentDBConnectionString"].ConnectionString;
        string sql = "DELETE FROM [Policies],[BackupSpec] WHERE [PolicyID] = @original_PolicyID";
        string sql1 = "DELETE FROM [Backupspec] WHERE [PolicyID] = @original_PolicyID";
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlCommand cmd1 = new SqlCommand(sql1, conn);

        cmd.Parameters.AddWithValue("@original_PolicyID", item);


        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
A: 

Delete from one table at a time and use transactions to make it atomic. Or define the FK as ON DELETE CASCADE and delete only from the parent table.

Lukáš Lalinský
isnt there a query to do this..??
Not in SQL Server (there is a way to do it in MySQL, for example).
Lukáš Lalinský
A: 

The cleaner way to do it is just have 2 separate queries to delete from the policies and backup spec table. The only reason i would do this is because

1).Its easier for other people debugging by code to understand whats happening.

2).The is usually managed by a manager class which aids in separation of code.

RC1140
even i thougt the same but it is not happening??
the above method is not working... any help
You need to make sure you delete from backupspec first ,I.E you always delete the foreign key before the primary key
RC1140
+1  A: 

Look at here,same question : Deleting from 2 tables at the same time?

anishmarokey
A: 

Your code chould work if you carry out the delete from Backupspec first, then delete from Policies.

The FK is preventing you from removing the Policies record first (that's the point of Referential Integrity).

Ed Harper
+1  A: 

You cannot delete from two tables at once. This is a limit of SQl Server and thus you have no choice but to send two delete statements or to define cascade delete on the parent record. I recommend the two statements rather than cascade delete because cascade delete can cause locking problems if the delete involves many records. Remember cascade delete affects any deletes from any source in the tables involved and so even if you are only deleting one record ata time, it would also take affect when someone else at some point in the future needs to delete a million records. It will also take longer and longer and tie up more tables as the number of child tables increases.

HLGEM