简单的类型转换

songguozhi 2010-09-19 01:07:27
我希望将int类型的一个值 转换成varchar(4)类型的字符串

如1转换为'0001'
23转为'0023'
123转为'0123'
1234转为'1234'

也就是说前面的0是自动补齐,保证字符串长度为4位的

哪位帮帮
...全文
115 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
abuying 2010-09-21
  • 打赏
  • 举报
回复
declare @id int
set @id = 1

select right(10000+@id,4)
cxmcxm 2010-09-19
  • 打赏
  • 举报
回复
转为字符串后前面补‘000’再右截4位
boqiang1988 2010-09-19
  • 打赏
  • 举报
回复
declare @id int;
set @id=123;
print right('0000'+cast(@id as varchar(10)),4);

上述代码输出为0123
Rotel-刘志东 2010-09-19
  • 打赏
  • 举报
回复
declare @id int
set @id = 1
select right(10000+@id,4)
baiying15 2010-09-19
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 liangck 的回复:]
declare @id int
set @id = 1

select right(10000+@id,4)
[/Quote]

这个方法很有效。。。我觉得是针对这种问题最有效的方法了。
brownhwy 2010-09-19
  • 打赏
  • 举报
回复
2楼的把5改成4结果是正确的。
select * ,code=right('000'+cast(id as varchar),4)

yhtapmys 2010-09-19
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 liangck 的回复:]
declare @id int
set @id = 1

select right(10000+@id,4)
[/Quote]

+1
brownhwy 2010-09-19
  • 打赏
  • 举报
回复
1楼的结果是正确的,2楼的结果不正确。如果12的话转换成00012了。
HSBOY86 2010-09-19
  • 打赏
  • 举报
回复
right('0000'+cast(id as varchar),4)
Olive_Guo 2010-09-19
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 liangck 的回复:]
declare @id int
set @id = 1

select right(10000+@id,4)
[/Quote]

好厉害,学习喽
王向飞 2010-09-19
  • 打赏
  • 举报
回复
create table tb
(id int identity,
name varchar(10),
code int)
go
insert tb(name) select 'A'
union all select 'B'
union all select 'C'
union all select 'D'

select * ,code=right('000'+cast(id as varchar),5)
from tb

drop table tb


---
id name code code
1 A NULL 0001
2 B NULL 0002
3 C NULL 0003
4 D NULL 0004
liangCK 2010-09-19
  • 打赏
  • 举报
回复
declare @id int
set @id = 1

select right(10000+@id,4)

34,571

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧