This might sound silly. However I am trying to trying to take the last modified date value from the comparison of both tables, however I get the "must declare the scalar variable @pa' error. I have lot more columns and that is the reason i am using cursor to check
declare @pa varchar(50)
declare audit_cur cursor for
select distinct audit_field
from #Iam
where concat(',',@af,',') like concat('%,',audit_field,',%')
OPEN audit_cur
FETCH NEXT FROM audit_cur into @pa
declare @cmd varchar(1000)
WHILE @@FETCH_STATUS = 0
BEGIN
set @cmd=concat('SELECT a.A_n,i.audit_field,a.',@pa,' field_value,i.field_after
FROM #Iam_audit a
JOIN (Select a.A_n, a.field_after,audit_field
from #iam a(nolock)
inner join (Select a_n, max(Modified_Date) as maxdate
from #iam a2(nolock)
where a2.Audit_field=@pa
group by a_n
) as aa on aa.a_n = a.a_n and aa.maxdate=a.modified_Date
where a.Audit_Field=@pa ) i
ON i.audit_field=''',@pa,''' AND i.A_n=a.A_n AND a.',@pa,'<>i.field_after')
print @cmd -- for debug
exec(@cmd)
FETCH NEXT FROM audit_cur into @pa
END
CLOSE audit_cur
DEALLOCATE audit_cur