Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CAST and CONVERT in T-SQL

Is it posible to CAST or CONVERT with string data type (method that takes data type parametar as string), something like:

CAST('11' AS 'int') 

but not

CAST('11' AS int)
like image 823
mcorluka Avatar asked Dec 04 '25 03:12

mcorluka


2 Answers

No. There are many places in T-SQL where it wants, specifically, a name given to it - not a string, nor a variable containing a name.

like image 183
Damien_The_Unbeliever Avatar answered Dec 06 '25 16:12

Damien_The_Unbeliever


If you want to use dynamic sql, this should get you started:

DECLARE @datatype varchar(20)
DECLARE @sql varchar(4000)

SELECT @datatype = 'int'

SELECT @sql = 'PRINT CAST(''11'' AS '+@datatype+')'

exec (@sql)

Depending on what you exactly want/need you should read The Curse and Blessings of Dynamic SQL, especially the parts about sp_executesql

like image 25
Ocaso Protal Avatar answered Dec 06 '25 15:12

Ocaso Protal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!