Question

The code select DATEPART(month,getutcdate()) returns an integer representing the numeric month value of the current date. The value MONTH is one of a number of predefined options for the interval parameter. What is the underlying data type of that interval value?

declare @date datetime = getutcdate()
, @interval notNVarChar(16) = 'month' --what type should this be?  
                                      --Would it need quotes for assignment?

select DATEPART(@interval, @date)
Was it helpful?

Solution 2

There isn't one - you cannot parameterize it.

From the documentation:

DATEPART ( datepart , date )

datepart

Is the part of date (a date or time value) for which an integer will be returned. The following table lists all valid datepart arguments. User-defined variable equivalents are not valid.

(my emphasis)

OTHER TIPS

You can make it parameterize by making a dynamic SQL as below:

declare @date datetime
set @date = GETDATE()
declare @option varchar(50)
declare @sql varchar(max)
SET @option = 'MONTH' --Here you can set other options like hour, second, milisecond etc..

set @sql = 'SELECT DATEPART('+ @option + ',''' + CONVERT(varchar,@date,21)+''')'


print @sql
EXEC( @sql)

There are lots of options available like :

day
week
hour
minute
second
millisecond

etc..

PLease go thru thisLINK

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top