Ayesha Fathima

Ayesha Fathima

  • NA
  • 184
  • 28.1k

The column prefix 'a' does not match with a table name

Jul 19 2018 1:16 AM
  1.  DECLARE @cols AS NVARCHAR(MAX),  
  2.  @query  AS NVARCHAR(MAX)  
  3.  select @cols = STUFF((SELECT ',' + QUOTENAME(role_id)   
  4.   from form_appr_workflow where ref_no='LYC002-001-CHAR-2018-96'  
  5.    group by user_id, role_id  
  6.    order by role_id  
  7.    FOR XML PATH(''), TYPE  
  8.    ).value('.''NVARCHAR(MAX)')   
  9.         ,1,1,'')  
  10. set @query = N'SELECT ' + @cols + N' from   
  11. (  
  12.                 select user_id, role_id  
  13.                 from form_appr_workflow  
  14.             ) x  
  15.  pivot   
  16.             (  
  17.                 max(user_id)  
  18.                 for role_id in (' + @cols + N')  
  19.             ) p '  
  20.   
  21. exec sp_executesql @query;  
Result
column-2068     2069     2055
value-   usr1      usr2      usr3
 I need to join one more table to the existing table on roleid ,because in the result instead of numbers(like 2068 etc) i need related rolenames
 
Iam trying to do like this
 it is saying error like 
SQL Error (107): The column prefix 'a' does not match with a table name or alias name used in the query. */ 
  1. DECLARE @cols AS NVARCHAR(MAX),  
  2.  @query  AS NVARCHAR(MAX)  
  3.  select @cols = STUFF((SELECT ',' + QUOTENAME(a.role_id)   
  4.   from form_appr_workflow a join win_role_master b on a.role_id=b.role_id where a.ref_no='LYC002-001-CHAR-2018-96'  
  5.    group by a.user_id, a.role_id  
  6.    order by a.role_id  
  7.    FOR XML PATH(''), TYPE  
  8.    ).value('.''NVARCHAR(MAX)')   
  9.         ,1,1,'')  
  10. set @query = N'SELECT ' + @cols + N' from   
  11. (  
  12.                 select a.user_id,a.role_id  
  13.                 from form_appr_workflow a  
  14. ) x  
  15.  pivot   
  16.             (  
  17.                 max(a.user_id)  
  18.                 for a.role_id in (' + @cols + N')  
  19.             ) p '  
  20.   
  21. exec sp_executesql @query;  
  Expected result
column-coo        chief     head
value-   usr1        usr2    usr3
 

Answers (2)