Cast a column as the type of another column

I need to cast column_A as the type of column_B.
So if column_B is varchar then column_A should be varchr.
If column_B is int then column_A should be int.
Thanks in advance for any help.

>Solution :

You can check column_b datatype from system tables and you can use it accordingly

declare @datatype Varchar(50)

select @datatype = DATA_TYPE from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'table1'
and COLUMN_NAME = 'column_b'

declare @sql varchar(max)
set @sql = 'select cast(column_a as '+@datatype+'), column_b from table1'
exec(@sql)

Leave a Reply