Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tsql : best way to cast variables to string type?

I wrote a tsql procedure which inserts a string into a text file which means it requires all variables be converted to a string. Instead of using a case by case statement, is there an easier to do this which encompasses all cases and forces whatever type to a string type?

thanks in advance

like image 537
phill Avatar asked Aug 12 '09 21:08

phill


People also ask

How do I cast a variable in SQL Server?

Cast() Function in SQL Server The Cast() function is used to convert a data type variable or data from one data type to another data type. The Cast() function provides a data type to a dynamic parameter (?) or a NULL value. The data type to which you are casting an expression is the target type.

Which is better cast or convert in SQL?

CAST is also less powerful and less flexible than CONVERT. On the other hand, CONVERT allows more flexibility and is the preferred function to use for data, time values, traditional numbers, and money signifiers. CONVERT is also useful in formatting the data's format.


1 Answers

All-caps is literal text, lower-case is something into which you should interpolate a value:

CAST(expression AS CHAR)
-- or:
CAST(expression AS VARCHAR)

You can optionally specify a length.

Unfortunately, it's a bit harder with datetimes, if you want to format it in any way that's different from the default representation.

My info came from the MSDN site. I think you'll have to read that site, and others, carefully and play around with it a bit, but hopefully the CAST function will be a good start.

Good luck!

like image 182
Platinum Azure Avatar answered Oct 28 '22 15:10

Platinum Azure