SQL Server EXECUTE sp_executesql中的DateTime操作

时间:2009-10-21 00:08:57

标签: sql sql-server stored-procedures

我正在尝试执行以下操作:

EXECUTE sp_executesql
    N'SELECT TOP 10 * FROM dbo.Items WHERE DateCreated BETWEEN @start AND @end'
    , N'@start DATETIME, @end DATETIME'
    , @start = '20091001'
    , @end = GETDATE() --problem is caused by this line

Error:
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near ')'.

我需要操纵日期并将其作为参数传递,即一周的星期一,一年中的某个月等等。它是否可能?

感谢。

1 个答案:

答案 0 :(得分:5)

你需要声明一个变量,我认为它在使用函数时遇到了麻烦:

DECLARE @endDate as datetime
SET @endDate = GETDATE()
EXECUTE sp_executesql
    N'SELECT TOP 10 * FROM dbo.Items WHERE DateCreated BETWEEN @start AND @end'
    , N'@start DATETIME, @end DATETIME'
    , @start = '20091001'
    , @end = @endDate