日期:2014-05-17  浏览次数:20430 次

sql问题,字符串拼接问题
表A
省代码      市代码    
1               1
2               2
6               7
11              13
现在我想在表A中加一个新的列“城市代码”
要求字段城市代码=国家代码(固定为20)+省代码(省代码为个位时补0,即省代码为1时,为01)+市代码(市代码为个位时补0,即市代码为1时,为01),得到新的表A
表A
省代码  市代码  城市代码
1           1              200101
2           2              200202
6           7              200607
11         13              201113
该怎么写语句~

------解决方案--------------------


;with cte(省代码,市代码) as
(
select 1,1
union all select 2,2
union all select 6,7
union all select 11,13
)
select *,
       '20'+case LEN(省代码) 
                 when 1 then '0'+cast(省代码 as varchar) 
                 else cast(省代码 as varchar)
            end +
    case LEN(市代码)
         when 1 then '0'+cast(市代码 as varchar)
         else cast(市代码 as varchar) 
    end as  城市代码
from cte
/*
省代码         市代码         城市代码
----------- ----------- ----------------------------------------------------------------
1           1           200101
2           2           200202
6           7      &nbs