sqlserver2016 (basic concepts and commonly used T-SQL statements)

Database common objects

  • Table (main form of storing data and expressing relationship)
  • View (the reference table generated by one or more tables also becomes a virtual table, which is a way to query data, instead of storing data, but storing its query definition. When opening a view, the query definition is executed and the corresponding data is generated)
  • Index (sort a column or a combination of columns in the table, by searching the value of the index expression, you can achieve quick access to this type of data)
  • Constraints (used to ensure data consistency and integrity)
  • Stored procedures (a group of SQL statements that complete specific functions are compiled and stored in the SQLserver server-side database in the form of names, and the user can execute them by specifying the name of the stored procedure)
  • Trigger (a special type of stored procedure that triggers execution when a specific event occurs)

System database

  • There are 4 default databases by default when the database is installed
  • The master database (records all system-level information, database file location, initialization information, if the master database cannot be used, the SQL Server fails to start)
  • model database (template for all databases, which can be changed)
  • msdb database (used to plan alarms and jobs, etc.)
  • tempdb database (temporary database, used to store temporary objects and intermediate result sets)

Files and file groups

 file:

  • Master data file (.mdf), one
  • Secondary data files (.ndf), 0 or more
  • Log file (.ldf), one or more
     file groups:
  • The main file group (the main data file, not explicitly allocated, the system table is allocated here)
  • User-defined file group (any file group specified by FILEGROUP in CREAT DATEBASE and ALTER DATEBASE statements)
  • Default file group (only one file group is the default file group at a time, if not specified, then the main file group is the default file group)
     design rules:
  • File can only be a member of a file group
  • File or file group can only be used by one database
  • Data and logs cannot be put together, which means they cannot belong to the same file or file group
  • The log file is not part of the file group, which means that the data space and log space are managed separately.

Database creation

Create a database named Student with an initial size of 5MB and a maximum size of 20MB. Automatic growth is allowed, and it grows by 10%. The initial size of the log file is 2MB, and the maximum size is 8MB, increasing by 1MB. The storage location of data files and log files is the database folder "C:\SQL Practice" of SQL Server.

CREATE DATABASE Student
	ON --存放数据库的数据文件在之后定义
	(
		NAME='Student_DATA',--只是T-SQL中使用的逻辑文件名
		FILENAME='C:\SQL练习\Student.mdf',--存放路径和操作系统中实际文件名
		SIZE=5MB,
		MAXSIZE=20MB,
		FILEGROWTH=10%
	)
	LOG ON
	(
		NAME='Student_log',
		FILENAME='C:\SQL练习\Student.ldf',
		SIZE=2MB,
		MAXSIZE=8MB,
		FILEGROWTH=1MB
	)
GO

Delete database

DROP DATABASE Student 

Separation and attachment of database

Slightly, but remember: once a database is successfully detached, from the perspective of SQL Server, it is no different from deleting the database. The difference is that the storage files of the separated database still exist, but the storage files of the deleted database no longer exist.

Table Structure

  • The names and data types of the columns that make up the table are collectively referred to as the table structure

recording

  • Each table contains several rows of data, which are the "values" of the table. A row in the table is called a record. Therefore, a table is a limited collection of records.

Field

  • Each record consists of several data items. The data items that make up the record are called fields. For example, the table structure in Table 6-1 is (student ID, name, gender, date of birth, major, total credits, remarks), which contains 7 fields and consists of 8 records.

Null value

  • Null value (NULL) usually means unknown, unavailable or data that will be added later. If a column is allowed to be null, it is not necessary to give a specific value for the column when entering the record in the table; if a column is not allowed to be a null value, then a specific value must be given when entering.

Keyword

  • If a field or combination of fields in a record in the table can uniquely identify the record, the field or combination of fields is called a candidate key

Primary key

Select one of the primary keys (Primary Key), also known as the primary key. Used to uniquely identify the record.

Foreign key

The columns in the "child table" that correspond to the "main table" are called foreign keys or reference keys in the "child table". Its value requirements correspond to the primary key of the main table. Foreign keys are used to enforce referential integrity. A table can have multiple foreign keys.

type of data

Design table

  • The naming of the table adopts the Pascal naming rules, and should be named with complete English words, avoid using abbreviations, and English words are in singular form.
  • Field naming also adopts Pascal naming rules. There must be a primary key. The auto-incrementing primary key of the table uses the ID. The unique primary key name of the table uniformly uses "table name + ID", such as StudentID.

constraint

  • Constraints are a method of automatically maintaining database integrity provided by SQL Server. It guarantees data integrity by restricting data in fields, data in records, and data between tables. In SQL Server, there are two types of constraints for basic tables: column-level constraints and table-level constraints.

Create table

Create a database with the CREATE TABLE statement StudentManagement in the Course table, required courses numbered primary key , course name unique , each course credit default is 4.

USE StudentManagement
GO
CREATE TABLE Course
(
    CourseID char(6) PRIMARY KEY,
    CourseTypeID char(2),
    CourseName nvarchar(30) UNIQUE,
    Info nvarchar(50),
    Credits numeric(2,0) DEFAULT(4),
    Time numeric(3,0),
    PreCourseID char(6),
    Term numeric(1,0)
)

Use the CREATE TABLE statement to create the SelectCourse table in the StudentManagement database, record the information of students' course selection, and set foreign key constraints .

USE StudentManagement
GO
CREATE TABLE SelectCourse
(
    SelectCourseStudentID char(10) FOREIGN KEY(SelectCourseStudentID) REFERENCES Student(StudentID),
    SelectCourseID char(6) FOREIGN KEY(SelectCourseID) REFERENCES Course(CourseID),
    Score numeric(3,1),
    PRIMARY KEY(SelectCourseStudentID,SelectCourseID)
)

Modify table

  • Use the ADD clause to add columns


    Use the ALTER TABLE statement to add StudentBonus columns to the Student table


    ALTER TABLE <table name> ADD <column name> <data type>[<integrity constraint>]
ALTER TABLE Student ADD StudentBonus tinyint
  • Use the ADD CONSTRAINT clause to add constraints


    . Set a unique constraint on the Name column in the Student table.


    ALTER TABLE <table name> ADD CONSTRAINT <constraint name> Constraint [<column name table>]
ALTER TABLE Student ADD CONSTRAINT Name01 UNIQUE(Name)
  • Use the ALTER COLUMN clause to modify the column attribute


    of the Email column in the Student table to 50, and allow it to be empty.


    ALTER TABLE <table name> ALTER COLUMN <column name> <data type> [NULL|NOT NULL]
ALTER TABLE Student ALTER COLUMN Email varchar(50) NULL
  • Rename column


    EXEC sp_rename'table name. The original column name','the changed column name'

EXEC sp_rename 'Student.Name', 'StudentName
  • Use the DROP COLUMN clause to delete columns.


    Delete the StudentBonus column in the Student table.


    ALTER TABLE <table name> DROP COLUMN <column name>
ALTER TABLE Student
DROP COLUMN StudentBonus
  • Use the DROP CONSTRAINT clause to delete constraints.


    Delete the unique constraint on the Name column in the Student table.


    ALTER TABLE <table name> DROP CONSTRAINT <constraint name>
ALTER TABLE Student DROP CONSTRAINT Name01
  • Delete table
DROP TABLE TestDelete

Insert data into the table

  • Add 4 class records to the Class table
USE StudentManagement
GO
INSERT Class(ClassID, ClassDepartmentID, ClassTeacherID, ClassName, Amount)
    VALUES('20191101', '11', '20101123', '计算机1901', 30)
INSERT Class
    VALUES('20192602', '26', '20122652', '自动化1902', 40)
INSERT Class
VALUES('20193101 ','31','20113145', '哲学1901',60)
INSERT Class
    VALUES('20196202', '62', '20136238', '经贸1902', 40)
GO
SELECT * FROM Class
GO

Modify the data in the table

  • Change the name of the class with the class number "20196202" in the Class table to "Foreign Economic and Trade 1902" and the number of people to 30.
USE StudentManagement
GO
UPDATE Class
    SET ClassName ='外经贸1902', Amount=30
    WHERE ClassID='20196202'
GO
SELECT * FROM Class
GO

Delete records in the table

  • Delete the record of the student named "Wang Yiming" in the Student table
USE StudentManagement
GO
DELETE Student
    WHERE StudentName='李一民'
Go
SELECT * FROM Student
GO

Guess you like

Origin blog.csdn.net/qq_45549336/article/details/108037262