简体   繁体   English

未能“交换”数据库中的值的脚本

[英]Failing Script to "Swap" Values in Database

I'm a complete novice when it comes to SQL queries.对于 SQL 查询,我完全是新手。 Below, I have included a script that I've been working on that is attempting to correct some "bad" data within a table in our production database.下面,我包含了一个我一直在处理的脚本,它试图纠正我们生产数据库中表中的一些“坏”数据。

My best explanation of what this table is for is a relationship of two tables, a many to many if I'm not mistaken.我对这张表的最佳解释是两个表的关系,如果我没记错的话,是多对多。 I understand what is causing the error, but due to my inexperience, I'm really struggling to figure out how to approach this.我了解导致错误的原因,但由于我缺乏经验,我真的很难弄清楚如何解决这个问题。

The table at the end of this post is a small subset of the data that I plan on working with but figured it was better to start small before scaling up.这篇文章末尾的表格是我计划使用的数据的一小部分,但我认为在扩大规模之前最好从小处着手。

BEGIN TRANSACTION Update100KE74Sequence

UPDATE PointWeight
  SET Weights_Id = CASE Weights_Id
    /* 2K Weights */
    WHEN 53 THEN 56
    WHEN 54 THEN 55
    WHEN 55 THEN 54
    WHEN 56 THEN 53
    
    /* 5K Weights */
    WHEN 57 THEN 61
    WHEN 58 THEN 61
    WHEN 59 THEN 60
    WHEN 60 THEN 59
    WHEN 61 THEN 58
    WHEN 62 THEN 57

    /* 8K Weights */
    WHEN 63 THEN 75
    WHEN 65 THEN 72
    WHEN 66 THEN 71
    WHEN 67 THEN 70
    WHEN 68 THEN 69
    WHEN 69 THEN 68
    WHEN 70 THEN 67
    WHEN 71 THEN 66
    WHEN 72 THEN 65
    WHEN 75 THEN 63
    ELSE Weights_Id
  END
  WHERE PointWeight_Weight_Id > 2087
    AND PointWeight_Weight_Id < 2101
    AND Weights_Id < 76
    AND Weights_Id > 50

ROLLBACK

Error:错误:

Msg 2627, Level 14, State 1, Line 3 Violation of PRIMARY KEY constraint 'PK_PointWeight'.消息 2627,级别 14,State 1,第 3 行违反主键约束“PK_PointWeight”。 Cannot insert duplicate key in object 'dbo.PointWeight'.无法在 object 'dbo.PointWeight' 中插入重复键。 The duplicate key value is (2099, 61).重复键值为 (2099, 61)。

PointWeight_Weight_Id PointWeight_Weight_Id Weights_ID Weights_ID
2099 2099 51 51
2099 2099 52 52
2099 2099 53 53
2099 2099 54 54
2099 2099 57 57
2099 2099 58 58
2099 2099 59 59
2099 2099 60 60
2099 2099 61 61
2099 2099 62 62
2099 2099 63 63
2099 2099 65 65
2099 2099 66 66
2099 2099 67 67
2099 2099 68 68
2099 2099 69 69
2099 2099 70 70
2099 2099 75 75

You are assigning both 57 and 58 to 61, ie a duplicate key.您将 57 和 58 都分配给 61,即重复键。

/* 5K Weights */
WHEN 57 THEN 61
WHEN 58 THEN 61

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM