2014-09-11 41 views
2

SQL Server 2008的如何更新特定的列字段while循環

我的SQL表就像下面

---------------------------------------- 
**name department fee_paid id** 
---------------------------------------- 
Farooq ECE   10000  NULL 
Khan EEE   20000  NULL 
Syed Chemistry 4000  NULL 
Syed Chemistry 14000  NULL 
Yousuf Physics  2000  NULL 
Yousuf Physics  18000  NULL 
Zubair EEE   4000  NULL 
---------------------------------------- 

現在我想填寫ID字段中的數據像下面

---------------------------------------- 
**name department fee_paid id** 
---------------------------------------- 
Farooq ECE   10000  1000 
Khan EEE   20000  1001 
Syed Chemistry 4000  1002 
Syed Chemistry 14000  1003 
Yousuf Physics  2000  1004 
Yousuf Physics  18000  1005 
Zubair EEE   4000  1006 
---------------------------------------- 

我試着像下面,但它在所有的ID字段存儲相同的值..我知道,因爲我想念我在哪裏條件更新查詢below.But我如何使用條件與上面的t有條件的標準,因爲它有重複?

declare @i as int =1000 
while @i<=1006 
begin 
    update flatfile set [email protected] 
    set @i+=1 
end 
+0

我如果很感興趣那將有可能爲此使用遞歸CTE。如果這是可能的,有人可以提供一個例子。 – Dimt 2014-09-11 08:17:30

+0

但是我已經厭倦了遞歸,無法獲得獨特名稱的結果。 – Dimt 2014-09-11 08:20:16

回答

3

爲什麼不使用ALTER TABLE

alter table flatfile 
add ID int identity(1000,1) 

編輯 - 如果你想做到這一點在循環 :

declare @i as int = 1000 
while @i<=1006 
begin 
    update top(1) flatfile set [email protected] 
    where id is null; 
    set @i+=1 
end 
+0

我知道你說的方式,但我想通過更新查詢在循環條件中學習只............和我試着跟隨查詢並獲得行號,但我不知道如何分配在哪裏條件......'代碼'從平文件 – CIPHER 2014-09-11 08:23:42

+0

中選擇ROW_NUMBER()over(order by(select 0)),這裏是循環解決方案 – 2014-09-11 08:37:42

+0

U只給出了一半解決方案.....如果我的ID列有一些字段中的數據和一些領域有空意味着你的解決方案如何滿足該標準....我只是發佈一個例子在我的問題與所有NULL ...我尋找答案更新ID字段使用rownumber()或者任何另一種方式 – CIPHER 2014-09-11 09:09:03

0

將內容放置在遊標中。 在循環中,檢索遊標值並將其用於更新語句的where條件中。 假設名稱,部門和fee_paid的組合是唯一的,您將擁有唯一的ID。


3

爲了得到它可能使用Row_Number功能的ID。

窗函數沒有在更新腳本允許的,但我們可以編寫一個可更新視圖或CTE和工作與它相反:

WITH CTE AS (
    SELECT [name], [department], [fee_paid], [id] 
     , num = Row_Number() 
     OVER (ORDER BY (SELECT NULL)) + 999 
    FROM table1 
) 
UPDATE CTE SET 
    ID = num; 

SQLFiddle Demo