2012-05-24 44 views
-1

我有在MS SQL服務器(TSQL)更新的問題
假設我有一個表描述ID字段和插入1000條記錄此表與此值更新許多records.should我使用光標?

1  Descript1 
    2  Descript2 
    3  Descript3 
    ..  ...... 
    ..  ...... 
    1000 Descript1000 

我怎樣才能改變這個1000條記錄下同記錄

1 Description1 
2 Description2 
3  Description3 
...... 
...... 
1000  Description1000 

我應該使用光標? 我寫此查詢,但它不工作

while @Counter<=1000000 
     begin 
      update Person set Description='Descripton'+CONVERT(nvarchar(15),@Counter) where ID>=1 
    set @[email protected]+1 
     end 
+0

運行在基於集時尚查詢是_much_比逐行更快(如while循環,遊標等)。 – Bridge

回答

2

沒有cursor需要的,只是一個簡單的update

update Person 
set Description = "Description" + convert(varchar(10), ID) 
+0

非常感謝您的回答[aF](http://stackoverflow.com/users/187730/af) –

+1

@SalahSanjabian如果它有效,您應該接受以下答案:http://meta.stackexchange.com/questions/ 5234/how-does-accepting-an-answer-work –

+0

'convert(varchar' without length?I do not recommend it。http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/09/bad -habits-to-kick-declaring-varchar-without-length.aspx –

1
UPDATE Person 
SET  Discription = SPACE(Z.n)+ Z.Discription 
FROM ( SELECT ID, 
       Description , 
       ROW_NUMBER() OVER (ORDER BY ID)n 
     FROM Person 
    )Z 
+0

感謝您的回答[mehdi lotfi](http://stackoverflow.com/users/1407421/ mehdi-lotfi)(mamnon agha mehdi) –