Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 CAST and CONVERT

Author  Topic 

KrafDinner
Starting Member

34 Posts

Posted - 2010-07-13 : 11:39:27
I was just wondering what the difference between these two happens to be. Is there a particular best case for using CAST or using CONVERT ?

If anyone could shed some light on that, I would appreciate it.

Thanks ! :D

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-07-13 : 11:51:58
Syntax for CAST:
CAST ( expression AS data_type [ ( length ) ] )

Syntax for CONVERT:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )


They are nearly equal but CONVERT is more powerful if you need the STYLE


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

KrafDinner
Starting Member

34 Posts

Posted - 2010-07-13 : 12:10:04
Fair enough - I knew the syntax I was just wondering if there was some case where one or the other was better.

Thanks for the input :)
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2010-07-13 : 12:18:11
Because I sometimes use STYLE I have decided to always use CONVERT, and never use CAST, so that my code is consistent.

But I don't know if that's a good policy, or not!
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2010-07-13 : 15:21:25
I'm sure I sound like broken record, but CAST is ansi compliant and CONVERT is not. Which may or may not matter to anyone. I think the only time I ever use CONVERT is to answer a question on the forums where someone has either an educational question or they have data issues.
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2010-07-14 : 02:28:11
The whole SQL standard thingie is a bit moot isn't it? Every version introduces new keywords ... are VARCHAR(MAX) and DATETIME2 compatible with any other SQL brand? (I don't know the answer, but given the weird and seemingly poorly thought-through naming conventions I had assumed not ...)

I can't see me using anything other than MS SQL, or my MS SQL code running on any other brand of SQL (even if I used CAST rather than CONVERT)!! Hmmm ... is that an MS marketing plot I wonder?

But I wholeheartedly agree that it would be an important point for anyone making cross-platform queries.
Go to Top of Page
   

- Advertisement -