In this article we will learn about Working with Cast and Convert Sql-server function.

Introduction

In this article, we will see how to use Cast and Convert in-built Sql Server function. The Cast and Convert functions provide similar
functionality.They are used to convert a value from one data type to
another.

They explicitly converts an expression of one data type to another. Cast and Convert provide similar functionality.

Syntax

Using CAST:

CAST(expressionAS data_type)

Using CONVERT:

CONVERT(data_type[length],expression[,style])

Where, Express :- Is any expression.Data_Type :- Is any Sql Server Data TypeLength :- Ca be any length to store value.

Objective

Working with Cast and Convert Sql-Server function.

Using the code

We can understand the Working of Cast and Convert function by an Example:-

Output:

Cast and Convert can also be used in conjunction with each other to achieve certain effects.

For instance,a typical way to produce a char variable with the current date would be to use:

Output:

We can also use Cast and Convert as

Above both query will give us the same output as:-

Cast and Convert can also be used to Format Date-Time as shown below:-

Output:

One more example of Date and Time as

Output:

We can also use Cast and Convert function as String to Numeric Conversion as: