简体   繁体   中英

Conversion failed when converting date and/or time from character string

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?

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.

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

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM