我是新的存储过程并尝试编写过程以将用户(通过user_id)主详细信息数据复制到新的用户数据中。这是我的表格结构。我将目标user_id和目标user_id传递给存储过程。你能告诉我如何实现这个功能吗?我感谢任何帮助。
TABLE A
----------------
a_id int(Primary Key)
desc varchar(50)
user_id int
TABLE B
-----------------
b_id int(Primary Key)
a_id int(Foreign Key)
detail varchar(100)
CREATE PROCEDURE [duplicate_user_data]
@old_user_id int,
@new_user_id int
AS
BEGIN
INSERT INTO TABLEA
([desc]
,[user_id]
)
select desc, user_id from TABLEA where user_id = @old_user_id
END
答案 0 :(得分:1)
您可以使用自联接来匹配旧的和新的父ID。
CREATE PROCEDURE [duplicate_user_data]
@old_user_id int,
@new_user_id int
AS
INSERT INTO TableA ([desc], [user_id])
SELECT [desc], @new_user_id
FROM TableA
WHERE [user_id] = @old_user_id
INSERT INTO TableB ([a_id], [detail])
SELECT NewTableA.[a_id], TableB.[detail]
FROM TableA AS NewTableA
CROSS JOIN TableA AS OldTableA
JOIN TableB ON TableB.[a_id] = OldTableA.[a_id]
WHERE NewTableA.[user_id] = @new_user_id
AND OldTableA.[user_id] = @old_user_id
答案 1 :(得分:0)
如果我理解正确,您希望为新用户插入新记录,但要复制其他用户的详细信息。如果是这样,那么你可以这样做:
CREATE PROCEDURE [duplicate_user_data]
@old_user_id int,
@new_user_id int
AS
BEGIN
declare @old_a_id int
-- get the old a_id first
SELECT @old_a_id = a_id
FROM TableA
WHERE [user_id] = @old_user_id
-- insert the new record into TableA
INSERT INTO TABLEA
(
[desc]
,[user_id]
)
select [desc]
, @new_user_id
from TABLEA
where [user_id] = @old_user_id
-- insert new record into tableB using the @old_a_id
INSERT INTO TableB
(
a_id
, detail
)
SELECT @old_a_id
, detail
FROM TableB
WHERE a_id = @old_a_id
END
这会将new_user_id
插入TableA
,但会[desc]
old_user_id