我正在尝试创建一个将用于报告的存储过程,并且我希望2个日期参数的DEFAULT值为今天的日期和1个月之前。
以下是正确的方法吗?我在其他地方读到我应该使用COALESCE ...(SEE HERE)这是一个敏感的制作系统所以我想在我前进之前仔细检查。
CREATE PROCEDURE spCaseNoteReport
-- Add the parameters for the stored procedure here
@ContactStartDate DateTime = null,
@ContactEndDate DateTime = null
AS
IF @ContactStartDate is null
SET @ContactStartDate = dateadd(m,-1, CONVERT(date, GETDATE()))
IF @ContactEndDate is null
SET @ContactEndDate = CONVERT(date, GETDATE())
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT (id.LastName + ', ' + id.FirstName) AS 'MemberName'
,c.ContactDate
,Li.ItemDescription AS 'Location'
,c.PresentAtContact
,c.ContactDetails
,c.InsertUser
,c.TimeSpentUnits
FROM dbo.tblCaseNotes c
inner join dbo.tblIdentificationMap id
on c.PersonID = id.PersonID
left outer join dbo.tblCaseNoteContactLocation L
on c.Casenoteid = L.Casenoteid
inner join dbo.tblCaseNotesMaintItem Li
on L.ContactLocationID = Li.ItemID
WHERE c.ContactDate BETWEEN @ContactStartDate AND @ContactEndDate
ORDER BY MemberName, c.ContactDate, c.InsertUser
END
因此,当我实际尝试为此运行CREATE PROCEDURE
时,我收到以下错误 - >
Msg 243, Level 16, State 1, Procedure spCaseNoteReport, Line 12
Type date is not a defined system type.
Msg 243, Level 16, State 1, Procedure spCaseNoteReport, Line 14
Type date is not a defined system type.
答案 0 :(得分:3)
这种方法没有错。我自己用它。
参数默认值只能是常量或udfs,所以替代方法是使用udfs,这实际上并没有真正帮助。
编辑:从日期时间删除时间组件的最佳方法
DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
看到这个优秀的SO Q + A "Most efficient way in SQL Server to get date from date+time?"(不是我的!)