简体   繁体   English

SQL更新唯一键值对

[英]SQL update of unique Key-Value pair

I have a table that has a unique non-clustered constraint on two columns (let's call them key and value ) 我有一个表,该表在两列上具有唯一的非聚集约束(我们称它们为keyvalue

CREATE TABLE table (
  id varchar(50), key varchar(64) NOT NULL, value varchar(64) NOT NULL, ...
  CONSTRAINT pk_table_id PRIMARY KEY CLUSTERED (id ASC) WITH (...) ON [PRIMARY],
  CONSTRAINT pk_key_value UNIQUE NONCLUSTERED ( key ASC, value ASC) WITH (...) ON PRIMARY
) ON [PRIMARY]

Now I need to write a safe update script that updates all rows that have key='oldKey' , where safe update script means it has to be possible to be executed multiple times, without throwing an exception. 现在,我需要编写一个安全的更新脚本来更新所有具有key='oldKey' ,其中,安全的更新脚本意味着必须能够多次执行,而不会引发异常。

What I had at the beginning was: 我刚开始的时候是:

UPDATE table
SET key = 'newKey'
WHERE key = 'oldKey'

which worked at the first execution (due to the constraint). 在第一次执行时有效(由于约束)。

Let's say I have a row with key='oldKey' and value='b' , that got updated to key='newKey' and value='b' . 假设我有一个key='oldKey'value='b' ,该行已更新为key='newKey'value='b' Now two new rows are inserted, one with key='oldKey' and value='b' and the other with key='oldKey' and value='c' , and the update script is run again. 现在,将插入两行新记录,其中一行的key='oldKey'value='b' ,另一行的key='oldKey'value='c' ,并再次运行更新脚本。 Because the key is updated to 'newKey' and the key-value pair newKey, b already exists, an exception is thrown. 由于键已更新为'newKey' ,并且键值对newKey, b已存在,因此将引发异常。

What I'm trying to achieve now, is to make an update statement that updates all rows that have key='oldKey' AND no key-value pair key='newKey' value='b' already exists, otherwise do nothing. 我现在要实现的目标是,执行一条update语句来更新所有具有key='oldKey'并且不存在键值对key='newKey' value='b' ,否则不执行任何操作。

this is what I tried so far: 这是我到目前为止尝试过的:

-- 1st try, nothing is updated
IF NOT EXISTS (SELECT * FROM table WHERE key='newKey' AND value IN (SELECT value FROM table WHERE key='oldKey'))
BEGIN
  UPDATE table
  SET key = 'newKey'
  WHERE key = 'oldKey'
END

-- 2nd try, exception thrown
UPDATE table
SET key = 'newKey'
WHERE key = 'oldKey' AND
  (SELECT COUTN(*) FROM table WHERE key='newKey' AND value IN (SELECT value FROM table WHERE key='oldKey')) > 0

-- 3rd try, nothing is updated
UPDATE table
SET key = 'newKey'
WHERE NOT EXISTS (SELECT * FROM table WHERE key='newKey' AND value IN (SELECT value FROM table WHERE key='oldKey'))

Try this: 尝试这个:

UPDATE t1
SET key = 'newKey'
from table t1
WHERE key = 'oldKey'
and NOT EXISTS (SELECT * FROM table t2 WHERE t2.key='newKey' AND t1.value=t2.value)

TRY THIS : 尝试一下

UPDATE t SET key = 'newKey' 
FROM yourtable t
LEFT JOIN yourtable t1 ON t1.value = t.value
    AND t1.key = 'newKey'
WHERE t.key = 'oldKey'
    AND t1.value IS NULL

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

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