更新多行SQL Server 2008

时间:2016-10-16 11:10:58

标签: sql-server sql-server-2008

美好的一天,我正在尝试更新我的桌子。因为我的网站有错误。首先请检查我的表。 (Penilaian_Header)

IdPenilaian | KodePenilaian       |   Nip  | PositionCode | Total
    1613           -----             1603405    P028          0 
    1618           -----             1602999    P028          0 
    1641          PE0001568           603060    P040         35
    1640          PE0001567          1411862    P007         35
你可以看到

有两行KodePenilaian为空。那么有没有机会填补它?所以结果就是这样。

IdPenilaian | KodePenilaian       |   Nip  | PositionCode | Total
    1613          PE0001570         1603405     P028          0 
    1618          PE0001569         1602999     P028          0 
    1641          PE0001568           603060    P040         35
    1640          PE0001567          1411862    P007         35

这是我如何生成KodePenilaian

select case 
    when right(max(KodePenilaian),7) is null then 'PE0000001' 
    else ('PE' + RIGHT('0000000' + cast(right(max(KodePenilaian),7) + 1 as nvarchar),7)) 
    end KodePenilaian from Penilaian_Header

这是我运行时的结果

KodePenilaian
  PE0001569

谢谢,抱歉我的英语不好。

2 个答案:

答案 0 :(得分:1)

并不真正习惯sql server 2008 尝试这样的事情:

update Penilaian_Header pen 
   set pen.KodePenilaian = 
             (select case 
                     when right(max(newKode.KodePenilaian),7) is null then 'PE0000001' 
                     else ('PE' + RIGHT('0000000' + cast(right(max(newKode.KodePenilaian),7) + 1 as nvarchar),7)) 
                     end KodePenilaian
                from Penilaian_Header newKode)
 where pen.KodePenilain = NULL

如果您的表格中-----NULL

答案 1 :(得分:0)

你可以这样试试......

;WITH cte
AS (SELECT *,
  MAX(CONVERT(int, REPLACE(KodePenilaian, 'PE000', ''))) OVER () AS MaxNum,
  ROW_NUMBER() OVER (ORDER BY kodePenilaian) AS rn
FROM YourTable)
UPDATE cte SET KodePenilaian = concat('PE000', maxnum + rn)
    WHERE KodePenilaian IS NULL

你的桌子

create table YourTable (
IdPenilaian int, KodePenilaian varchar(20),  Nip  int, PositionCode varchar(10), Total INT)

insert into YourTable
(IdPenilaian , KodePenilaian       ,   Nip  , PositionCode , Total) values
   (  1613      ,     NULL         ,      1603405   ,'P028',          0  )
  ,(  1618      ,     NULL         ,      1602999   ,'P028',          0  )
  ,(  1641      ,    'PE0001568'   ,       603060   ,'P040',         35  )
  ,(  1640      ,    'PE0001567'   ,      1411862   ,'P007',         35  )