也許是這樣的:
測試數據:
CREATE TABLE #PhoneBook(ID INT,Name VARCHAR(100))
INSERT INTO #PhoneBook VALUES(1,'Reza'),(2,'Ali')
CREATE TABLE #DynamicField(ID INT,Caption VARCHAR(100))
INSERT INTO #DynamicField VALUES(1,'Job'),(2,'Level')
CREATE TABLE #PhoneBook_DynamicField_Rel(ID INT,PhoneBookID INT,
DynamicFieldID INT,Value VARCHAR(100))
INSERT INTO #PhoneBook_DynamicField_Rel
VALUES(1,1,1,'Emp'),(2,1,2,'1'),(3,2,1,'SomeJob')
獲取colums
DECLARE @cols VARCHAR(MAX)
SELECT @cols=STUFF
(
(
SELECT
',' +QUOTENAME(tbl.Caption)
FROM
#DynamicField AS tbl
FOR XML PATH('')
)
,1,1,'')
那麼查詢就像這樣:
DECLARE @query NVARCHAR(4000)=
N'SELECT
*
FROM
(
SELECT
*
FROM
(
SELECT
PhoneBook.ID,
PhoneBook.Name,
field.Caption,
rel.Value
FROM
#PhoneBook AS PhoneBook
JOIN #PhoneBook_DynamicField_Rel AS rel
ON PhoneBook.ID = rel.PhoneBookID
JOIN #DynamicField AS field
ON rel.DynamicFieldID=field.ID
) AS SourceTable
) AS p
PIVOT
(
MAX(Value) FOR Caption IN('[email protected]+')
) AS pvt'
EXECUTE(@query)
然後在我的情況下,我會刪除臨時表:
DROP TABLE #PhoneBook
DROP TABLE #DynamicField
DROP TABLE #PhoneBook_DynamicField_Rel
你嘗試過這麼遠嗎?不要在這裏寫一個問題,期待別人爲你做你的工作。 – Dan
我不知道如何樞軸工作,我不希望其他人爲我做我的工作,只是我有問題,我認爲這個網站是爲它...你可以問,你不知道和迴應其他人回答什麼知道,並且相反,。我也想知道樞軸是如何工作的,這不是我的工作......這是我的問題 –