简体   繁体   中英

Dynamic SQL Server 2008 Query Join

Hi I have the following table:

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 I want to generate result like this:

 ProductID          Type             Technology      Coated 

   40               Pack              Laminate          YES 

   52               Roll               Null              No

Here type,Technology,Coated are not fixed this can be generated dynamically..

It can be generated like this...

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)

Now I want to join this dynamic query to #tProduct to get the desired results:

 tProductID   tProductName        Type             Technology      Coated 

   40            ABC              Pack              Laminate          YES 

   52            XYZ              Roll               Null              No  

You can do this with a dynamic pivot and a join in the dynamic query to #tProduct

declare @SQL nvarchar(max)
declare @FieldList nvarchar(max)

set @FieldList = 
  (
  select distinct ','+quotename(ParentFeatureName)
  from #Test
  for xml path(''), type
  ).value('substring(text()[1], 2)', 'nvarchar(max)')

set @SQL = 
'
select TP.tProductID,
       TP.tProductName,'+
       @FieldList+'
from 
  (
  select ProductID, 
         ParentFeatureName,
         ChilFeatureName
  from #Test
  ) as T
pivot
  (
    max(T.ChilFeatureName) 
    for T.ParentFeatureName in ('+@FieldList+')
  ) as P
inner join #tProduct as TP
  on P.ProductID = TP.tProductID'

exec(@SQL)

SQL Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM