I have been hitting a strange issue lately on SQL Server.
The application I am using is saving user's attributes in a table containing user/attribute/value records. I need to find whether a user is still valid using his end of validity date. The query I have been using is the following:
SELECT COUNT(*) FROM value_all
WHERE AttrName = 'VALIDTO' AND
userkey=574924 AND
CONVERT (DATE,Value, 120) < GETDATE();
The conversion is necessary because all values are stored as VARCHAR.
The query was working correctly but lately I have been hitting the following error:
SQL Error [241] [S0001]: Conversion failed when converting date and/or time from character string.
I though that the stored validity date was wrong. However, the value does match the correct format:
SELECT * FROM value_all
WHERE AttrName = 'VALIDTO' AND
userkey=574924 AND
|userkey |AttrName |Value |
|--------|-----------|--------------------|
|574924 |VALIDTO |2016-07-31T23:59:59 |
I can even do a convert and show the result correctly:
SELECT CONVERT (DATE,Value, 120) AS Date FROM value_all
WHERE AttrName = 'VALIDTO' AND
userkey=574924 AND
CONVERT (DATE,Value, 120) < GETDATE();
|Date |
|-----------|
|2016-07-31 |
However, as soon as I add the COUNT
, the error is coming back.
Does any-one have an idea of what is going on in this case? Is it linked, in some way, to the value used?
EDIT
Thanks to the question at "Conversion to datetime fails only on WHERE clause?", I was able to rework my query as follow, which correct the issues I had:
SELECT COUNT(*) FROM value_all
WHERE AttrName = 'VALIDTO' AND
userkey=574924 AND
CONVERT (DATE, CASE WHEN ISDATE(Value) THEN Value END, 120) < GETDATE();