我需要在SQL中将当前月份的第1个日期显示为列名
我编写了以下查询,但没有获得正确的列名
SELECT Citrix_ID as [Citrix ID], Full_Name as [Full Name]
, Band, Cigna_DOJ as [Cigna DOJ]
, [01] +' as ' + '''' + SELECT CONVERT(VARCHAR,DATEADD(month, DATEDIFF(MONTH, 0, GETDATE()), 0),106) + ''''
FROM [dbo].[admin.Attendance]
答案 0 :(得分:2)
您可以将Dynamic Sql用于此类用途。
示例片段:
declare @FirstDayOfMonth date = dateadd(day,1,eomonth(GetDate(),-1));
declare @ColName varchar(30) = quotename(format(@FirstDayOfMonth,'dd-MMM-yyyy'));
declare @DynSql nvarchar(max);
-- build the string for the actual query
set @DynSql = 'select 1 as '+ @ColName;
-- test how it looks
select @DynSql as DynSql;
-- run it
exec(@DynSql);
结果:
01-Jan-2019
-----------
1
对于您的查询,字符串可以这样构造:
set @DynSql = 'SELECT'+char(10)+
' Citrix_ID as [Citrix ID]'+char(10)+
', Full_Name as [Full Name]'+char(10)+
', Band'+char(10)+
', Cigna_DOJ as [Cigna DOJ]'+char(10)+
', [01] as '+ @ColName +char(10)+
'FROM [dbo].[admin.Attendance]';
请注意,在Sql Server 2017+中,有一个CONCAT_WS
答案 1 :(得分:0)
尝试如下
SELECT SELECT format( DATEADD(month, DATEDIFF(month, 0,getdate()), 0),'dd-MMM-yyyy') AS _stday AS firstday,Citrix_ID as [Citrix ID], Full_Name as [Full Name], Band, Cigna_DOJ as [Cigna DOJ]
FROM [dbo].[admin.Attendance]
答案 2 :(得分:0)
SELECT CONVERT(VARCHAR,DATEADD(month, DATEDIFF(MONTH, 0, GETDATE()), 0),101) as FirstDateOfMonth
答案 3 :(得分:0)
您可以直接使用REPLACE
功能
SELECT REPLACE(CONVERT(VARCHAR,DATEADD(month, DATEDIFF(MONTH, 0, GETDATE()),0),106),' ', '-')
as FirstDateOfTheMonth;
01-Jan-2019