0

I am trying to create a table with two columns, holiday_date and day_of_the_week.

I'd like the day_of_the_week column to be derived by default from the holiday_date column using the datepart() function. The day_of_the_week column is by default null and computed when new values of holiday_date are inserted.

I have tried using the query below:

CREATE TABLE [HolidaysTest] (
    [holiday_date] varchar(50),
    [day_of_the_week] int DEFAULT datepart(dW, holiday_date)
)

This isn't working and the error that results is shown below

The name "holiday_date" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.

3
  • 1
    Use a computed column? You don't want to edit it do you? Commented Sep 27, 2019 at 9:19
  • No I don't. I'd like it to return an integer value representing the day of the week depending on the date. Commented Sep 27, 2019 at 9:22
  • learn.microsoft.com/en-us/sql/relational-databases/tables/… Commented Sep 27, 2019 at 9:42

2 Answers 2

1

If you want day_of_the_week() to be in the table and always consistent with holiday_date, then I would recommend:

create table HolidaysTest (
    holiday_date date,
    day_of_the_week as (datepart(weekday, holiday_date))
);

Note the change of type of holiday_date. Do not store dates as strings! Use the built-in data types.

day_of_the_week is calculated when you refer to it in a query. It is always accurate.

Also not that weekday is spelled out. This generally makes queries less ambiguous and more maintainable.

Sign up to request clarification or add additional context in comments.

Comments

1

If you don't want to store day of week and you only want to return int value representing week of day then don't create column for it in table.

Just create your table with holiday_date and at time of fire select query write something like this:

select holiday_date, DATEPART(WEEKDAY, holiday_date) from HolidaysTest

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.