Reputation: 735
I have this SQL Server query which is returning Conversion failed when converting date and/or time from character string.
(
@numberRecords int,
@date varchar(12)
)
AS
SET ROWCOUNT @numberRecords
SELECT re.ID, re.RecentChangeTypeID, re.LogID, re.RevisionID
FROM RecentChanges re
FULL OUTER JOIN Revisions rev
ON re.RevisionID = rev.ID
FULL OUTER JOIN Logs lg
ON re.LogID = lg.ID
WHERE convert(datetime, rev.Timestamp) >= '@date' OR
convert(datetime, lg.Timestamp) >= '@date';
RETURN
The date
parameter returns a string value in the format "dd-MM-yyyy". What may be the cause?
Upvotes: 1
Views: 18293
Reputation: 103579
remove the single quotes as @JNK has described to make your query work. However, for possibly much better performance (index usage) try this query (if you have indexes on the columns Revisions.Timestamp
and Logs.Timestamp
) :
SELECT
re.ID, re.RecentChangeTypeID, re.LogID, re.RevisionID
FROM RecentChanges re
INNER JOIN Revisions rev ON re.RevisionID = rev.ID
WHERE rev.Timestamp >= @date
UNION
SELECT
re.ID, re.RecentChangeTypeID, re.LogID, re.RevisionID
FROM RecentChanges re
INNER JOIN Logs lg ON re.LogID = lg.ID
WHERE lg.Timestamp >= @date
Upvotes: 1
Reputation: 65147
Don't put your @date
parameter inside single quotes - it's being interpreted as a string instead of as a parameter.
As written you are trying to make '@date'
a datetime
which won't parse.
That being said, you should probably make the input parameter a datetime
in the first place.
Upvotes: 4
Reputation: 1
it looks to me, at first glance, that you are converting to datetime, not from it. I am assuming rev.Timestamp is a datetime already, while your @date is a varchar(12)...so SQL Server is complaining that it can't compare a datetime to a string...
Upvotes: 0