문제

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)
도움이 되었습니까?

해결책 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)

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top