任何人都可以帮我解决这个问题吗?我不确定我的导师是什么意思......
这是#3和我的解决方案:
我的代码:
DECLARE @enrollment INT
DECLARE killCourse_Cursor CURSOR
FOR
SELECT Enrollment FROM Course
OPEN killCourse_Cursor
FETCH NEXT FROM killCourse_Cursor INTO @enrollment
WHILE (@@FETCH_STATUS = 0)
BEGIN
IF(@enrollment < 20)
BEGIN
DELETE FROM Course WHERE @enrollment = Enrollment
END
FETCH NEXT FROM killCourse_Cursor INTO @enrollment
END
CLOSE killCourse_Cursor
DEALLOCATE killCourse_Cursor
SELECT Ref_Number, Enrollment FROM Course
该表只有10行,在我完成后仍然有5行。我想我误解了这个问题?一旦我更新表并删除行...有没有办法知道删除了什么?这里很困惑......
答案 0 :(得分:0)
我同意在你完成后忘记游标。有几件事情浮现在脑海中。你是否也在学习触发器?使用触发器,您可以判断记录是否已删除,并可能将其写入单独的表或其他内容。
如果显示“应显示消息以指示课程已被删除”的部分是第二个任务,而不是第一个句子的一部分,则可能只是意味着使用PRINT语句写入删除记录时的“消息”选项卡。
我没有在游标进程中维护记录更改列表(删除,更新等)的任何内容。
答案 1 :(得分:0)
你的第一个解决方案开始很弱。即使被迫使用光标,也应该不选择您不需要的记录。让WHERE
子句为您完成工作。
您还应该使用课程Ref_Number删除课程,而不是注册!
您的光标可以构建一个临时表,其中包含有关已删除课程的信息供以后使用 - 但我的示例显示您也可以跳过光标。
鉴于:
CREATE TABLE dbo.Course ( Ref_Number INT PRIMARY KEY
, Enrollment INT
, Title VARCHAR(99))
和一些示例数据
INSERT INTO dbo.Course VALUES(100,22,'Java')
INSERT INTO dbo.Course VALUES(101,2,'Objective C')
INSERT INTO dbo.Course VALUES(102,3,'Into to Apple Development')
INSERT INTO dbo.Course VALUES(200,32,'Databases are cool')
INSERT INTO dbo.Course VALUES(201,22,'Primary Keys and You')
INSERT INTO dbo.Course VALUES(202,2,'Advanced Apple Development')
您可以收集并记住要删除的内容
SELECT Ref_Number, Enrollment, Title
INTO #KillList
FROM dbo.Course
WHERE Enrollment < 20
然后立即删除它们
DELETE FROM kc
FROM dbo.Course kc JOIN #KillList kl ON kl.Ref_Number = kc.Ref_Number
并打印剩余的列表
SELECT Ref_Number, Enrollment FROM dbo.Course
或打印整个列表,包括已删除的列表
SELECT Ref_Number, Enrollment, Title, '' as status FROM dbo.Course
UNION ALL SELECT Ref_Number, Enrollment , Title, 'DELETED!' as status
FROM #KillList kl
ORDER BY 1
使用可怕的cursor
SELECT * INTO #KillList2 FROM dbo.Course WHERE Enrollment < 20
DECLARE @RefNum INT
DECLARE killCourse_Cursor CURSOR
FOR
SELECT Ref_Number FROM Course WHERE Enrollment < 20
OPEN killCourse_Cursor
FETCH NEXT FROM killCourse_Cursor INTO @RefNum
WHILE (@@FETCH_STATUS = 0)
BEGIN
DELETE FROM Course WHERE Ref_Number = @RefNum
FETCH NEXT FROM killCourse_Cursor INTO @RefNum
END
CLOSE killCourse_Cursor
DEALLOCATE killCourse_Cursor
SELECT Ref_Number, Enrollment FROM Course
SELECT Ref_Number, Enrollment, Title, '' as status FROM dbo.Course
UNION ALL SELECT Ref_Number, Enrollment , Title, 'DELETED!' as status
FROM #KillList2 kl
ORDER BY 1