如何从此查询中获取所有行

时间:2017-10-12 01:52:39

标签: sql sql-server

如何返回我想要的值?

我知道明显的价值是弄乱结果,但不知道如何解决

Declare @ColumnNames NVARCHAR(MAX) = '';
Declare @today as date; Set @today = getdate();

Select distinct @ColumnNames +=  QuoteName(cast(date as varchar(100))) + ','
From Dates
where date >= @today

Print @ColumnNames

结果

[2017-10-17],

但应该是

[2017-10-11],[2017-10-12],[2017-10-13],[2017-10-14],[2017-10-15],[2017-10-16],[2017-10-17],

1 个答案:

答案 0 :(得分:0)

删除'+',使用coalesce并在使用coalesce之前使用distinct。在我的情况下,where子句是where date > 2017-10-04

select distinct convert(varchar(10),date,23) as new_date
into #temp1
from dates

declare @columnnames nvarchar(max)
select  @columnnames =  coalesce(@columnnames+ ', ', '') + new_date 
from #temp1  

drop table #temp1
print @columnnames

<强>输出

enter image description here