做一个克隆功能, 复制一份记录及其子记录, 除了主键和相关外键换一下, 其它不变。
表面上看起来简单, 但不用循环就要稍多花点心思了。
写一个类似的例子, 以后备用, 也算是造福人类吧。
IF OBJECT_ID('A') IS NOT NULL DROP TABLE A GO IF OBJECT_ID('B') IS NOT NULL DROP TABLE B GO IF OBJECT_ID('C') IS NOT NULL DROP TABLE C GO CREATE TABLE A( Aid INT PRIMARY KEY, Aname NVARCHAR(10) ) GO CREATE TABLE B( Bid INT PRIMARY KEY, Aid INT, Bname NVARCHAR(10) ) GO CREATE TABLE C( Cid INT PRIMARY KEY, Bid INT, Cname NVARCHAR(10) ) GO SET NOCOUNT ON INSERT INTO A(Aid,Aname) VALUES(1,'王大爷') INSERT INTO B(Bid,Aid,Bname) VALUES(10,1,'大儿') INSERT INTO B(Bid,Aid,Bname) VALUES(11,1,'二儿') INSERT INTO C(Cid,Bid,Cname) VALUES(100,10,'大儿儿') INSERT INTO C(Cid,Bid,Cname) VALUES(101,10,'大儿二儿') INSERT INTO C(Cid,Bid,Cname) VALUES(110,11,'二儿儿') INSERT INTO C(Cid,Bid,Cname) VALUES(111,11,'二儿二儿') INSERT INTO C(Cid,Bid,Cname) VALUES(112,11,'二儿三儿') SELECT * FROM A SELECT * FROM B SELECT * FROM C /* Aid Aname ----------- ---------- 1 王大爷 Bid Aid Bname ----------- ----------- ---------- 10 1 大儿 11 1 二儿 Cid Bid Cname ----------- ----------- ---------- 100 10 大儿儿 101 10 大儿二儿 110 11 二儿儿 111 11 二儿二儿 112 11 二儿三儿 */ --根据王大爷的记录复制出一份“王二爷”的记录及相关子记录, 子记录除了主键及外键不同之外,其它全部相同 --1. 王二爷 INSERT INTO A(Aid,Aname) VALUES(2,'王二爷') --2. 王二爷子辈 DECLARE @b TABLE( Bid INT, Aid INT, Bname NVARCHAR(10), oldBid INT ) INSERT INTO @b(Bid,Aid,Bname,oldBid) SELECT ROW_NUMBER() OVER (ORDER BY bid)+(SELECT MAX(bid) FROM B) AS bid ,2 AS aid ,Bname ,Bid FROM B WHERE aid=1 INSERT INTO B(Bid,Aid,Bname) SELECT Bid,Aid,Bname FROM @b --3. 王二爷孙辈 INSERT INTO C(Cid,Bid,Cname) SELECT ROW_NUMBER() OVER (ORDER BY cid)+(SELECT MAX(cid) FROM c) AS cid , b2.Bid , c2.Cname FROM C c2 INNER JOIN @b b2 ON c2.bid=b2.oldBid SELECT * FROM A SELECT * FROM B SELECT * FROM C DROP TABLE A DROP TABLE B DROP TABLE C /* Aid Aname ----------- ---------- 1 王大爷 2 王二爷 Bid Aid Bname ----------- ----------- ---------- 10 1 大儿 11 1 二儿 12 2 大儿 13 2 二儿 Cid Bid Cname ----------- ----------- ---------- 100 10 大儿儿 101 10 大儿二儿 110 11 二儿儿 111 11 二儿二儿 112 11 二儿三儿 113 12 大儿儿 114 12 大儿二儿 115 13 二儿儿 116 13 二儿二儿 117 13 二儿三儿 */
时间: 2024-10-14 20:44:14