Hi, Please review the SQL query and help.
I need help to fix the following two issues in my query to get the desired result. Note: The key columns are Name, code and PerID which can not be same.
1- Example: TableB’s key column BBBB-BB-003 is missing in TableA but result is not showing the keys columns, showing NULL instead of key columns. Should show key columns with data and with comments that 'Missing in Table-A' and same if TableA's key column is missing in TableB then it should all the data and with comments that 'Missing in Table-B'
2- if Comments has null then it should replace with ‘ ‘ (blank).
Note:I want to keep VARCHAR(20) to convert in varchar with every column in select query. Currently I am using VARCHAR(20) to convert which want to keep.
Create TableA (Name varchar(20), Code varchar(20),PerID varchar(20), City varchar(20), Post varchar(20), Address varchar(20), Date1 datetime);
Insert into TableA values (‘Peter’, ‘AA’, ‘001’, ‘HH’, ‘1X’, ‘123 Cres’, ‘2022-01-01’)
Insert into TableA values (‘Smith’, ‘AA’, ‘002’, ‘HH’, ‘1X’, ‘123 Cres’, ‘2022-01-01’)
Insert into TableA values (‘John’, ‘DD’, ‘002’, ‘HH’, ‘1X’, ‘high place’, ‘2022-01-01’)
Insert into TableA values (‘Doren’, ‘EE’, ‘007’, ‘HH’, ‘1X’, ‘123 Cres’, ‘2022-01-01’)
Insert into TableA values (‘AAA’, ‘AA’, ‘003’, ‘HH’, ‘1X’, ‘67 Dr’, ‘2022-01-01’)
Create TableB (Name varchar(20), Code varchar(20),PerID varchar(20), City varchar(20), Post varchar(20), Address varchar(20), Date1 datetime);
Insert into TableB values (‘Peter’, ‘AA’, ‘001’, ‘HH’, ‘1X’, ‘123 Cres’, ‘2022-01-01’)
Insert into TableB values (‘Smith’, ‘AA’, ‘002’, ‘FRYN’, ‘1X’, ‘123 Cres’, ‘2022-01-01’)
Insert into TableB values (‘John’, ‘DD’, ‘002’, ‘HH’, ‘1X’, ‘high place’, ‘2022-01-01’)
Insert into TableB values (‘Doren’, ‘EE’, ‘007’, ‘HH’, ‘55X’, ‘123 Cres’, ‘2022-01-01’)
Insert into TableB values (‘BBB’, ‘BB’, ‘003’, ‘HH’, ‘1X’, ‘67 Dr’, ‘2022-01-01’)
with CTE as(
select A.Name,A.Code,A.PerID,
CASE WHEN A.City = B.City THEN '' ELSE isnull(CAST(A.City AS VARCHAR(20)), '') END AS City,
CASE WHEN A.Post = B.Post THEN '' ELSE isnull(CAST(A.Post AS VARCHAR(20)), '') END AS Post,
CASE WHEN A.Address = B.Address THEN '' ELSE isnull(CAST(A.Address AS VARCHAR(20)), '') END AS Address,
CASE WHEN A.Date1 = B.Date1 THEN '' ELSE isnull(convert(VARCHAR(20),A.Date1,23), '') END AS Date1,
case when A.Name is null then 'Missing in Table-A'
when B.Name is null then 'Missing in Table-B' end as Comments /Remaining 3 lines of query in next answer's block*/