Hi everybody,
I'm using dynamic SQL in a stored procedure to build up a query that can have a variety of WHERE clauses depending on what parameters are passed into the stored procedure. One of my parameters (a DATETIME) seems to be causing an error:
Conversion failed when converting datetime from character string
The stored proc code is:
When trying to run it with test data as follows:
it generates the error above on the line:
Can someone help me with this, please?
Thanks as always
Craftor

I'm using dynamic SQL in a stored procedure to build up a query that can have a variety of WHERE clauses depending on what parameters are passed into the stored procedure. One of my parameters (a DATETIME) seems to be causing an error:
Conversion failed when converting datetime from character string
The stored proc code is:
Code:
CREATE PROCEDURE dbo.praGetSpecifiedEvent
@vcrUserName VARCHAR (8) = NULL,
@dtmDateFrom DATETIME = NULL,
@dtmDateTo DATETIME = NULL,
@in4IDEventStatus INT = NULL,
@result TINYINT OUTPUT
AS
BEGIN
SET NOCOUNT ON
SET @result = null
DECLARE @sqlStatement VARCHAR (5000)
DECLARE @whereClause VARCHAR(5000)
SELECT @sqlStatement =
'
SELECT
in4IDEvent,
dtmDateLastEvent,
dtmDateCurrentEvent,
vcrNameLastModifiedUser
FROM
dbo.tblEvent TE
INNER JOIN dbo.tblPaymentDetails P
ON TE.in4IDPayment = P.in4IDPayment
INNER JOIN dbo.tblEventStatus ES
ON TE.in4IDEventStatus = ES.in4IDEventStatus
'
IF @vcrUserName IS NOT NULL
BEGIN
SELECT @whereClause = ' P.vcrUserName = ''' + @vcrUserName + ''''
END
IF @dtmDateFrom IS NOT NULL
BEGIN
IF @whereClause IS NOT NULL
BEGIN
SELECT @whereClause = @whereClause + ' AND '
END
SELECT @whereClause = @whereClause + ' TE.dtmDateLastEvent <= ''' + @dtmDateTo + ''''
END
IF @dtmDateTo IS NOT NULL
BEGIN
IF @whereClause IS NOT NULL
BEGIN
SELECT @whereClause = @whereClause + ' AND '
END
SELECT @whereClause = @whereClause + ' TE.dtmDateLastEvent <= @dtmDateTo '
END
IF @in4IDEventStatus IS NOT NULL
BEGIN
IF @whereClause IS NOT NULL
BEGIN
SELECT @whereClause = @whereClause + ' AND '
END
SELECT @whereClause = @whereClause + ' TES.in4IDEventStatus <= ' + @in4IDEventStatus
END
IF @whereClause IS NOT NULL
BEGIN
SELECT @sqlStatement = @sqlStatement + ' WHERE ' + @whereClause
END
EXEC (@sqlStatement)
SET @result = 1
END
GO
When trying to run it with test data as follows:
Code:
DECLARE @result tinyint
DECLARE @dtm DATETIME
SET @dtm = '2007-12-06'
EXEC praGetSpecifiedEvent 'username', @dtm, NULL, NULL, @result OUTPUT
SELECT @result
it generates the error above on the line:
Code:
SELECT @whereClause = @whereClause + ' TE.dtmDateLastEvent <= ''' + @dtmDateTo + ''''
Can someone help me with this, please?
Thanks as always
Craftor