use Gaia declare @toClean table( alias varchar(222) not null ); insert into @toClean(alias) select 'ama207' union select 'ama208' union select 'cvi243' union select 'cvi244' union select 'cvi245' union select 'cvi255' union select 'cvi269' union select 'cvi811' union select 'sun143' union select 'ama002' union select 'ama003' union select 'ama004' union select 'ama006' union select 'ama008' union select 'ama201' union select 'ama203' union select 'ama204' union select 'ama206' ; /* PURGE OLD DATA */ with ctePharmacyCode as ( select phcy_code = case WHEN upper(left(alias,3)) = 'SUN' THEN 'GSU' + RIGHT(upper(alias),3) WHEN upper(left(alias,3)) = 'CVI' THEN 'GCV' + RIGHT(upper(alias),3) WHEN upper(left(alias,3)) = 'AMA' THEN 'GAM' + RIGHT(upper(alias),3) end from @toClean ) , cteOneStringPharmacyCode as ( select stuff(x.phcy_code,1,1,'') as concatenated_phcy_code from ( select ','''+phcy_code+'''' from ctePharmacyCode for xml path('') )x(phcy_code) ) SELECT 'DELETE FROM [' + s.name + '].[' + t.name + '] WHERE ' + c.name + ' IN (' + l.concatenated_phcy_code + ');' as delcmd FROM sys.schemas s JOIN sys.tables t ON t.schema_id = s.schema_id JOIN sys.columns c ON c.object_id = t.object_id AND c.name LIKE '%_pharmacy_code' cross join cteOneStringPharmacyCode l WHERE s.name = 'phar' ORDER BY t.name