Pages

Thursday, January 28, 2010

Convert Number to Varchar in SQL Server using CAST or CONVERT or STR or Any other String Functions

Recently i started to explpore "ways" in SQL Server.
Ways in SQL Server:
===============
Implementation of NOT IN operator with out using NOT IN....
TOP 5 ways to delete Duplicate Records in a Table

In the same series today i would like to show you different ways to convert number to varchar.

Using CAST Function:
=================
SELECT CAST(YEAR(GETDATE()) AS VARCHAR)
Output:
----
2010
(1 row(s) affected)

Using CONVERT Function:
======================
SELECT CONVERT(VARCHAR(4),YEAR(GETDATE()))
Output:
----
2010
(1 row(s) affected)

Using STR String Function:
=====================
SELECT STR(YEAR(GETDATE()))
Output:
----
2010
(1 row(s) affected)

Using RTRIM or LTRIM Functions:
=============================
SELECT RTRIM(YEAR(GETDATE()))
Output:
----
2010
(1 row(s) affected)

When you apply any string functions on the numbers then by default SQL Server converts them to string data type.

Please let me know if you have any other ways.....

Related Articles:
============
String Functions in SQL Server Part 1
String Functions in SQL Server -- Final Part

1 comment:

Saravanan said...

Dear VJ,
I get into your blog while search a solution on triggers.. on seeing your blog i m admired and become a frequent visitor.. thanks a lot for helping us to improve our knowledge in SQL and .Net
-Saravanan