I had the below code, but it is showing all records due to the UNION:
'WITH x AS
(
SELECT m, ' + @columnlist + ', rn = ROW_NUMBER() OVER (PARTITION BY ClientNric ORDER BY m DESC)
FROM
(
SELECT m = ''' + @table1 + ''', * FROM ' + @table1 + '
UNION ALL
SELECT m = ''' + @table2 + ''', * FROM ' + @table2 + '
) AS y
)
SELECT ' + @columnlist + ', DataState = m
FROM x
WHERE rn = 1;'
exec(@sql)
I need the results as follows:
table1
ID Name
1 TestA
2 TestB
3 TestC
4 TestD
table2
ID Name
1 TestE
2 TestF
3 TestG
4 TestD
Results:
Name DataState
TestA table1
TestB table1
TestC table1
TestD table2
Can advise how to achieve the results?
Thanks.
A left join should do the job, I think:
Or maybe the join should be on the
IDcolumn, I’m not sure. In any event, this should at least give you the idea.