SQL Server Alter table to get day name only from existing data

uelo1irk  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(103)

I have a table with a datetime column from which I need to extract the name of the day only and add to a new column like dayNameOnly and as default there after.

I have done the same to get the DATEONLY like this, but I cannot get it working with the datename or datepart.

ALTER TABLE someTable 
    ADD dayNameOnly AS CAST(DATEADD(DAY, DATADIFF(DAY, 0, someDateColounm), 0) as DATE)
gpnt7bae

gpnt7bae1#

You wanted the weekday name in string ?

ALTER TABLE someTable 
ADD dayNameOnly 
As datename(weekday, someDateColounm)

On the query that you have shown, you do not need to perform the dateadd/datediff calculation CAST(DATEADD(DAY, DATADIFF(DAY, 0, someDateColounm), 0) as DATE) . You can simply cast() or convert() it to date

CAST(someDateColounm as DATE)
lvjbypge

lvjbypge2#

If you are trying to add computed column somedatecolumn . Here's the script.

alter table someTable 
add dayNameOnly 
As cast(dateadd(day, datediff(day, 0, someDateColounm), 0) as date)

or, if you want to extract the weekday name as a computed column.

alter table someTable 
add dayNameOnly
as datename(dw, someDateColounm)
mbskvtky

mbskvtky3#

create table #mytbl
(mydate  as DATENAME(WEEKDAY,getdate()),sno int)

insert into #mytbl(sno)
values (1)

select * from #mytbl

相关问题