Click here to Skip to main content
15,908,111 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to delete certain records from a table based on a condition. I used the following transaction script to achieve it.

SQL
BEGIN TRY
    BEGIN TRANSACTION
	
	DELETE from Consultation
	where SchoolID in
	(
	SELECT SchoolID 
	from Consultation 
	where [SchoolID]=7128
	)
	
    COMMIT TRAN 
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN 
END CATCH


When I execute the above statement it shows 0 rows affected. But when I used the following script
SQL
BEGIN TRY
    BEGIN TRANSACTION
	
	select * from Consultation
	where SchoolID in
	(
	SELECT SchoolID 
	from Consultation 
	where [SchoolID]=7128
	)
	
    COMMIT TRAN 
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN 
END CATCH


it shows me 3 rows of records.

The records are deleting when I tried deleting it manually. But I consider it is not the safer method to delete records from table. Can anyone please help me find out what the issue behind this.

I even tried using script to delete for some other schoolID and it is working perfectly but not for this schoolID alone. I am unable to find out the issue fix for this. Please help.
Posted

Isn't your query just

DELETE from Consultation WHERE SchoolID=7128


surely you don't need the sub-query? If you want to ensure records in a second table exist then use joins rather than "in" sub-queries.

http://stackoverflow.com/questions/439750/t-sql-selecting-rows-to-delete-via-joins[^]
 
Share this answer
 
Please try to do one thing.

Please put some error description on catch block to see if there is any error occurred or not. In your query if any error will occur then it will rollback the transaction and returns "0 Rows Affected".

SQL
BEGIN CATCH
    IF @@TRANCOUNT > 0
        Print Error_Message()
        ROLLBACK TRAN
END CATCH


Please let me know if you have any concern or query.


Thanks
Advay Pandya
 
Share this answer
 
Comments
user 3008 27-May-15 6:44am    
Thank you so much for your idea. I had an error in the query. I didn't delete in its dependent table of Consultation and hence it has rolledback
Advay Pandya 27-May-15 9:52am    
Always welcome :)
Consider the following when using transactions:

If you are doing a SELECT (your second code block) - what is it you expect to roll back if the query fails?

Similarly, if you wish to DELETE a record - what is it you wish to roll back if the transaction fails?

TRANSACTIONS, in more simple terms, make sense with respect to INSERT and UPDATE queries - more specifically, if they're is more than one operation going on (directly or indirectly) where you truly need an all-or-nothing decision.

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900