假设某列zj字段,定义长度为char,长度为8位,但是现在该字段有些记录为一位,有些为2位,即该记录的值为1,2,3,4........25......99......101.....1001这种形式,如何我把它补全为:00000001,00000002,00000025,00000026..........
00000101,00000102,............00001001,00001002这种形式。谢谢。

解决方案 »

  1.   

    update tb
    set col=right('00000000'+col,8)
      

  2.   

    update tb
    set zj = right('00000000' + cast(zj as varchar),8)
      

  3.   

    zj是char的话,要把前后的空格去掉再处理
    ---测试数据---
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([zj] char(8))
    insert [tb]
    select '1' union all
    select '2' union all
    select '3' union all
    select '4' union all
    select '25' union all
    select '99' union all
    select '101' union all
    select '1001'
     
    ---更新---
    update tb
    set zj=right('00000000'+ltrim(rtrim(zj)),8) ---查询---
    select * from tb
    ---结果---
    zj       
    -------- 
    00000001
    00000002
    00000003
    00000004
    00000025
    00000099
    00000101
    00001001(所影响的行数为 8 行)
      

  4.   

    -->我再提供一种方式:
    ---测试数据---
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([zj] char(8))
    insert [tb]
    select '1' union all
    select '2' union all
    select '3' union all
    select '4' union all
    select '25' union all
    select '99' union all
    select '101' union all
    select '1001'
     
    ---更新---
    update tb
    set zj = replicate('0',8-len(zj))+zjselect * from tb/*
    ---结果---
    zj       
    -------- 
    00000001
    00000002
    00000003
    00000004
    00000025
    00000099
    00000101
    00001001
    */
      

  5.   

    update tb set zj=right('00000000'+ltrim(rtrim(zj)),8)
      

  6.   

    -->四楼更改为:
    ---测试数据---
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([zj] char(8))
    insert [tb]
    select '1' union all
    select '2' union all
    select '3' union all
    select '4' union all
    select '25' union all
    select '99' union all
    select '101' union all
    select '1001'
     
    ---更新---
    update tb
    set zj = replicate('0',8-len(ltrim(rtrim(zj))))+zjselect * from tb/*
    ---结果---
    zj       
    -------- 
    00000001
    00000002
    00000003
    00000004
    00000025
    00000099
    00000101
    00001001
    */
      

  7.   


    --char就是麻烦,平时用惯了varchar,常常忽略空格
    ---测试数据---
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([zj] char(8))
    insert [tb]
    select '1' union all
    select '2' union all
    select '3' union all
    select '4' union all
    select '25' union all
    select '99' union all
    select '101' union all
    select '1001'
     
    ---更新---
    update tb
    set zj = replicate('0',8-len(ltrim(rtrim(zj))))+ltrim(rtrim(zj))select * from tb/*
    ---结果---
    zj       
    -------- 
    00000001
    00000002
    00000003
    00000004
    00000025
    00000099
    00000101
    00001001
    */
      

  8.   

    但以上回复的几个都能正确更新到要的数据,哪怕是char