MS SQL:仅在数据记录不存在时更新

时间:2016-03-20 14:47:03

标签: sql-server conditional

我有一个包含以下列的MSSQL表:

ID (int, unique), Name (varchar), Hobby (varchar)

" Hobby"列允许NULL值。 该表包含这些数据集(作为示例):

1, "John Doe", null
2, "Jack Doe", "racing"
3, "Mary Doe", "running"
4, "Mike Doe", null
5, "Mike Doe", "skiing"

我现在想要做以下事情: 将空值替换为" chilling"在" Hobby"没有另一个数据行的列没有null。 在伪代码中,我想这样做:

UPDATE table SET Hobby = "chilling" WHERE Hobby is null and <nobody with the same name has a hobby already>

这意味着数据行1应该受到影响,但数据行5不应该是(以避免重复)。

我和我的同事已经考虑过这个问题很长一段时间了,但找不到解决办法。

如何创建执行我想要实现的SQL语句?

2 个答案:

答案 0 :(得分:0)

试试这个:

UPDATE t1
SET Hobby = "chilling" 
FROM table t1
WHERE Hobby IS NULL
AND NOT EXISTS(
    SELECT 1
    FROM Table t2
    WHERE t2.Name = t1.Name
    AND t2.Hobby IS NOT NULL
)

更新

UPDATE tablename t1
SET Hobby = 'chilling' 
FROM t1
WHERE Hobby IS NULL
AND NOT EXISTS(
    SELECT 1
    FROM tablename t2
    WHERE t2.Name = t1.Name
)

答案 1 :(得分:0)

Zohar的回答是有效的,除了代码中的一些拼写错误:

UPDATE tablename t1
SET Hobby = 'chilling' 
FROM t1
WHERE Hobby IS NULL
AND NOT EXISTS(
    SELECT 1
    FROM tablename t2
    WHERE t2.Name = t1.Name
    AND t2.Hobby IS NOT NULL
)