Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql how to cast a select query

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.

like image 944
Rocshy Avatar asked Aug 16 '12 14:08

Rocshy


People also ask

What is cast in SQL query?

The CAST() function converts a value (of any type) into a specified datatype.

Can you type cast in SQL?

You can cast to many SQL Server types such as binary , char , varchar , date , datetime , time , decimal , bigint , and float .

How do I cast a bit in SQL?

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);


3 Answers

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
like image 130
Taryn Avatar answered Oct 18 '22 16:10

Taryn


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)

like image 29
Himanshu Jansari Avatar answered Oct 18 '22 17:10

Himanshu Jansari


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>) . . .)
like image 25
Gordon Linoff Avatar answered Oct 18 '22 16:10

Gordon Linoff