Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>My suggestion when you are working with dynamic SQL is to always write the query hard-coded first, so you can get the logic correct, then convert it to dynamic SQL.</p> <p>Since you are attempting to pivot 3 columns of data I would first unpivot the <code>type_ds</code>, <code>expdt</code> and comdt` columns, then apply the PIVOT function.</p> <p>The hard-coded version of the query will be:</p> <pre><code>SELECT * FROM ( select pro_id, type_ds = case when col ='type_ds' then type_ds else type_ds+col end, value from ( SELECT A.Pro_Id, c.Type_DS, convert(varchar(10), b.ExpDt, 120) ExpDt, convert(varchar(10), b.ComDt, 120) ComDt FROM dbo.Project A left join [dbo].[Prj_App] B on A.Pro_id = B.Pro_Id right outer join dbo.Approval_Type C on B.App_Id = C.App_ID ) s cross apply ( select 'type_ds', type_ds union all select 'expdt', expdt union all select 'comdt', comdt ) c (col, value) ) data PIVOT ( MAX(value) FOR Type_DS IN (RMC2, RMC2expdt, RMC2comdt, RMC1, RMC1expdt, RMC1comdt) ) pvt1 </code></pre> <p>See <a href="http://sqlfiddle.com/#!3/08155/19" rel="nofollow">SQL Fiddle with Demo</a>. Now that you have a working version of the query, you can easily convert it to dynamic SQL:</p> <pre><code>DECLARE @SQL1 NVARCHAR(MAX) = '' DECLARE @SQL NVARCHAR(MAX) = '' SELECT @SQL1 = STUFF((SELECT ',' + QUOTENAME(Type_Ds) + ',' + QUOTENAME(Type_Ds + 'ExpDt') + ',' + QUOTENAME(Type_Ds + 'ComDt') from dbo.Approval_Type FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') SET @SQL = 'SELECT * FROM ( select pro_id, type_ds = case when col =''type_ds'' then type_ds else type_ds+col end, value from ( SELECT A.Pro_Id, c.Type_DS, convert(varchar(10), b.ExpDt, 120) ExpDt, convert(varchar(10), b.ComDt, 120) ComDt FROM dbo.Project A left join [dbo].[Prj_App] B on A.Pro_id = B.Pro_Id right outer join dbo.Approval_Type C on B.App_Id = C.App_ID ) s cross apply ( select ''type_ds'', type_ds union all select ''expdt'', expdt union all select ''comdt'', comdt ) c (col, value) ) data PIVOT ( MAX(value) FOR Type_DS IN (' + @SQL1 + ') ) pvt1 ' --print @SQL EXECUTE SP_EXECUTESQL @SQL </code></pre> <p>See <a href="http://sqlfiddle.com/#!3/08155/20" rel="nofollow">SQL Fiddle with Demo</a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload