SQL Server CAST Usage

Hi Experts,
My sql is;
select  cast(MyTable.MyField1 as varchar(5)) from MyTable

My field is;
MyField1           5                       smallint

I wonder What is the difference between;
1) cast(MyTable.MyField1 as varchar(5))
2) cast(MyTable.MyField1 as varchar)

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

varchar(5) is varchar, limited with 5 characters length
Guy Hengel [angelIII / a3]Billing EngineerCommented:
http://msdn.microsoft.com/en-us/library/ms187928.aspxlength    Is an optional integer that specifies the length of the target data type. The default value is 30. so:2) cast(MyTable.MyField1 as varchar)would be the same as2) cast(MyTable.MyField1 as varchar(30) )
Mohit VijayCommented:
varchar(5) will allow 5 character space and only varchar will decide space at run time, best way is to use varchar(5), static allocation.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!


a smallint can be anyting between -2^15 (-32,768) to 2^15-1 (32,767). So you'd better use varchar(6)! ;-)

SELECT cast(-32768 as varchar(5))

SELECT cast(-32768 as varchar(6))


kosturdurAuthor Commented:
3 helpfull comments so 3 answers made me increase the points
kosturdurAuthor Commented:
Thanks all
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.