下面我有一段来自我试图动态化的存储过程的代码。这意味着我想运行EXEC('select * from table_name WHERE filter=something')
以将结果集返回到我的 Web 服务。我正在查询的表中的 week_start_date 字段是日期时间字段,而不是日期字段。如何正确地将 datetime 参数附加到动态 SQL,以便它在查询中正确解释它?另外,如果您对如何使代码更清洁有任何建议,我会接受建议。
当我查看数据时,我的值如下所示:
2012-08-10 00:00:00.000
不工作的 T-SQL 代码:
ALTER PROCEDURE [dbo].[logged_time_by_week]
@week_start_date_filter datetime = null
AS
BEGIN
……
DECLARE @select_clause nvarchar(4000);
DECLARE @from_clause nvarchar(4000);
DECLARE @where_clause nvarchar(4000);
DECLARE @order_clause nvarchar(4000);
SET @select_clause =
' SELECT '
+ ' [sunday_hours],'
+ ' [monday_hours],'
+ ' [tuesday_hours],'
+ ' [wednesday_hours],'
+ ' [thursday_hours],'
+ ' [friday_hours],'
+ ' [saturday_hours]'
SET @from_clause =
' FROM '
+ ' [timesheet_row] '
SET @where_clause = ''
IF @week_start_date_filter IS NOT NULL AND @week_start_date_filter != ''
BEGIN
IF @where_clause != ''
BEGIN
SET @where_clause = @where_clause + ' AND '
END
SET @where_clause = @where_clause + ' [week_start_date] = ' + CONVERT(nvarchar, @week_start_date_filter)
END
IF @where_clause != ''
BEGIN
SET @where_clause = ' WHERE ' + @where_clause
END
SET @order_clause = ' ORDER BY [' + @sort_column + '] ' + @sort_direction
EXEC(@select_clause + @from_clause + @where_clause + @order_clause)