Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading