📜  oracle sql number to varchar2 - SQL (1)

📅  最后修改于: 2023-12-03 15:03:23.953000             🧑  作者: Mango

Oracle SQL Number to Varchar2

In Oracle SQL, we can convert a number to varchar2 using the TO_CHAR function. This function is commonly used when we need to concatenate a number with a string or when we need to display a number as a string.

Syntax

The syntax for converting a number to varchar2 is as follows:

TO_CHAR(number, [format_mask], [nls_language])
  • number: The numeric value to convert to a string.
  • format_mask: Optional. A string that specifies the format of the resulting string. If not specified, the default format is used.
  • nls_language: Optional. The language to use for the conversion. If not specified, the database language is used.
Examples
Example 1: Convert a number to varchar2
SELECT TO_CHAR(123.45) AS result
FROM dual;

This will return:

RESULT
------
123.45
Example 2: Add leading zeros to a number
SELECT TO_CHAR(123, '0000') AS result
FROM dual;

This will return:

RESULT
------
0123
Example 3: Format a number with commas
SELECT TO_CHAR(1234567.89, '999,999,999.99') AS result
FROM dual;

This will return:

RESULT
------------
1,234,567.89
Example 4: Change the decimal separator
SELECT TO_CHAR(12345.67, '99999D99', 'NLS_NUMERIC_CHARACTERS='',.''') AS result
FROM dual;

This will return:

RESULT
-------
12345.67
Conclusion

In Oracle SQL, we can easily convert a number to varchar2 using the TO_CHAR function. We can also format the string in a variety of ways to meet our specific needs.