In the SQL, the integer is converted to a string (varchar)Many applications need to convert the integer data type into string, especially Varchar type. This article will introduce several methods to convert int to Varchar in SQL.
What is the problem?
A user attempts to perform the following queries to convert the int to Varchar:
These queries cause errors.What is the solution?
<code class="language-sql">select CAST(id as VARCHAR(50)) as col1 from t9; select CONVERT(VARCHAR(50),id) as colI1 from t9;</code>Copy after loginTo convert the int to Varchar, we need to use the Char data type instead of the Varchar data type. The following inquiries will be effective:
Why is the solution effective? CHAR data type is a string data type with a fixed length, and Varchar is a variable -length string data type. When we convert the int to Char, the int will convert it to a string of specified length, and any remaining characters will be filled with a space.
On the other hand, the varchar data type is a variable -length string data type, which means that the length of the string can be changed. When we convert the int to Varchar, the int will convert it to a string, and the length of the string is determined by the length of the int.
Additional description<code class="language-sql">select CAST(id as CHAR(50)) as col1 from t9; select CONVERT(id, CHAR(50)) as colI1 from t9;</code>Copy after loginWhen using the CAST function, the grammar is as follows:
Among them, EXPR is an expression to be converted, and data_type is a data type to be converted.
When using the Convert function, the grammar is as follows:
or
Among them, EXPR is an expression to be converted, data_type is a data type to be converted, and transcoding_name is the name of the conversion method.
The above is the detailed content of How to Correctly Cast an Integer to a String (varchar) in SQL?. For more information, please follow other related articles on the PHP Chinese website!