How to Do Type Casting in SQL Server

By default, SQL Server is not strict with type casting. For example, adding a numeric value in string quotes to another numeric value with not give the usual errors other databases and programming languages will give:

select 10 + '10';

However, should the need arise, you can use either the cast() or the convert() function to force the type of a value.

-- cast float to integer
select cast(1.0123456789 as int);
select convert(int,1.0123456789);

-- cast string to date
select cast('11-02-2020' as date);
select convert(date,'11-02-2020');

-- cast string to decimal
select cast('12.345' as decimal(5,2));
select convert(decimal(15,2),'12.345');

-- cast string to time
select cast('12:45' as time);
select convert(time,'12:45');

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

database icon
Better SQL for the people
Get more done with PopSQL and SQL Server