有表table,结构如下:
AUTOID AA BB
  1 1 0
  2 1 0
  3 1 0
  4 1 0
  5 1 0
  6 1 0
  7 1 0
  8 1 0
  9 2 0
  10 2 0
  11 2 0
  12 2 0
  13 2 0
  14 3 0
  15 3 0
  16 4 0
现在需要把表中AA字段相等的值的行BB值更新为从1递增的值,更新后,表table的值如下:
AUTOID AA BB
  1 1 1
  2 1 2
  3 1 3
  4 1 4
  5 1 5
  6 1 6
  7 1 7
  8 1 8
  9 2 1
  10 2 2
  11 2 3
  12 2 4
  13 2 5
  14 3 1
  15 3 2
  16 4 1
请问SQL语句怎么写呢?顺便请教下,通过脚本把txt文件导入到数据库中,除了BCP语句外,还有啥命令?
因为我把txt导入数据库时,发现txt文件有乱码,且不能修改txt,必须把乱码也导入到数据库中

解决方案 »

  1.   


    ;with cte as(
    select rid=row_number() over (partition by AA order by AUTOID),* from table
    )
    update a set BB=b.BB from table a,cte b where a.AUTOID=b.AUTOID
      

  2.   

    create table tb(AUTOID int, AA int, BB int)insert into tb
    select 1,1,0 union all
    select 2,1,0 union all
    select 3,1,0 union all
    select 4,1,0 union all
    select 5,1,0 union all
    select 6,1,0 union all
    select 7,1,0 union all
    select 8,1,0 union all
    select 9,2,0 union all
    select 10,2,0 union all
    select 11,2,0 union all
    select 12,2,0 union all
    select 13,2,0 union all
    select 14,3,0 union all
    select 15,3,0 union all
    select 16,4,0update a set a.BB=b.NBB
    from tb a
    inner join
    (select AUTOID,
    row_number() over(partition by AA order by AUTOID) NBB
    from tb) b on a.AUTOID=b.AUTOIDselect * from tbAUTOID      AA          BB
    ----------- ----------- -----------
    1           1           1
    2           1           2
    3           1           3
    4           1           4
    5           1           5
    6           1           6
    7           1           7
    8           1           8
    9           2           1
    10          2           2
    11          2           3
    12          2           4
    13          2           5
    14          3           1
    15          3           2
    16          4           1(16 row(s) affected)
      

  3.   

    --> 还有bulk insert命令, 用法详见Google.
      

  4.   

    update
     a
    set
      bb=b.bb
    from
      tb a,
      (select px=row_number() over (partition by AA order by AUTOID),* from tb)b
    where
       a.AUTOID=b.px
      

  5.   

    UPDATE a
    SET BB=(SELECT COUNT(1) FROM TABle1 WHERE AA=a.AA AND AUTOID<=a.AUTOID)
    FROM TABle1 AS a