我正在嘗試更新標識值。所以如果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查詢,但仍犯規更新
您不能(很好,不應該能夠)更改主鍵的值。如果你需要一個可改變的標識符,你應該添加一個新的表。請問爲什麼你要改變它呢? –
http://stackoverflow.com/questions/751522/how-to-change-identity-column-values-programmatically – PGallagher
如果它被標記爲數據庫中的標識列,爲什麼要更新它呢?如果此列有其他用途而不是唯一標識符作爲排序,請刪除標識規範。如果您只是想創建具有特定ID的新行,那麼您可以在查詢周圍打開或關閉此表的「IDENTITY_INSERT」。 – Bridge