2013-07-29 31 views
3

我正在嘗試更新標識值。所以如果ID是1,新的值是2,它應該用新的ID替換舊的ID。無法更新標識列'LocationID'

後端:

 public static void UpdateLocation(int locationID, SqlConnection connection,    SqlTransaction transaction) 
    { 
     StringBuilder sqlString = new StringBuilder(); 
     SqlCommand command; 

     sqlString.Append("UPDATE [Location] SET "); 
     sqlString.Append("description = @description "); 
     sqlString.Append("WHERE locationID = @locationID "); 
     command = new SqlCommand(sqlString.ToString(), connection); 
     if((transaction != null)) command.Transaction = transaction; 

     command.Parameters.Add("@locationID", SqlDbType.Int).Value = locationID; 
     command.Parameters.Add("@description", SqlDbType.VarChar).Value = description; 
     int rowsAffected = command.ExecuteNonQuery(); 

     if(!(rowsAffected == 1)) 
     { 
      throw new Exception("An error has occurred while updating UpdateMedicationDispenseStatus."); 
     } 
    } 

前端:

 private void btnFromLocation_Click(object sender, System.Windows.RoutedEventArgs e) 
    { 
     if(!((Locations)cmbLocationDescriptionList.SelectedItem == (Locations)cmbDescriptionListTo.SelectedItem)) 
     { 


      for(int i = 0; i < lstMedicationForCurrentLocation.SelectedItems.Count; i++) 
    { 
       location = (Locations)cmbDescriptionListTo.SelectedItem; 
     LocationData.UpdateLocation(location.LocationID); 

EDIT我添加了一個參數到SQL查詢,但仍犯規更新

+0

您不能(很好,不應該能夠)更改主鍵的值。如果你需要一個可改變的標識符,你應該添加一個新的表。請問爲什麼你要改變它呢? –

+0

http://stackoverflow.com/questions/751522/how-to-change-identity-column-values-programmatically – PGallagher

+0

如果它被標記爲數據庫中的標識列,爲什麼要更新它呢?如果此列有其他用途而不是唯一標識符作爲排序,請刪除標識規範。如果您只是想創建具有特定ID的新行,那麼您可以在查詢周圍打開或關閉此表的「IDENTITY_INSERT」。 – Bridge

回答

0

LocationID是自動生成的ID然後。你應該改變數據庫。你應該將身份設置爲no。

+0

看看編輯。謝謝 – Mark

6

下面的解決方法可能不是可取的,但至少從知識的角度來看,這可能對您有所幫助。

如果您想自己設置Identity列(LocationID)值,而不是讓Sql服務器執行某些解決方法。

set identity_insert Table_Name ON 

然後刪除你的行,並以不同的身份重新插入它。請注意,您仍然無法將同一行更新爲新的身份。這將允許插入語句指定標識列值。

一旦你完成了新標識值的插入,打開identity_insert關閉

set identity_insert Table_Name OFF 

既然你是編程做更新,你可以擁有所有列的值,並可能插入新行與相同的價值觀除了身份值之外的所有列都將是您的選擇。

0

您必須檢查您的SQL數據庫中是否啓用了Identity_insert,否則請在更新語句之前按照以下方式進行操作。

set identity_insert YourTable ON。 然後刪除你的行並用不同的身份重新插入它。

一旦你完成插入,不要忘記把IDENTITY_INSERT關閉

SET IDENTITY_INSERT YourTable OFF。