更新时Sqlite约束失败

时间:2016-04-22 08:15:23

标签: sqlite

以下查询以某种方式给出了Constraint失败错误:

/// Represent an optional value
///
/// This is needed to restrict our Observable extension to Observable that generate
/// .Next events with Optional payload
protocol OptionalType {
    associatedtype Wrapped
    var asOptional:  Wrapped? { get }
}

/// Implementation of the OptionalType protocol by the Optional type
extension Optional: OptionalType {
    var asOptional: Wrapped? { return self }
}

错误:UPDATE dimensionitems SET vitemcode = itemcode || '_' || Substr('0000' || (SELECT (SELECT Count(1) FROM dimensionitems t2 WHERE t2.itemcode = t1.itemcode AND t2.rowid <= t1.rowid) AS no FROM dimensionitems t1 WHERE t1.rowid = dimensionitems.rowid ORDER BY t1.itemcode, t1.dimvalue1, t1.dimvalue2), -4, 4)

测试1

但是,当我通过查询结果执行一个组并检查列值的重复项时,我得不到:

UNIQUE constraint failed: dimensionitems.vitemcode, dimensionitems.dimvalue1, dimensionitems.dimvalue2: UPDATE dimensionitems ...

没有结果,这意味着没有重复吗?

SELECT Count(*), v2 FROM (SELECT itemcode, dimvalue1, dimvalue2, itemcode || '_' || Substr('0000' || (SELECT (SELECT Count(1) FROM dimensionitems t2 WHERE t2.itemcode = t1.itemcode AND t2.rowid <= t1.rowid) AS no FROM dimensionitems t1 WHERE t1.rowid = dimensionitems.rowid ORDER BY t1.itemcode, t1.dimvalue1, t1.dimvalue2), -4, 4) AS v2 FROM dimensionitems) r GROUP BY dimvalue1, dimvalue2, v2 HAVING Count(*) > 1

测试2

我通过以下查询检查了是否有任何更新:

0 Rows returned from: select COUNT(*)

但这也没有产生任何结果。

可以逐个更新行Sqllite并逐个检查整数吗? 并且阻止更新它自己的行具有相同的值?

备注

  • 此约束不是主键。
  • Vitemcode本身也有一个独特的约束,它始终是唯一的
  • 此外,由于vitemcode保持不变,似乎没有任何实际更新

我的最终结果:

该表有两个约束

SELECT * 
FROM   (SELECT itemcode, 
               dimvalue1, 
               dimvalue2, 
               vitemcode, 
               itemcode 
               || '_' 
               || Substr('0000' 
                         || (SELECT (SELECT Count(1) 
                                     FROM   dimensionitems t2 
                                     WHERE  t2.itemcode = t1.itemcode 
                                            AND t2.rowid <= t1.rowid) AS no 
                             FROM   dimensionitems t1 
                             WHERE  t1.rowid = dimensionitems.rowid 
                             ORDER  BY t1.itemcode, 
                                       t1.dimvalue1, 
                                       t1.dimvalue2), -4, 4) AS v2 
        FROM   dimensionitems) r 
WHERE  vitemcode != v2 

由此我得出结论:如果vitemcode是unqiue(由于约束1而导致),vitemcode,dimvalue1和dimvalue2的组合也将始终是唯一的。

由于这个原因,我删除了第二个约束,并且它全部重新开始工作

1 个答案:

答案 0 :(得分:1)

是的,SQLite会在每行更新时检查约束。

您可以使用一些唯一的前缀或后缀更新行以防止重复,然后稍后将其删除:

UPDATE dimensionitems SET vitemcode = 'blah' || ...;
UPDATE dimensionitems SET vitemcode = substr(vitemcode, 5);