2016-10-16 144 views
0

美好的一天,我試圖更新我的表。因爲我的網站有錯誤。首先請檢查我的桌子。 (Penilaian_Header)更新多行SQL Server 2008

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 

謝謝,對不起我的英語不好。

回答

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

+0

其工作表示感謝。只需要移除'pen'(別名) – YVS1102

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 )