Below I have a snippet of code from a stored procedure I’m trying to make dynamic. Meaning I want to run the EXEC('select * from table_name WHERE filter=something') to return a result set to my web service. The week_start_date field in my table that I’m querying is a datetime field, not a date field. How do I properly append the datetime parameter to the dynamic SQL so it interprets it correctly in the query? Also, if you have suggestions on how to make the code cleaner, I’ll take advice.
When I look at the data, I have values that look like this:
2012-08-10 00:00:00.000
T-SQL code that is not working:
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)
Easiest way to troubleshoot these kinds of errors is to print out the generated sql to see why it’s failing.
Just by looking at your query i believe you just need to fix the quotes around the @week_start_date_filter variable.
Also as a side note, I’d recommend instead to use parameterized sql if you have to use dynamic sql. Here’s an example using sys.objects since i don’t know the schema of your table.