SQL basic command statement records

Source: Internet
Author: User

1. Create the database teaching (including the course, score, teacher, class, and teach_class tables ).

use mastergoif exists(select * from sysdatabases where name='teaching')drop database teachingcreate database teachingon (name =teaching,filename ='g:/SQL/teaching.mdf')log on(name=teaching_log,filename='g:/SQL/teaching_log.ldf')

2. Use the T-SQL statement to perform basic operations in the teaching database.
A. Create the course table structure:

create table course(courseno nchar(6) not null,cname nchar(20) not null,type nchar(8) not null,period tinyint not null,credit numeric(4,1) not null,constraint PK_course primary key clustered(courseno ASC))

B. insert

Insert course values ('c111111', 'electronic techno', 'compulsory)

C. query statement example
1) query the names and ages of all boys older than 20 in the student table.

Select sname as name, year (getdate ()-year (birthday) as age from student

2). query the number of students who have selected elective courses and whose final score is not empty.

Select count (*) as count from scorewhere final is not null and courseno in (select courseno from course where type = 'electives ')

3) query the student's student ID, number of optional courses, and total score, and store the query results in the generated "Student Course Selection statistical table.

Select studentno as student ID, count (*) as number of elective courses, sum (final) as total score into student course selection statistical table from scoregroupby studentno

4) query the electives 'c05109 ', and the student ID, course number, and final score of the first five students with the final score.

Select top 5 studentno as student ID, coursenoas course number, final as final score from scoreorder by final DESC

5 ). if the course number starts with 'c05 'and is selected by three or more students and the final score is higher than 75, the course number, number of optional students, and the final score are average, and sorted in descending order on average.

Select courseno course No., count (*) electives, avg (final) end average score from scorewhere courseno like 'c05% 'group by coursenohaving count (*)> = 3 and avg (final)> 75 order by avg (final) desc

6) to query the average end score of all students of grade 08, you must use the computeby method to display the number, course number, end Score list, and summary table of the average end score.

Select studentno student number, courseno course number, final score from scorewhere '08 '= substring (studentno, 1, 2) compute avg (final)

D. Update

Update student set sex = 'feme' where studentno = '201312'

E. Delete

delete from studentwhere studentno='0922221324'

F. Modify

① Add the ethnic nation column to the student table. The data type is varchar (10) and can be empty. Alter table student add nation varchar (10) ② modify the Data Type of the nation column in the student table to varchar (10 ). Alter table student alter column nation varchar (12) ③ Delete the column nation in student. Alter table student drop column nation

G. View

if object_id('v_age','view')is not nulldrop view v_agegocreate view v_ageasselect studentno,sname,sex,birthday,classnofrom studentwhere year(getdate())-year(birthday)>=18drop view v_age

H. Index
Create a unique non-clustered index UQ_tname on the tname column of the teacher table in the teaching database using a T-SQL statement. If the index already exists, delete it and recreate it.

if exists(select name from sys.indexes where name='UQ_tname')drop index UQ_tname on teachergocreate unique nonclustered index UQ_tnameon teacher(tname)drop index UQ_tnameon teacher

3. cursors, triggers, stored procedures, and transactions
A. Use a cursor to output the Student name, elective course name, and final exam score.

Print 'name course final score 'declare @ sname varchar (20), @ cname varchar (20), @ final varchar (20) declare stu_cursor cursorforselect sname, cname, finalfrom student a join score B on. studentno = B. studentno join course c onb. courseno = c. coursenoopen stu_cursorfetch next from stu_cursor into @ sname, @ cname, @ finalwhile @ fetch_status = 0 beginprint @ sname + @ cname + @ finalfetch next from stu_cursor into @ sname, @ cname, @ finalendclose stu_cursordeallocate stu_cursor

B. Create a stored procedure ProcAvg using T-SQL statements to query the average score of a specified course in a specified class. The class number and Course name are given by the input parameters. The calculated average score is returned by the output parameters. Call the stored procedure after the creation.

Create proc procavg @ classno nchar (10), @ cname nchar (20), @ AVG int outputasselect @ AVG = AVG (final) from student a join score B on. studentno = B. studentno join course C on B. courseno = C. coursenowhere. classno = @ classnoand C. cname = @ cname declare @ avg1 intexec procavg '000000', 'mechanical plotting ', @ avg1 outputprint @ avg1

C. Create an After trigger trigclassname using the T-SQL statement. when data is inserted or modified into the class table, things are rolled back if the class name is repeated. Test the trigger.

Create trigger into classfor insert, updateasdeclare @ classname1nchar (12) Select @ classname1 = classname from insertedif exists (select classname from class where classname = @ classname1 group by classname having count (*) = 2) Begin raiserror ('duplicate class name ',) rollback endelse raiserror ('success! ', 16,2)

D.
1) define a thing, add a student's basic information record and Course Selection Record in the student table and score table of the Teaching database, and submit things.

Begin transaction trans_insertinsert into student values ('000000', 'wyz2', 'male', '2017-09-02 ', '2', '000000', '4 ', '4'); insert into score values ('201312', 'c05104 ', '11', '11'); commit tran trans_insert

2 ). define a thing, change the gender of students whose Student ID is '2013' to 'female, and set a save point, then, change the final score of the student whose student ID is 0922221326 in the score table to 88, and finally roll back to the storage point to submit the transaction.

Begin transactionupdate student set sex = 'femal' where studentno = '000000' save tran savepointupdate score set final = 88 where studentno = '000000' rollback tran savepointcommit tran

4. Permission assignment

a.grant insert,delete on student to U1b.revoke select on student from U1 cascadec.deny select to U1

5. Backup and Restoration
A. back up the teaching database, create a backup device named "teachbak" in T-SQL language, the complete file name for the device in the hard disk is "D: \ SQL \ teaching. bak ".

Exec sp_addump device'disk','teachbak','D:\SQL\teaching.bak'backup database teaching to teachbak

B. Back up the "teaching" database to the "D: \ SQL \ teaching. bak" file using the T-SQL language.

backup database teaching to disk='D:\SQL\teaching.bak'

C. Use the T-SQL language to restore the backup to the "teaching" database.

restore database teaching from disk='D:\SQL\teaching.bak'with file=1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.