title: dynamic pivot in sql
body: <p>I have an following <code>sql</code> query using pivot function. I do not know what error i have in </p>
  
  <p>this query. Please just help me out of this</p>
  
  <pre><code>DECLARE @DEPT VARCHAR(MAX)            
    SELECT @DEPT=COALESCE('@DEPT+','['+DEPTID+']','['+DEPTID+'])  
    FROM DEPARTMENTDEMO  
    DECLARE @QUERY VARCHAR(MAX)  
    SET @QUERY='SELECT '+@DEPT+'    
  FROM (SELECT DEPTID  
  FROM DEPARTMENTDEMO     
  )AS SOURCETABLE  
  PIVOT  
  (DEPTNAME FOR DEPTID IN ('+@DEPT+')  
  )AS PIVOTTABLE'
  
  EXEC SP_EXECUTESQL @QUERY
  </code></pre>