SQL data definition, update, view

1 Data Definition Language

Definition 1.1 database

As a whole database is stored in external memory in the physical file. There are two physical file:

  • First, the data file (data file), the object data stored in the database;
  • Second, the log file (log file), storing redundant data for restoring the database.

  A database can have multiple physical file may be provided one or several physical file as a logical device; a database can have multiple logical devices, it must be defined in the definition of the database. Only need to specify the object stored in the logic device which, without concern for the details of the definition of more physical database objects; to contact by the logical device and the physical file, in order to achieve independence mode and the storage mode logical database.

USE master;
GO
--在创建 ScoreDB 数据库之前删除名为 ScoreDB 的数据库(如果它存在)。
IF DB_ID (N'ScoreDB') IS NOT NULL
DROP DATABASE ScoreDB;
GO
--以下示例会创建数据库 ScoreDB。 由于未使用关键字 PRIMARY,因此第一个文件 (ScoreDB_data) 将成为主文件。 
--因为在 ScoreDB_data 文件的 SIZE 参数中没有指定 MB 或 KB,将使用 MB 并按 MB 分配。 
--ScoreDB_log 文件以 MB 为单位进行分配,因为 SIZE 参数中显式声明了 MB 后缀。
CREATE DATABASE ScoreDB
ON								--定义数据文件
	( NAME=ScoreDB_data,		--逻辑文件名
								--物理文件名
	  FILENAME='G:\ProgramFiles\MSSQL14.SQLEXPRESS01\MSSQL\DATA\ScoreDB_data.mdf' ,
	  SIZE=10,					--文件初始大小为5MB
	  MAXSIZE=200,				--文件最大为200MB
	  FILEGROWTH=5				--增量为5MB
	)
LOG ON							--定义日志文件
	( NAME=ScoreDB_log,			--逻辑文件名
	  FILENAME='G:\ProgramFiles\MSSQL14.SQLEXPRESS01\MSSQL\DATA\ScoreDB_log.ldf' ,
								--物理文件名
	  SIZE=10MB,				--文件初始大小为5MB
	  MAXSIZE=200MB,			--文件最大为200MB
	  FILEGROWTH=5MB			--增量为5MB
	)
GO

1.2 Definition of the base table

  After you create a database, you can create a basic table in the database. By base table associated with a logical device, so that a basic table can be placed on a data file, you may be placed on the plurality of data files.

The basic SQL data types are:

  • Integer: int (4B), smallint (2B), tinyint (1B);
  • 实型:float、real(4B)、decimal(p, n)、numeric(p, n);
  • Character: char (n), varchar (n), text;
  • The binary type: binary (n), varbinary (n), image;
  • Logical: bit, 0 and 1 can take, NOT NULL
  • Currency: money (8B, 4 decimal places), small money (4B, 2 decimal places);
  • Time Type: datetime (4B, beginning from 1753-01-01), smalldatetime (4B, from start 1900-01-01).

Wherein: image data stores the image type, text store large text data.

1.2.1 Creating a Basic Table

  When you create a basic table, associated with the basic table describes the information will be stored into the database system tables. Creating a basic table operations syntax is:

CREATE TABIE <tableName>
(
    <columnNamel> <dataType> [DEFAULT <defaultvalue>][NULL | NOT NULL] [,
	<columnName2> <dataType> [DEFAULT <defaultvalue>][NULL | NOT NULL]…]
	[, CONSTRAINT <constraintName1>] 
	   {UNIQUE | PRIMARY KEY} (<columName1> [, <columName2>…])[,…n]
	]
	[, CONSTRAINT <constraintName2>] 
	   FOREIGN KEY (< columName1> [, < columiName2>…])
	   	 REFERENCE [<dbName>.owner.]<refTable> (<refColumn1> [, <refColum2>…])[,…n]
	]
)[ON <filegroupName>]

among them:

  • <TableName>: name of the base table, may contain up to 128 characters
  • <ColumnName>: base table column name, unique within the table;
  • <DataType>: Specifies the data type of the column;
  • DEFAULT: Set Province value for the column, would be optional;
  • NULL | NOT NULL: Set whether to allow the column to a null value, would be optional;
  • <ConstraintName>: define the name of the constraint, would be optional;
  • UNIQUE: Create a unique index;
  • PRIMARY KEY: establish a master key;
  • FOREIGN KEY: the establishment of outer code;
  • ON <filegroupName>: database object on the specified logical device (s), the logical device (s) must be defined in the creation of the database or the database using the modified command has been added to the database logic device (group ), the object will be automatically established on the primary logical device by default.

  Recommendation: best not to put user database objects (such as basic tables, indexes, etc.) based on the main logic device, because the main logic device storage system management information database.

DROP TABLE IF EXISTS [dbo].[Student]
GO
CREATE TABLE Student
(
	studentNo	char(7)						NOT NULL    --学号
		CHECK (studentNo LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][0-9]'),	
	studentName varchar(20)					NOT NULL,	--姓名
	sex			char(2)						NULL,		--性别
	birthday	datetime					NULL,		--出生日期
	native		varchar(20)					NULL,		--籍贯
	nation		varchar(30)	DEFAULT '汉族'	NULL,		--民族
	classNo		char(6)						NULL,		--所属班级
	CONSTRAINT StudentPK PRIMARY KEY (studentNo),
	CONSTRAINT StudentFK FOREIGN KEY (classNo) REFERENCES Class(classNo)
);
GO

1.2.2 modify the basic table

Basic table structure may be modified by the ALTER TABLE command, such as expansion columns and the like.
Modifying the basic operating table syntax is:

  • Adding columns (null value of a new)
ALTER TABLE <tableName>
	ADD <columnName> <dataType>
  • Adding constraints.
ALTER TABLE <tableName>
	ADD CONSTRAINT <constraintName>
  • Delete constraints.
ALTER TABLE <tableName>
	DROP <constraintName>
  • Modifying the data type of the column
ALTER TABLE <tableName>
	ALTER COLUMN <columnName> <newDataType>

Wherein, <tableName> is the name of the table to be modified substantially.

Delete 1.2.3 basic table

DROP TABLE <tableName> [RESTRICT | CASCADE]
  • If selected RESTRICT , delete the base table there is a limit condition, i.e., in the basic table can not have a view, triggers and other base table is referenced (such as checking the CHECK constraints, an outer code constraint FOREIGN KEY), the default value
  • If you select CASCADE , the delete basic table no restrictions, delete the base table, but also delete all the indexes on the establishment of the basic table, integrity rules, triggers, and views, and so, when you delete a base table, the system will deleted from the database system is described together with the base table of tables,

Note: SQL Server does not support [RESTRICT | CASCADE] option

2 SQL language update

2.1 Inserting data

  • Insert a tuple
INSERT INTO <tableName> [(<columnName1> [, <columnName2>…])]
	VALUES(<value1> [, <value2>…])
  • Inserting a plurality of tuples
INSERT INTO <tableName> [(<columnName1> [, <columnName2>…])]
	<subquery>

E.g:

CREATE TABLE StudentNation (
	studentNo	char(7)					NOT NULL,	--学号
	courseNo	char(3)					NOT NULL,	--课程号
	termNo		char(3)					NOT NULL,	--学期号
	score		numeric(5,1) DEFAULT 0  NOT NULL	--成绩
		CHECK (score BETWEEN O.O AND 100.0),
	CONSTRAINT studentNationPK PRIMARY KEY (studentNo, courseNo, termNo)
)

--执行如下插入语句:

INSERT INTO StudentNation
	SELECT *
	FROM Score
	WHERE studentNo IN(SELECT studentNo FROM Student WHERE nation<>'汉族')

INSERT INTO StudentNation (studentNo, courseNo, termNo)
	SELECT studentNo, courseNo, termNo
	FROM Score
	WHERE studentNo IN (SELECT studentNo EROM Student WHERE nation='汉族')

2.2 to delete data

DELETE FROM <tableName> [WHERE <predicate>]

E.g:

DELETE FROM SCORE
WHERE studentNo='1600001'

Modification data 2.3

UPDATE <tableName>
SET <columnName1>=<expr1> [, <columnName2>=<expr2>…]
[FROM {<tableName1> | <queryName1> | <viewname1>} [[AS] <aliasName1>]
	[,{<tableName2> | <queryName2> | <viewname2>} [[AS] <aliasName2>] … ]
]
[WHERE <predicate>]

among them:

  • <TableName>: To modify the basic data table;
  • SET <columnName1> = <expr1> [, <columnName2> = <expr2> ...]:
    replace attribute values specified by the edge-type column value table, one can modify the attribute values of a plurality of columns, a comma between points;
  • [WHERE <predicate>]: indicates the conditions are modified to meet the tuple, that can be omitted, if omitted, all tuples showing modified base table, may be included in the WHERE clause subquery

E.g:

UPDATE Class SET classNum=sCount
FROM Class a, ( SELECT classNo, count(*) sCount
     			FROM Student
     			GROUP BY calssNo) b
WHERE a.classNo=b.classNo     			

3 views

  View is a virtual table, is derived from one or several base table (or view) in the table in the database system to store only the tables of the definition of the view, the view does not store data corresponding . When the data base table changes, a query from the view data is also changed .
  View enables out pattern database management system three modes, based operational view include: query , delete , limited update and define a new view based on the view , the view is that the main role:

  1. Simplify the user's operation;
  2. Allowing users to look at a variety of angles to the same database schema;
  3. To reconstruct the database schema provides a degree of logic independence;
  4. To provide a degree of security to protect confidential data in the database;
  5. Can more clearly express queries appropriate use of view.

3.1 Definitions view

Before using the view must be defined view:

CREATE VIEW <viewName> [(<columnName1> [, <columnName2>…])]
	AS <subquery>
	[WITH CHECK OPTION]
  • <ViewName>: name of the new view, the name must be unique within the database;
  • <columnName1> [, <columnName2> ...]: column names in the view definition. If the column name is omitted
    not write column names of the view automatically take <subquery> statement to check out the column names. If one of the following three cases, you must write the column name of the view:
  1. <Subquery> in a certain column are polymeric query function or expression;
  2. <Subquery> query appears in multi-table joins in the same name as the column name;
  3. New name needs to take more appropriate for a column in the view.
  • AS <subquery>: sub-queries, and must not contain an ORDER BY clause DISTINCT phrase;
  • [WITH CHECK OPTION]: If this option is used, then the view is updated to ( insert, delete, modify ) the validity check operation must be carried out only when the update operations of the view definition satisfies the predicate condition (<subquery> promoter when the conditional expression) queries, the update operations are allowed

E.g:

CREATE VIEW StudentView1999
AS
	SELECT *
	FROM Student
	WHERE year(birthday)=1999
CREATE VIEW ScoreView (courseNo, courseName, courseCount, courseAvg)
AS
	SELECT a.courseNo, courseName, count(*), avg (score)
	FROM Course a, Score b
	WHERE a.courseNo=b.courseNo
	GROUP BY a.courseNo, courseName

--或

CREATE VIEW ScoreView1
AS
	SELECT a.courseNo, courseName, count(*) courseCount, avg (Score) courseAvg
	FROM Course a, Score b
	WHERE a.courseNo=b.courseNo
	GROUP BY a.courseNo, courseName

3.2 Query View

  Query is the most important operations carried out on the view. From the user's perspective, the query and the query view mode table is substantially exactly the same, from a system perspective, the process of query views are:

  1. Checking the validity checks involved in the query whether there are basic tables and views
  2. Definition of a view taken from the system database tables, and query the binding subquery defined from the user's view
  3. After executing a query rewrite.
SELECT * 
FROM StudentView1999
WHERE classNo='CS1601'

--该视图转化为如下查询:

SELECT * 
FROM Student
WHERE year(birthday)=1999 AND classNo='CS1601'

3.3 view updates

  View through the view update instruction to insert, delete and modify the data base tables. Because the view is a virtual table, not the actual data stored, the update of the view, to be converted into a final update to the base table, and therefore, if the view definition comprises the expression, or aggregation operations, eliminating duplicate values or calculation, then You can not view the update operation.
  To view the update operation, which is more limited conditions, to establish the role of view instead of using a view to update the data in the database, but to simplify the user's query, and achieve a certain level of security protection, so try not to view the update operation .

3.4 Delete View

DROP VIEW <viewName> [CASCADE]
发布了50 篇原创文章 · 获赞 38 · 访问量 1万+

Guess you like

Origin blog.csdn.net/weixin_42250302/article/details/103120333