Hi @Jay Jackson ,
Welcome to Microsoft Q&A!
Agreed with Erland, you could combine all necessary columns from different tables into one query and produce the dynamic pivot at last.
It is also recommended for you to post CREATE TABLE statements for your tables together with INSERT statements with sample data, enough to illustrate all angles of the problem. We also need to see the expected result of the sample.
In addition, you could refer below query to produce all columns from different 4 tables and display only one ID column from table1.
DECLARE @SQL NVARCHAR(MAX)
DECLARE @SQL1 NVARCHAR(MAX)
DECLARE @SQL2 NVARCHAR(MAX)
SELECT @SQL = STUFF(( SELECT ', t2.' + QUOTENAME(C.COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.TABLE_SCHEMA = 'dbo' AND C.TABLE_NAME = 'table2' and C.COLUMN_NAME<>'ID'
ORDER BY C.ORDINAL_POSITION FOR XML PATH('')),1,2,'')
SELECT @SQL1 = STUFF(( SELECT ', t3.' + QUOTENAME(C.COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.TABLE_SCHEMA = 'dbo' AND C.TABLE_NAME = 'table3' and C.COLUMN_NAME<>'ID'
ORDER BY C.ORDINAL_POSITION FOR XML PATH('')),1,2,'')
SELECT @SQL2 = STUFF(( SELECT ', t4.' + QUOTENAME(C.COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.TABLE_SCHEMA = 'dbo' AND C.TABLE_NAME = 'table4' and C.COLUMN_NAME<>'ID'
ORDER BY C.ORDINAL_POSITION FOR XML PATH('')),1,2,'')
SELECT @SQL = 'SELECT t1.ID,t1.col1,t1.col2,t1.col3,' + @SQL +','+ @SQL1 +','+ @SQL2+
' FROM table1 t1
left join table2 t2 on t1.id=t2.id
left join table3 t3 on t1.id=t3.id
left join table4 t4 on t1.id=t4.id
'
--print @SQL
EXECUTE(@SQL)
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.