T-SQL将常量值传递给过程/函数

时间:2014-04-29 19:13:28

标签: sql-server tsql datediff

我最近注意到DateDiff不是很准确,所以想写一个更准确的版本

约会者不准确的例子

DECLARE @sTime as DATETIME ='12/31/2013 23:59:59'
DECLARE @eTime as DATETIME ='01/01/2014 00:00:00'
SELECT 
    DateDiffYears   = DATEDIFF(YEAR, @sTime, @eTime)
,   DateDiffMonths  = DATEDIFF(MONTH, @sTime, @eTime)
,   DateDiffDays    = DATEDIFF(DAY, @sTime, @eTime)
,   DateDiffHours   = DATEDIFF(HOUR, @sTime, @eTime)
,   DateDiffMinutes = DATEDIFF(MINUTE, @sTime, @eTime)
,   DateDiffSeconds = DATEDIFF(SECOND, @sTime, @eTime)
-- expected results: 0 year, 0 month, 0 day, 0 hour, 0 minute, 1 second
-- actual results:   1 year, 1 month, 1 day, 1 hour, 1 minute, 1 second

我的问题是,您是否可以将DAY,SECOND,HOUR等常量值传递到自定义函数中。

实施例: SELECT dbo._newDateDiff(YEAR, @sTime, @eTime)

我认为唯一的方法是传入一个字符串值为“年”,“月”和“等”,这是真的吗?

谢谢,

1 个答案:

答案 0 :(得分:-1)

是的,例如你可以用这个来做一个程序(一个函数不允许EXECUTE在其中):

declare @datepart char(2)
declare @stime char(19)
declare @etime char(19)
declare @sql varchar(100)
set @datepart = 'ss'
set @stime = '12/31/2013 23:59:59'
set @etime = '01/01/2014 00:00:00'
set @sql = 'SELECT DATEDIFF('+@datepart+','''+@stime+''','''+@etime+''')'
exec (@sql)

...您可以使用它来定义要比较的日期部分以及stime和etime。

CREATE PROC _newDateDiff (@datepart CHAR(2),@stime CHAR(19),@etime CHAR(19))
AS
BEGIN
declare @sql varchar(100)
set @sql = 'SELECT DATEDIFF('+@datepart+','''+@stime+''','''+@etime+''')'
exec (@sql)
END

EXEC _newDateDiff 'SS','12/31/2013 23:59:59','01/01/2014 00:00:00' 

或者您可以将值放入具有datetime数据类型的表中:

CREATE TABLE DATET
(
DID INT,
DT DATETIME
)
INSERT INTO DATET VALUES (1,'12/31/2013 23:59:59')
INSERT INTO DATET VALUES (1,'01/01/2014 00:00:00')

SELECT DISTINCT DID,MAX(DT)-MIN(DT) FROM DATET GROUP BY DID