如何实现'A' + 1 = 'B'

nipzj 2012-05-24 11:29:47
现在有一个表 如:
id score
1 50
2 50
3 50

我如何用把字母1处改为1A,2处改为2B,把3改为3C

我的方法是

DECLARE @temp_char VARCHAR(10),@temp_int int //设置临时变量

SELECT @temp_char = 'A'

为什么下面这里就报错呢 说不能转换
SELECT @temp_int = convert(INT, @temp_char)
SELECT @temp_int = @temp_int + 1
SELECT @temp_char = convert(VARCHAR(10), @temp_int)
...全文
128 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复

select ascii('A')
--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
create table [test]([id] int,[score] int)
insert [test]
select 1,50 union all
select 2,50 union all
select 3,50

select LTRIM([id])+CHAR(64+id) as id,[score] from test

/*
id score
1A 50
2B 50
3C 50
*/
nipzj 2012-05-24
  • 打赏
  • 举报
回复
求大神 帮忙比较急 谢谢
nipzj 2012-05-24
  • 打赏
  • 举报
回复
不太明白,我的意思是最后变成
ID SCORE
1A 50
2B 50
3C 50
这个样子
AcHerat 元老 2012-05-24
  • 打赏
  • 举报
回复

create table tb(id int,score int)
insert into tb
select 1,10 union all
select 2,34
go

select *,char(ascii('A')+(id-1)%26) as word
from tb

drop table tb

/****************

id score word
----------- ----------- ----
1 10 A
2 34 B

(2 行受影响)

AcHerat 元老 2012-05-24
  • 打赏
  • 举报
回复
你那样转换是有问题的,去建一个临时表,结构如下

id -- wordid

1 ----- A
2 ----- B
....
26----- Z

你的表id字段确定是字母么,或者别更新直接查询吧!

select a.*,ltrim(a.id)+b.wordid
from a join b on a.id%26 = b.id
nipzj 2012-05-24
  • 打赏
  • 举报
回复
嗯 一直对应到Z 但是还没做到那一步 这里类型转换怎么总是说不对呢
AcHerat 元老 2012-05-24
  • 打赏
  • 举报
回复
100 怎么表示
AcHerat 元老 2012-05-24
  • 打赏
  • 举报
回复
一直对应到 26 Z ???
nipzj 2012-05-24
  • 打赏
  • 举报
回复
SELECT @temp_int = ascii(@temp_char)
SELECT @temp_int = @temp_int + 1
SELECT @temp_char = CHAR(@temp_int)
这样就可以 结合 游标
叶子 2012-05-24
  • 打赏
  • 举报
回复

--SQL SERVER 里面是没有问题的
--ltrim是去掉左空格,这里是将int 隐式转换成 varchar
declare @T table([id] int,[score] int)
insert @T
select 1,50 union all
select 2,50 union all
select 3,50

select ltrim(id)+char(id+64) as id,[score] from @T
/*
id score
------------- -----------
1A 50
2B 50
3C 50
*/
叶子 2012-05-24
  • 打赏
  • 举报
回复
楼主用的是什么数据库?是SQL SERVER吗?哪个版本?还是access?
nipzj 2012-05-24
  • 打赏
  • 举报
回复
最后一句什么意思

select LTRIM([id])+CHAR(64+id) as id,[score] from test

报错

34,590

社区成员

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

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