SQL database notes, continuous update

1. No database selected. . .

Insert picture description here
I have encountered this problem several times, and every time I open the software, I forgot to select the database I want to operate, and I froze there for a long time, looking for instructions everywhere. . .
The instruction operation should correspond to the selection of the database to be operated! ! !

2. Data duplication. . .

I just encountered a problem. There were too many duplicate cnos in the subquery, which caused the statement to be unresponsive. Based on my previous experience with a self-made language, I estimate that the data in the set obtained by the subquery must be unique, otherwise it will be thrown. An exception occurred, causing the outside statement to fail! ! !

--删除没有人选的课程的记录。
DELETE FROM course WHERE cno not in(SELECT cno FROM sc)   --incorrect
DELETE FROM course WHERE cno not in(SELECT DISTINCT cno FROM sc)  --correct

3. When no EXISTS is used to introduce a subquery, only one expression can be specified in the select list. . .

There can only be one selection item in the subquery! ! !

--显示VB课程的第2名到第4名的学生的学号、姓名、成绩。
SELECT top 3
		sc.sno,sname,grade FROM student 
		JOIN sc on student.sno = sc.sno
		JOIN course on course.cno = sc.cno
		WHERE cname = 'VB基础' and grade not in (
			
			SELECT top 1 
				sc.sno,sname,grade FROM student   --incorrect
				grade FROM student    				--correct
				JOIN sc on student.sno = sc.sno
				JOIN course on course.cno = sc.cno
				WHERE cname = 'VB基础'
				ORDER BY grade DESC
		
		) 
		ORDER BY grade DESC

4. Invalid column name

This is often a wrong word,,,,

5. When aggregate functions cannot be used in Where!

Learn to use → \rightarrow HAVING
When you cannot use Where to achieve constraints, first use GROUP BY to group, and then use HAVING clause!

For example, functions like AVG cannot be used in WHERE, but can be used in HAVING! ! !

6. Problems that cannot be deleted

Select a row but cannot delete it, saying that it cannot be found!

For example, such a topic: create a trigger, when deleting a student record in student, delete the student record in sc at the same time!

--1、建立一个触发器T_delsc,当删除STUDENT表中的某条记录时,
--也删除SC表中与其相关联的记录。


----删除已有的触发器
IF EXISTS( SELECT name FROM SYSOBJECTS WHERE name='T_delsc')
	DROP TRIGGER T_delsc
GO

--创建新的触发器
CREATE TRIGGER T_delsc
	ON student
	FOR DELETE
	AS
	BEGIN
		DECLARE @NO char(8)						--定义中间变量
		SELECT @NO=sno FROM DELETED				--在DELETED中查询要删除的学号
		DELETE sc WHERE sno = @NO				--删除该学号的所有记录
	END
GO
----直接在student删除一条记录时,因为会删除sc中的多条记录,这多条记录的学号一样,SQL Server不知道要删除哪条,所以删除操作被SQL Server阻止!!!
----解决方式是设置sno为student的主键!!!

The execution is successful, but when you manually delete a record in the student, it cannot be deleted-the reason is that the sno in the student table is not set as the primary key!

Guess you like

Origin blog.csdn.net/weixin_41374099/article/details/105630845