Is it possible to apply the cast function to a select statement? If yes, how? I have a query that returns a number which I have to use a string to get other info's from another table.
The CAST() function converts a value (of any type) into a specified datatype.
You can cast to many SQL Server types such as binary , char , varchar , date , datetime , time , decimal , bigint , and float .
Data Type Conversions using the SQL CAST Function. For example, if we want to cast a Boolean value from the bit data type to a tiny int data type, we can do it with a valid expression such as: DECLARE @mybit BIT = 1; SELECT Test = CAST(@mybit AS TINYINT);
You just CAST()
this way
SELECT cast(yourNumber as varchar(10))
FROM yourTable
Then if you want to JOIN
based on it, you can use:
SELECT *
FROM yourTable t1
INNER JOIN yourOtherTable t2
on cast(t1.yourNumber as varchar(10)) = t2.yourString
Yes you can do.
Syntax for CAST
:
CAST ( expression AS data_type [ ( length ) ] )
For example:
CAST(MyColumn AS Varchar(10))
CAST
in SELECT
Statement:
Select CAST(MyColumn AS Varchar(10)) AS MyColumn
FROM MyTable
See for more information CAST and CONVERT (Transact-SQL)
I interpreted the question as using cast on a subquery. Yes, you can do that:
select cast((<subquery>) as <newtype>)
If you do so, then you need to be sure that the returns one row and one value. And, since it returns one value, you could put the cast in the subquery instead:
select (select cast(<val> as <newtype>) . . .)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With