I want a generic query to move the "IN" state records from tableB,TableC,TableD to TableA which has studid as identity column.After moving the records to TableA delete the records with state ="IN" from tableB,TableC,TableD.Below is my sceniario but i have more nearly 15 tables which the records to be moved and deleted.Below is the Ex:TableA-------Studid Stuname State------ ------- -------1 SaM IN2 Mat INTableB-----Studid Stuname State------ ------- -------1 VIn IN2 Jon IN3 Pat NYTableC-------Studid Stuname State------ ------- -------1 Kim IN2 Jim WA3 Pat NYTableD-------Studid Stuname State------ ------- -------1 Rog IN2 Ant IN3 Put NYExpected outputTableA-------Studid Stuname State------ ------- -------1 SaM IN2 Mat IN3 VIn IN4 Jon IN5 Kim IN6 Rog IN7 Ant INTableB-----Studid Stuname State------ ------- -------3 Pat NYTableC-------Studid Stuname State------ ------- -------2 Jim WA3 Pat NYTableD-------Studid Stuname State------ ------- -------3 Put NY
;with cteData as ( select StuName from TableB where State ='IN' union select StuName from TableC where State ='IN' union .... -- Extra select statement here, i used Union (without ALL) so only distinct values will be in the output list) Insert into TableA (Stuname,State) Select StuName,'IN' from cteData delete from TableB where State = 'IN' Delete from TableC where State ='IN' ..... -- extra delete statement here for the other tables