What are your opinions on converting INT (and indeed anything else like GUIDs) to VARCHAR?
For INTs I see the following used
SELECT MyINT,
']'+CAST(MyINT as varchar(20))+'[' AS [Cast],
']'+CONVERT(varchar(20),MyINT)+'[' AS [Convert()],
']'+STR(MyINT,20)+'[' AS [Str()],
']'+LTRIM(STR(MyINT,20))+'[' AS [LTrim(Str())]
FROM
(
SELECT CONVERT(bigint, 1) AS [MyINT] UNION ALL
SELECT 12345 UNION ALL
SELECT 2147483647 UNION ALL -- Max INT
SELECT 9223372036854775807 -- Max BigINT
) AS T
I use VARCHAR(20) as being a round number that I can remember, and big enough for any of these, but I typically see CONVERT(varchar(5), MyINT) which to my mind is potentially hiding a future-failure when MyINT ticks over from 99,999 to 100,000. I also see CONVERT(varchar, MyINT) or CAST(MyINT as varchar) which I dislike as default sizing for varchar can be either 30 or 1 For me the default of varchar(30) is unnecessarily wide - e.g. if the CONVERT is in a SELECT and the receiving APP decides on a column width based on the size of the column, rather than the widest value it contains. CONVERT(varchar(20), MyINT) may be far too wide for many numbers - I don't think I have ever hit the maximum value for a BigInt! - but it does at least fail safe.
I see LTrim(Str(MyINT)) used but I've never used that style. It is safe up to the max value for INT, but not for BigInt (without adding a without a length parameter). Just seems to me to be hard to generate a left-side-padded string which is them left-trimmed (and there might also be a "cost" to the implicit conversion of INT to FLOAT before str() converts it to string?)
GUID only needs 36 characters (or perhaps allow 38 for surrounding "{...}" which sometimes come into my APP for the ADO layer), but I convert using 40 because its a round number that I can easily/safely remember.
SELECT MyGUID,
']'+CAST(MyGUID as varchar(40))+'[' AS [Cast],
']'+CONVERT(varchar(40),MyGUID)+'[' AS [Convert()]
FROM
(
SELECT NewID() AS [MyGUID]
) AS T
I'd appreciate your thoughts on how you do this, what GotChas you encounter and what you consider to be Best Practice.