1

How can we find the day number for a date passed. Say, if it is 'Sunday', then 1, 'Monday', then 2 and so on. Is there any in built function for this other than user defined functions?

CodeMachine
  • 260
  • 2
  • 4
  • 10

2 Answers2

2

SQL Server builtin function DATEPART() takes two parameters and can do what you are trying to do.

SELECT DATEPART(DW , GETDATE() -1)   -- Returns 1 for sunday. 

Also depending on what you pass to the 1st parameters in the function, it can return different parts of the date value passed in the second parameter.

M.Ali
  • 67,945
  • 13
  • 101
  • 127
  • Actually, this one returns 1 for Monday. You could avoid the `-1` part right? – AswinRajaram Jul 16 '18 at 06:44
  • @AsRa I have used `-1` is to get Sunday's date not to get 1, I have passed GETDATE() which will pass the function today's date, I wanted to passed the functino Sunday's date. – M.Ali Jul 16 '18 at 06:45
1

You can use the function DAYOFWEEK. The format is:

 SELECT{fn DAYOFWEEK(GETDATE())}

Alternate method:

 SELECT DATEPART(WEEKDAY,GETDATE())
AswinRajaram
  • 1,519
  • 7
  • 18