I have a sql server report which have startdate and enddate datetime parameters but when i specify datetime in them the report show error
An error has occurred during report processing.
Exception has been thrown by the target of an invocation.
Conversion failed when converting date and/or time from character string.
startdate paramter have value 6/22/2011 12:00:00 AM when set as report parameter in C# code, My stored procedure code is
create PROCEDURE Price
@Startdate datetime = null,
@Enddate datetime = null
AS
declare @sql varchar(8000)
set @sql = 'SELECT CommodityPrice.dtm_Date FROM Commodity
INNER JOIN CommodityPrice ON Commodity.int_CommodityId = CommodityPrice.int_CommodityId where Commodity.vcr_HSCode is not null '
IF (@Startdate <> '')
BEGIN
SET @sql = @sql + ' and CommodityPrice.dtm_Date >= '+ @Startdate
END
IF (@Enddate <> '')
BEGIN
SET @sql = @sql + ' and CommodityPrice.dtm_Date <= '+ @Enddate
END
set @sql = @sql+ ' order by CommodityPrice.dtm_Date desc'
exec (@sql)
How can i remove this issue? I am creating dynamic sql because i have some other paramters as well.
My advice; don’t concatenate input ;p (as always). You can still use parameters with EXEC, especially with sp_ExecuteSQL. That will avoid all the issues and allow query-plan re-use.
NEVER concatenate user input, even in TSQL. ALWAYS use parameters, unless it is absolutely impossible to do so.
As a trivial example (in particular to show how the parameter names don’t need to match):
we are passing in @a and @b as parameters (mapping to @x and @y) to the SQL in @sql, and executing in a safe, re-usable, cachable way.