Может быть что-то вроде этого:
Тестовые данные
CREATE TABLE #User
(
UserID INT,
UserName VARCHAR(100)
)
INSERT INTO #User
VALUES(1,'Jhon')
CREATE TABLE #PhoneBook
(
PhonebookID INT,
UserID INT,
Name VARCHAR(100),
MobileNumber INT
)
INSERT INTO #PhoneBook
VALUES(1,1,'MyBrother',252848)
CREATE TABLE #PhonebookExtraField
(
PhonebookExtraFieldID INT,
UserID INT,
ExtraFieldName VARCHAR(100)
)
INSERT INTO #PhonebookExtraField
VALUES(1,1,'Age'),(2,1,'Job'),(3,1,'Address')
CREATE TABLE #PhoneBookExtraFieldData
(
PhoneBookExtraFieldDataID INT,
PhonebookExtraFieldID INT,
PhonebookID INT,
ExtraFieldValue VARCHAR(100)
)
INSERT INTO #PhoneBookExtraFieldData
VALUES(101,1,1,'30'),(102,2,1,'Web Developer'),(103,3,1,'A.V. Rose')
Найти динамические столбцы
DECLARE @cols VARCHAR(MAX)
SELECT @cols = COALESCE(@cols + ','+QUOTENAME(ExtraFieldName),
QUOTENAME(ExtraFieldName))
FROM
#PhonebookExtraField
Выполнить некоторые динамические sqlс опорой:
DECLARE @query NVARCHAR(4000)=
N'SELECT
*
FROM
(
SELECT
#User.UserName,
#PhoneBook.Name AS [Phonebook(Name)],
#PhoneBook.MobileNumber AS [Phonebook(MobileNumber)],
#PhonebookExtraField.ExtraFieldName,
#PhoneBookExtraFieldData.ExtraFieldValue
FROM
#User
JOIN #PhoneBook
ON #User.UserID=#PhoneBook.UserID
JOIN #PhonebookExtraField
ON #PhoneBook.UserID=#PhonebookExtraField.UserID
JOIN #PhoneBookExtraFieldData
ON #PhonebookExtraField.PhonebookExtraFieldID=#PhoneBookExtraFieldData.PhonebookExtraFieldID
) AS p
PIVOT
(
MAX(ExtraFieldValue)
FOR ExtraFieldName IN('+@cols+')
) AS pvt'
EXECUTE(@query)
Тогда я уберу за собой:
DROP TABLE #User
DROP TABLE #PhoneBook
DROP TABLE #PhonebookExtraField
DROP TABLE #PhoneBookExtraFieldData