I need to display 1st date of current month as column name in SQL
I wrote the below query, but not getting correct column name
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]
You can use Dynamic Sql for such things.
Example snippet:
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);
Result:
01-Jan-2019
-----------
1
For your query the string could be constructed like this:
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]';
Note that in Ms Sql Server 2017+ there's a CONCAT_WS
Try like below
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]
SELECT CONVERT(VARCHAR,DATEADD(month, DATEDIFF(MONTH, 0, GETDATE()), 0),101) as FirstDateOfMonth
You can directly use REPLACE
function
SELECT REPLACE(CONVERT(VARCHAR,DATEADD(month, DATEDIFF(MONTH, 0, GETDATE()),0),106),' ', '-')
as FirstDateOfTheMonth;
01-Jan-2019
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.