SQLTeam.com | Weblogs | Forums

Should I cast int to varchar?


#1

Someone asked me: When I insert an integer into a varchar column, SQL Server automatically converts it and there's no error. Should we cast it?

I thought it was good practice to cast the integer to a varchar but I couldn't come up with a good reason.

Thoughts?


#2

One basic rule: Explicit is better than implicit. For that reason alone, I cast things rather than relying on implicit conversion


#3

Another reason that explicit is better than implicit - to avoid errors such as what you will see if you run the following query:

CREATE TABLE #A( id VARCHAR(32));
INSERT INTO #A VALUES (1),('x'),(2);
DROP TABLE #A;

#4

Ahhh, good one