2

Looking at the return value for year() on SQL Server and it seems to be an int.

Then why does the following statement return 'equal'?

Why does the comparison operator consider int 2002 and string '2002' equal? Should it?

select 
    case 
        when year('2002-01-14 00:00:00.000') = '2002' then 'equal' 
        else 'not equal' 
    end

Microsoft's Year Doc.

4
  • 3
    Yes, sql server is doing an implict cast changing '2002' to a int. it always attempts to cast the 2nd data type to the first one. Commented Nov 11, 2016 at 17:25
  • 1
    Whether something should or shouldn't happen doesn't matter. What matter is that you know what does happen and code accordingly. Commented Nov 11, 2016 at 17:26
  • 1
    Good question, and nice answer from @xQbert. There are some very good arguments against using implicit casts. As a general rule, I try to avoid them in my dbs. Commented Nov 11, 2016 at 17:32
  • @destination-data nice article supporting avoiding implicit casting. Commented Nov 11, 2016 at 17:42

1 Answer 1

2

Because SQL server is implicitly casting '2002' to the data type of of the first value in the equality check. (int) in this case

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.