How can write a delete script from the table

Polachan Paily 91 Reputation points
2022-06-16T06:33:04.13+00:00

I have a customer table with the follwing structure and records. I would like to write a delete script inside a stored procedure but make have to make sure the number of record from the select statement and delete statement are equal if not it should go to rollback . please can you help

Developer technologies Transact-SQL
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Olaf Helper 47,436 Reputation points
    2022-06-16T07:27:27.59+00:00

    That's to less on information.
    Please post table design as DDL, some sample data as DML statement and the expected result.

    0 comments No comments

  2. LiHong-MSFT 10,056 Reputation points
    2022-06-16T07:58:28.687+00:00

    Hi @Polachan Paily

    I have a customer table with the follwing structure and records.

    I didn't see your customer table or any records. Please edit your issue.

    make sure the number of record from the select statement and delete statement are equal if not it should go to rollback .

    Check this sample:

    DECLARE @full_table_count1 int  
    DECLARE @full_table_count2 int  
    DECLARE @select_Count int  
    DECLARE @delete_Count int  
      
    BEGIN TRANSACTION DELETE_DATA  
      SELECT @full_table_count1 = COUNT(*) FROM table_name   
      
      SELECT @select_Count = COUNT(*) FROM table_name WHERE <add conditions here>  
        
      DELETE FROM table_name WHERE <add conditions here>  
      
      SELECT @full_table_count2 = COUNT(*) FROM table_name  
      
      SET @delete_Count = @full_table_count1 - @full_table_count2  
        
      IF @delete_Count <> @select_Count  
        BEGIN   
          ROLLBACK TRANSACTION   
          PRINT 'Records of select statement and delete statement are equal'  
        END  
      ELSE  
        BEGIN  
          COMMIT TRANSACTION   
          PRINT 'Delete successfully'  
        END  
    

    Of course, it may not match your request, and it would be better if you could supplement the question more complete.

    Best regards,
    LiHong

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.