HejI've been working on this query that will be converted into a Stored Procedure and then used for a report. I've pieced it together, but now I'm running into an issue with the datetype parameter. If I remove the WHERE clause which uses this parameter it runs fine, otherwise I get an error similar to:Line 8: Incorrect syntax near '5'. depending on the date used for @StartDate.Declare @vSQL varchar(1000)Declare @StartDate datetypeDeclare @EndDate datetypeDeclare @Show intDeclare @Order intSet @StartDate = '2006/04/05'Set @EndDate = '2007/04/12'Set @Show = 8Set @Order = 2select @vSQL = 'Select top ' + convert(varchar, @Show) + ' * From ( SELECT Roster_Master.LASTNAME, Roster_Master.MEMBER_NO, COUNT(*) AS Visits, SUM(vUsage.Itemizer1) as Food, max(tbl_d_business_date.business_date) as LastDate FROM vUsage INNER JOIN Roster_Master ON vUsage.Ref_Info_1 = Roster_Master.Member_No_DW INNER JOIN tbl_d_business_date ON vUsage.fk_business_date = tbl_d_business_date.seq_num WHERE (tbl_d_business_date.business_date > ' + convert(varchar, @StartDate) + ') and (tbl_d_business_date.business_date < ' + convert(varchar, @EndDate) + ') Group by LASTNAME, MEMBER_NO) aorder by CASE WHEN ' + convert(varchar, @Order) + ' = 1 THEN Food WHEN ' + convert(varchar, @Order) + ' = 2 THEN Visits END Desc'EXEC(@vSQL)
Using PRINT creates the following String:Select top 8 * From ( SELECT Roster_Master.LASTNAME, Roster_Master.MEMBER_NO, COUNT(*) AS Visits, SUM(vUsage.Itemizer1) as Food, max(tbl_d_business_date.business_date) as LastDate FROM vUsage INNER JOIN Roster_Master ON vUsage.Ref_Info_1 = Roster_Master.Member_No_DW INNER JOIN tbl_d_business_date ON vUsage.fk_business_date = tbl_d_business_date.seq_num WHERE (tbl_d_business_date.business_date > Apr 5 2006 12:00AM) and (tbl_d_business_date.business_date < Apr 12 2007 12:00AM) Group by LASTNAME, MEMBER_NO) aorder by CASE WHEN 2 = 1 THEN Food WHEN 2 = 2 THEN Visits END Desc
I've used the '#' between dates before when passing them to CR. That doesn't seem to help in this case, but is there something else equally simple that I'm missing, or is my strategy way off?In the table design, the 'business_date' uses the Data Type: DATETYPE (datetime)