Cast int to varchar(将 int 转换为 varchar)
问题描述
我有以下查询,需要将 id 转换为 varchar
I have below query and need to cast id to varchar
架构
create table t9 (id int, name varchar (55));
insert into t9( id, name)values(2, 'bob');
我尝试了什么
select CAST(id as VARCHAR(50)) as col1 from t9;
select CONVERT(VARCHAR(50),id) as colI1 from t9;
但它们不起作用.请提出建议.
but they don't work. Please suggest.
推荐答案
您需要cast 或 convert 作为 CHAR 数据类型,没有可以将数据转换/转换为的 varchar 数据类型:
You will need to cast or convert as a CHAR datatype, there is no varchar datatype that you can cast/convert data to:
select CAST(id as CHAR(50)) as col1
from t9;
select CONVERT(id, CHAR(50)) as colI1
from t9;
在 SQL Fiddle 上查看以下 SQL — 实际操作:
See the following SQL — in action — over at SQL Fiddle:
/*! Build Schema */
create table t9 (id INT, name VARCHAR(55));
insert into t9 (id, name) values (2, 'bob');
/*! SQL Queries */
select CAST(id as CHAR(50)) as col1 from t9;
select CONVERT(id, CHAR(50)) as colI1 from t9;
除了您尝试转换为不正确的数据类型这一事实之外,您用于 convert 的语法也不正确.convert 函数使用以下内容,其中 expr 是您的列或值:
Besides the fact that you were trying to convert to an incorrect datatype, the syntax that you were using for convert was incorrect. The convert function uses the following where expr is your column or value:
CONVERT(expr,type)
或
CONVERT(expr USING transcoding_name)
您的原始查询的语法向后.
Your original query had the syntax backwards.
这篇关于将 int 转换为 varchar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 int 转换为 varchar
基础教程推荐
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 在多列上分布任意行 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
