我在這裏發現此線程:http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=16836 我有完全相同的問題。報價:sql中行的級聯副本
羅布紅蘋果寫道:「我有一個持有疑問3個表
表1:問題
字段:ID(唯一的)字段:姓名(文本)
表2:問題文本(參考表1-ID)
字段:ID(唯一)字段:QuestionID(inte GER裁判表1 ID) 字段:文本
表3:選項
字段:ID(唯一)字段:QuestionTextID(整數裁判表2 ID) 字段:文本
說,例如,我用2個問題文本記錄和選項記錄創建了一個問題。如果我想將該問題複製到新的 問題中,並將問題文本記錄複製到新ID和所有 相關選項,我怎樣才能輕鬆完成此任務(因爲重複的 問題將有一個新的ID,每個。中複製的問題文本的 將有新的ID,這將每個選項)」
建議的解決方案是:
create procedure CopyQuestion
@idtocopy int
AS
declare @tempquestionid
declare @tempquestiontextid
declare @questiontextid
insert into question (name)
select name from question where id = @idtocopy
select @tempquestionid = @@identity
declare question_cursor cursor for
select id from [question text] where id = @idtocopy
open question_cursor
fetch next from question_cursor into @questiontextid
while @@fetch_status = 0
begin
insert into [question text] (questionid, text)
select @tempquestionid, text from [question text] where id = @questiontextid
select @tempquestiontextid = @@identity
insert into [options] (questiontextid, text)
select @tempquestiontextid, text from [options] where questiontextid = @questiontextid
fetch next from question_cursor into @questiontextid
end
close question_cursor
deallocate question_cursor
是否有更好的解決這個問題,我將使用插入觸發器 謝謝!
我還沒有仔細查看其餘的邏輯,但請停止使用@@ IDENTITY - 使用SCOPE_IDENTITY()代替。所以問題有id和name,你可以使用完全相同的名稱創建一個新的問題,但新的代理標識值?用戶將如何區分他們 - 他們是否必須記住ID? –
我會的。我更關心光標,並且我認爲有更好的方法去做 – user194076
不理解邏輯。如果遊標實際上說WHERE questionid = @idtocopy?你似乎在混合使用一個名爲「ID」的列......這個光標實際上是做你期望的嗎?你能展示一些樣本數據和期望的結果嗎?另外,你的數據類型真的是TEXT?您應該在SQL Server 2008中使用VARCHAR或NVARCHAR。TEXT已棄用。 –