Sql 复制同一表的多行,但id不同,并将复制行的旧id存储在列名old ids中
这是我使用游标的代码,它做得很好,但由于速度问题,我不想使用游标Sql 复制同一表的多行,但id不同,并将复制行的旧id存储在列名old ids中,sql,sql-server,Sql,Sql Server,这是我使用游标的代码,它做得很好,但由于速度问题,我不想使用游标 DECLARE @StudentID NVARCHAR(MAX)='1,2,4,5,6,7,8,9,10' SELECT value StudentID INTO #TMP_tbSchedulTas FROM STRING_SPLIT(@StudentID,',') DECLARE @SchedID AS Integer SELECT @SchedID = StudentID FROM #TMP_tbSchedulTa
DECLARE @StudentID NVARCHAR(MAX)='1,2,4,5,6,7,8,9,10'
SELECT value StudentID INTO #TMP_tbSchedulTas FROM STRING_SPLIT(@StudentID,',')
DECLARE @SchedID AS Integer
SELECT @SchedID = StudentID
FROM #TMP_tbSchedulTas
DECLARE Attendence CURSOR FOR
SELECT StudentID FROM #TMP_tbSchedulTas
OPEN Attendence
FETCH NEXT FROM Attendence INTO @SchedID
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO dbo.Student
(
FirstName,LastName,
FatherName,DOB,CNIC,Religon,Mobile,Email,Address,Gender,Isactive,Isdeleted,CreatedBy,CreatedOn,CityID,OldstudentId,BranchID,IsSelected,StudentGUID )
SELECT FirstName,LastName,
FatherName,DOB,CNIC,Religon,Mobile,Email,Address,Gender,Isactive,Isdeleted,CreatedBy,CreatedOn,CityID,@SchedID,BranchID,IsSelected,StudentGUID FROM dbo.Student
WHERE StudentID=@SchedID
FETCH NEXT FROM Attendence INTO @SchedID
END
CLOSE Attendence
DEALLOCATE Attendence
-- drop temporary table to store schedule event attendees email status
DROP TABLE #TMP_tbSchedulTas
您可以这样简化它,但是我不确定您是否真的想从同一个表中读取数据并再次插入到该表中,原因是什么
DECLARE @StudentID NVARCHAR(MAX) = N'1,2,4,5,6,7,8,9,10';
INSERT INTO dbo.Student
(
FirstName
, LastName
, FatherName
, DOB
, CNIC
, Religon
, Mobile
, Email
, Address
, Gender
, Isactive
, Isdeleted
, CreatedBy
, CreatedOn
, CityID
, OldstudentId
, BranchID
, IsSelected
, StudentGUID
)
SELECT
FirstName
, LastName
, FatherName
, DOB
, CNIC
, Religon
, Mobile
, Email
, Address
, Gender
, Isactive
, Isdeleted
, CreatedBy
, CreatedOn
, CityID
, @SchedID
, BranchID
, IsSelected
, StudentGUID
FROM
dbo.Student
WHERE
StudentID IN
(
SELECT
value StudentID
FROM
STRING_SPLIT(@StudentID, ',')
);
使用和a,如中所示,而不是使用@SchedID,我可以直接使用studentID