2
您好我有以下表格:動態SQL Server 2008的查詢聯接
CREATE TABLE #Test
(
ProductID int,
MainMasterFeatureID int,
--MasterFeatureValue Varchar(100),
ChilFeatureName varchar(100),
ParentFeatureName varchar(100)
)
INSERT INTO #Test
SELECT 40,1,,'Pack','Type'
UNION ALL
SELECT 40,0,'Laminate','Technology'
UNION ALL
SELECT 40,11,'Yes','Coated'
UNION ALL
SELECT 52,1,'Roll','Type'
UNION ALL
SELECT 52,11,'NO','Coated'
SELECT * FROM #Test
CREATE TABLE #tProduct
(
tProductID int PRIMARY KEY,
tProductCode nvarchar(128),
tProductName nvarchar(256)
)
INSERT INTO #tProduct
SELECT 40,'001','ABC'
UNION ALL
SELECT 52,'002','XYZ'
UNION ALL
SELECT 50,'006','IJK'
From #test table
我要生成的結果是這樣的:
ProductID Type Technology Coated
40 Pack Laminate YES
52 Roll Null No
這裏類型,技術,塗層不固定這樣可以動態生成...
它可以這樣生成...
Declare @sql Varchar(MAX)
Select @sql = 'SELECT ProductID, '
Select @sql = @sql + STUFF((Select DISTINCT ',MAX(Case When ParentFeatureName = ' + CHAR(39) + ParentFeatureName + CHAR(39) + ' Then ChilFeatureName Else ' + CHAR(39) + CHAR(39) + ' End) As ' + ParentFeatureName From #Test For XML PATH('')),1,1,'')
Select @sql = @sql + ' FROM #Test Group By ProductID'
Execute(@sql)
現在我想加入這個充滿活力的查詢#tProduct
來得到想要的結果:
tProductID tProductName Type Technology Coated
40 ABC Pack Laminate YES
52 XYZ Roll Null No
感謝mikael..i得到了理想的結果 – SQL006