如何将编码字符串转化为名称字符串
例如 我要将 'a1,b2,c3' 这组编码代表的编码转化为'药品1,药品2,药品3'
数据库结构如下:
bm mc
a1 药品1
b2 药品2
c3 药品
[最优解释]
SELECT @str=REPLACE(','+@str+',',','+bm+',',mc) FROM TB t
这样就可以了
[其他解释]
--> 测试数据:[TB]
if object_id('[TB]') is not null drop table [TB]
GO
create table [TB]([bm] varchar(2),[mc] varchar(5))
insert [TB]
select 'a1','药品1' union all
select 'b2','药品2' union all
select 'c3','药品'
DECLARE @str VARCHAR(200)
SET @str= 'a1,b2,c3'
SELECT @str=REPLACE(@str,bm,mc) FROM TB t
SELECT @str
drop table [TB]
[其他解释]
create table xv(bm varchar(10),mc varchar(10))
insert into xv(bm,mc)
select 'a1', '药品1' union all
select 'b2', '药品2' union all
select 'c3', '药品3'
declare @x varchar(20)
select @x='a1,b2,c3'
select stuff(
(select ','+d.mc
from
(select substring(a.x,b.number,charindex(',',a.x+',',b.number)-b.number) 'x'
from (select @x x) a,master.dbo.spt_values b
where b.type='P' and b.number between 1 and len(a.x)
and substring(','+a.x,b.number,1) = ',') c
inner join xv d on c.x=d.bm
for xml path('')),1,1,'') 'y'
/*
y
-------------------------
药品1,药品2,药品3
(1 row(s) affected)
*/
[其他解释]
我用的sqlserver 2000
[其他解释]
方法2,
create table xv(bm varchar(10),mc varchar(10))
insert into xv(bm,mc)
select 'a1', '药品1' union all
select 'b2', '药品2' union all
select 'c3', '药品3'
declare @x varchar(20),@sql varchar(6000)
select @x='a1,b2,c3'
select @sql='replace('+isnull(@sql,''''+@x+'''')+','''+bm+''','''+mc+''')'
from xv
select @sql='select '+@sql+ ' ''y'''
exec(@sql)
/*
y
-------------------------
药品1,药品2,药品3
(1 row(s) affected)
*/
[其他解释]
这种方法有个问题如果编码 有 10,100,101这样的数字的数据就不准确了