SQL Server Convert() function – An Ultimate Guide!

Filed Under: SQL Server
SQL SERVER CONVERT() FUNCTION

Hey, all! In this article, we will be focusing on SQL Server Convert() function in detail.

SQL Server offers us various functions to deal and manipulate with different types of data values. One such function is Convert() function.

So, let us get started!


What is SQL Server Convert() function?

SQL Convert() function enables us to alter and deal with data values of different data types in an efficient manner.

The convert() function converts the data value to the particular data type passed to it as a parameter. Thus, we can say that the Convert() function acts as a value converter. It converts the passed or specified value to the specified data type respectively.

Having understood the working of Convert() function, let us now focus on the structure of the same.


Syntax of SQL CONVERT() function

The CONVERT() function accepts these mandatory parameters:

  • The data type to which the passed value is to be manipulated
  • The data value to be converted

Syntax–

Convert(data type, expression)

SQL Server Convert() function can be used to convert the data values into different data types such as

  • int
  • float
  • varchar
  • datetime
  • numeric
  • decimal, etc.

Now, let us implement the function through the below examples.


Examples of Convert() function

We use the convert() function along with the SELECT statement to display our results onscreen.

In the below example, we have converted a decimal value to an integer value:

SELECT CONVERT(INT, 25400.2543);

So, here the decimal portion i.e. the portion after the decimal point gets truncated.

Output:

25400

Now, we have used the convert() function to convert, the string value into the value of a DateTime type expression.

SELECT CONVERT(datetime, '2020-07-27');

As seen above, the convert() function converts the string ‘2020-07-27’ into datetime value.

Output:

2020-07-27T00:00:00.000Z

In this example, we have converted the float value to a string value using the data type as varchar.

SELECT CONVERT(varchar, 235.1246);

Output:

'235.1246'

Conclusion

By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.

For more such posts related to SQL Server, do visit SQL Server JournalDev.

Till then, Happy Learning!!


References

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages