Click here to Skip to main content
15,891,629 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am using a dynamic query and trying to fetch columns in a single row using COALESCE function. But it is not working

What I have tried:

DECLARE @COLUMNS NVARCHAR(3000)
SET @COLUMNS = 'SELECT
COALESCE('+@COLUMNS+' + '','', '') +
CM.ColumnName
FROM ICCS_StdReportTable_Master TM
inner join
ICCS_StdReport_Column_Master CM
on CM.TableId=TM.TableId
where
tm.RecordIdentifierKeyword in (
select SUBSTRING(VALUE,TM.StartPosition,TM.Length) from ICCS_MENUS MNU
INNER JOIN
ICCS_StdReportTable_Master TM
ON TM.TableName=SUBSTRING(VALUE,TM.StartPosition,TM.Length)
INNER JOIN
ICCS_SCREENS SC
ON SC.SCREENID=MNU.SCREENID'
Posted
Updated 27-Feb-17 3:57am

1 solution

"not working" is not very helpful and makes it harder for us to help you! It's always a good idea to make the query as simple as possible first - get something working and then add the complexity later. That way you could include some sample data and the table schemas. These things make your question better meaning it is more likely to get a quick answer.

To your problem though ... I will demonstrate what is going on with this very simple table:
SQL
eate table [ColumnNames]
(
	id INT IDENTITY(1,1),
	ColumnName varchar(125)
)
INSERT INTO ColumnNames values ('COL1'),('COL2'),('COL3')

If I do something similar to your query I get this query:
SQL
DECLARE @columns NVARCHAR(MAX) = 'SELECT '
SELECT @columns = COALESCE(@columns+',' ,'') + CAST(ColumnName AS Varchar)
FROM ColumnNames
PRINT @columns
But when I run that query I get the results:
SELECT ,COL1,COL2,COL3
Spot that extra comma after the SELECT but before COL1. It's going to cause a syntax error in the final query. You shouldn't be surprised that it's there as you are trying to add a comma to the end of @columns for each value returned from the table! If @columns already contains data then SQL will put the comma on the end of that first.

If I change the query to this
DECLARE @columns NVARCHAR(MAX) = null
SELECT @columns = COALESCE(@columns+',' ,'') + CAST(ColumnName AS Varchar)
FROM ColumnNames
then I get
COL1,COL2,COL3
The problem now is how to get the rest of your query together. My personal preference is to have a separate variable for the column list and the final sql e.g.
SQL
DECLARE @sql VARCHAR(MAX)
SET @sql = 'SELECT ' + @columns + ' ... the rest of your query'
Even if you don't want to do that it is still a two stage query -
SQL
DECLARE @columns NVARCHAR(MAX) = null
SELECT @columns = COALESCE(@columns+',' ,'') + CAST(ColumnName AS Varchar)
FROM ColumnNames
set @columns = 'SELECT ' + @columns + '... the rest of your query'
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900