OR Declare @QryString varchar(8000)Create TAble ##tbl1 (col1 varchar(8),col2 varchar(8))Create TAble ##tbl2 (col3 varchar(8),col4 varchar(8))Insert ##tbl1 Select '1','A' Union All Select '2','B' Union AllSelect '3','C'Insert ##tbl2 Select '2','XX' Union All Select '3','YY' Union All Select '1','ZZ' Union All Select '4','NN'-- Pivot the Table Query Set @QryString = 'Select 'Select @QryString = @QryString + 'Max(Case When Col4 = ''' + Col4 + ''' Then Col4 End )' + Col4 + ',' From ##tbl2--Remove the last ',' Select @Qrystring = Left(@QryString ,len(@QryString)-1)Select @QryString = @QryString + ' Into ##tbl3 From ##Tbl2 '-- Now Insert the values into 3rd table Exec(@QryString)--Now finally run the query :-)Select t1.Col1,t3.* from ##Tbl3 t3,##tbl1 t1-- Drop The Temp Tables Drop Table ##tbl2,##tbl1,##tbl3
Chirag