cCode cName2 cFather iLevel cCatCode
1 Assets NULL 1 NULL
11 Current assets 1 2 NULL
1101 Cash on Hand 11 3 12012
110101 Cash on Hand 1101 4 **NULL**
110102 NULL 1101 4 **NULL**
110103 cashier 1101 4 **NULL**
110104 Cash on Hand 1101 4 **NULL**
我想更新cCatCode
的值cFather = 'cCode'
。
将cCatcode
12012
复制到110101,110102,110103,110104等所有附属帐户
cCode cName2 cFather iLevel cCatCode
1 Assets NULL 1 NULL
11 Current assets 1 2 NULL
1101 Cash on Hand 11 3 12012
110101 Cash on Hand 1101 4 12012
110102 NULL 1101 4 12012
110103 cashier 1101 4 12012
110104 Cash on Hand 1101 4 12012
我运行此但它无效
update chart set cCatCode = ccatcode where cfather = ccode
答案 0 :(得分:1)
对于 SQL Server:
update c1
set c1.cCatCode=c2.cCatCode
from chart c1 join
chart c2 on c1.cFather LIKE CAST(c2.cfather as varchar(max))+'%' and c1.cCode<>c2.cCode
where c1.cCatCode IS NULL and c2.cCatCode IS NOT NULL
SQL Server的 对于 MySQL:
update chart c1 join
chart c2 on c1.cFather LIKE CONCAT(c2.cfather,'%') and c1.cCode<>c2.cCode
set c1.cCatCode=c2.cCatCode
where c1.cCatCode IS NULL and c2.cCatCode IS NOT NULL
MySQL的 结果:
cCode cName2 cFather iLevel cCatCode
------------------------------------------------
1 Assets (null) 1 (null)
11 Current assets 1 2 (null)
1101 Cash on Hand 11 3 12012
110101 Cash on Hand 1101 4 12012
110102 (null) 1101 4 12012
110103 cashier 1101 4 12012
110104 Cash on Hand 1101 4 12012
答案 1 :(得分:0)
一种方法(应该适用于所有数据库)使用相关子查询。对于您的特定数据,这个(或类似的东西)将适用于大多数数据库:
update chart
set cCatCode = (select c2.cCatCode
from chart c2
where c2.cCode = chart.Father
)
where cCatCode is NULL;
答案 2 :(得分:0)
以下是在同一桌面上进行更新的最佳方式。
SET SQL_SAFE_UPDATES=0;
UPDATE chart SET cCatCode = (SELECT cCatCode FROM chart WHERE cFather = cCode AND cCatCode IS NOT NULL) WHERE cCatCode IS NULL;
SET SQL_SAFE_UPDATES=1;