Basic learning of SQL Server database

 

Summary of SQLServer database learning

1. SQL basics
SQL Server2000 installation, configuration, server start, stop, enterprise manager, query analyzer
The first generation database--network database and hierarchical database; the second-generation database--relational database
database (DB ); database management system (DBMS); database system (DBS)
SQL Server 2000 provides different editions: Enterprise Edition, Standard Edition, Personal Edition, Development Edition

Data types in SQL Server: Integer: int, smallint, tinyint, bigint; Floating point numbers: real, float, decimal; Binary: binary, varbinary; Logical: bit; Characters: char, nchar, varchar, nvarchar; Text and graphics: text, ntext, image; Date and time: datetime, smalldatetime; Currency: money , smallmoney

database creation and deletion; database table creation, modification and deletion

Data integrity: Entity integrity: Primary Key, Unique Key, Unique Index, Identity Column; Domain integrity: Default, Check, Foreign Key, Data type, Rule; referential integrity: Foreign Key, Check, Triggers, Procedure; user-defined integrity: Rule, Triggers, Procedure; all column-level and table-level constraints in Create Table

There are five kinds of constraints in SQL Server: Primary Key Constraint, Default Constraint, Check Constraint, Unique Constraint, Foreign Key Constraint. Relational

graph

database Design steps: requirements analysis, conceptual structure design, logical structure design, database physical design, database implementation, database operation and maintenance The connection

between two entities: one-to-one (1:1), one-to-many (1:n ), many-to-many (m:n)

entity relationship model -- ER diagram

Database normalization: simplify the structure of the database to the simplest form; remove redundant columns from the table; identify all data that depends on other databases.

Three normal forms of the database: the first normal form is no repeated columns; the second normal form is that the non-primary attributes are not partially dependent on the primary keyword; the third normal form is that the attributes do not depend on other non-primary attributes 2. The full name of SQL statement SQL is

"
structured Query language (Structured Query Language)"

4 parts of SQL:
data definition language DDL (Data Definition Language) is used to define the structure of data: create, alter, drop.
Data Control Language DCL (Data Control Language) is used to control the access permissions and access rights of database components and other commands: grant, revoke.
Data Manipulation Language DML (Data Manipulation Language) commands used to manipulate data in the database: insert, update, delete.
Data query language DQL (Data Query Language) is used to query the command of data in the database: select.

Operators in SQL: arithmetic operators, bit operators, comparison operators, logical operators, wildcard operators, string concatenation operators, assignment operators 3. Query Simple query, use the TOP clause to sort the query

results
order
by
Conditional query where, use arithmetic expression, use logical expression, use between keyword, use in keyword,
fuzzy query like
use aggregation function in query: sum(x), avg(x), min(x) , max(x), count(x), count(*)
use group by query group by, having clause
distinct keyword
column alias
select top 6 * from sales order by qty desc
select au_id,au_fname,au_lname from authors where state in ('ks','ca','mi')
select au_fname,au_lname,phone from authors where au_id like '72[234]-%'
select type,sum(price),avg(price),count(*) from titles group by type having type in('business','psycheology')


Simple subqueries: nested subqueries, correlated subqueries; the order by clause cannot be used in the select statement of the subquery, and the roder by clause can only sort the final query results.
Nested subquery: In the execution process, the subquery is executed first, and the result obtained by the subquery is not displayed, but passed to the outer query as the condition of the outer query, and then the outer query is executed and the result is displayed.
The execution of a nested subquery does not depend on the outer query, and the subquery is executed only once.
Subqueries with comparison operators, subqueries with in and not in, subqueries with any or all
Correlated subqueries: the subquery is executed once for each row of the outer query, and the outer query refers to the subquery The value of the column is passed to the subquery.
The execution of a correlated subquery depends on the outer query, and the subquery needs to be executed repeatedly.
Correlated subqueries with exists and not exists.
Multi-table join query: inner join (inner join), outer join ((left, right, full) outer join), self join (self join) and cross join (cross join) Create a new table on the query: select into statement
first Create a new table and populate the new table with the results of the query.
Table alias
select coursename from course where courseid in (select distinct courseid from grade where grade>10)
select studname from student where suicide > any (select student from student where class = 'Information Department') and class<>'Information Department'
select studname from student where exists (select * from grade where studid = student.studid and courseid = '01')
select stud1.* from student as stud1 join student as stud2 on stud2.studname = 'mm' and stud1.studsex = stud2 .studsex
select * into girls from student where studsex='m'

4. Views, indexes and transaction
views are virtual tables or query tables derived from one or more data tables (basic tables), which are provided by relational database systems to users An important mechanism for viewing data in a database from multiple angles.
The benefits of the view: it can simplify the user's operation; the view can provide security protection for confidential data.
When a view is created, the name of the view exists in the sysobjects table. Information about columns defined in a view is added to the syscolumns table, and information about view dependencies is added to the sysdepends table. Additionally, the text of the create view statement is added to the syscomments table.
When inserting data into a table through a view, if the insert statement list contains columns that are not selected in the view and columns that do not allow null values, this operation is not allowed.
Create view: create view view_employee as select emp_id, fname, lname from employee
Use view: select * from view_employee
Modify view: alter view view_employee as select emp_id, fname, job_id from employee where job_id>10
Delete view: drop veiw view_employee
view view structure: exec sp_help view_employee
view view definition information: exec sp_helptext 'view_employee'

index provides a column-based or A method for fast access to the data rows of a table by the values ​​of multiple columns. Indexes provide a logical order in the table.
A clustered index sorts and stores data rows within a table based on their key values. When a data table establishes a clustered index with a column as a key, the data rows in the table are stored in the sort order of the column (clustered index key). There can be only one clustered index per table.
Non-clustered indexes have a structure completely independent of data rows, and multiple non-clustered indexes can be established for a table.
Create a clustered index: create clustered index studid_ind on stud (studid)
Create a non-clustered index: create unique index studfullname_ind on stud (fname desc, lname)
Delete the index: drop index stud.studid_ind
View the index on the stud table: exec sp_helpindex stud

transaction is A mechanism is an operation sequence, which includes a set of database operation commands, and all commands submit or withdraw operation requests to the system as a whole.
The characteristics of transactions: Atomicity, Consistenty, Isolation, Durability.
Transaction classification: display transaction, hidden transaction, auto-commit transaction.

Creation, use, modification and deletion of views, indexes and transactions

5. Transact—SQL programming
Global variables: defined and maintained by the system, whose names start with @@ characters
Local variables: defined and assigned by users, whose names start with @ characters
Output statement: print Logic control statement: begin...end ;break ;case ;continue ; goto
; if...else ;return ; e, s), cast() mathematical function: absolute value abs(n), rounded up ceiling(n), rounded down floor(n), specified power power(n, y), rounded round(n, length), find the symbol sign(n), square root sqrt(n) date and time functions: dateadd(datepart,num,date),datediff(datepart,date1,date2),datename(datepart,date),datepart(datepart,date ), getdate(), year(date), month(date), day(date) string functions: lower(e), upper(e), left(e,i), right(e,i), replace( s1, s2, s3) replace 2 in 1 with 3, replicate(e, i) repeat the specified number of times, stuff(s1, start, length, s2) replace the specified position in 1 with 2, substring(expression, start, length)





元数据函数:db_id('database_name'),db_name(datebase_id),object_id('obj_name'),object_name(obj_id),col_length('table','column'),col_name(table_id,col_id)
聚合函数:avg(expr),count(expr),count(*),max(expr),min(expr),sum(expr)
select au_lname,au_fname,contory =
case state
when 'ut' then 'utah'
when 'ca' then 'california'
else 'world'
end,city from authors order by state desc

while(select avg(price) from titles)<30
begin
update titles set price = price * 2
if(select max(price) from titles)>50 break
else continue
end
print '价格太高'

begin
insert into jobs values('a',80,234) else goto M
if @@error<>0 print 'data insertion failed'

end
M: print 'data inserted successfully'

6. Cursor
Cursor is a mechanism that can extract one record at a time from the result set containing multiple data records. Turn batch operations into row operations, and operate on a row in the result set.
declare author_csr cursor read_only for --Define a read-only cursor
select au_fname,au_lname from authors where state = 'ca' order by au_fname,au_lname
declare @lname varchar(20),@fname varchar(20) --Define variable
open author_csr -- Open the cursor
fetch next from author_csr into @lname,@fname --perform a data read operation
while @@fetch_status=0 --loop cursor read data
begin
print 'author name:'+@lname+''+@fname
fetch next from author_csr into @lname,@fname
end
close author_csr -- close the cursor
deallocate author_csr -- release the cursor

7.
Stored procedure Stored procedure (stored procedure) is similar to the function in C language. It is a set of SQL statements to complete a specific function, which is compiled and stored in the database. The user executes the stored procedure by specifying its name and giving parameters.
Commonly used system stored procedures: sp_database, sp_helpdb, sp_renamedb, sp_tables, sp_column, sp_help, sp_helpconstraint, sp_helpindex, sp_stored_procedure, sp_password
Create stored procedures:
create procedure book_num (@book_name varchar(26), @starttime datetime, @endtime datetime, @total int output)
as
select @total=count(jy.askbookid) from book,jyls jy where bookname like @book_name and book.isbn=jy.isbn and jy.starttime>=@starttime and endtime<=@endtime use stored procedure
:
declare @book_name char(26),@total int
set @book_name='object-oriented analysis and design'
exec book_num @book_name,'2007-01-01','2007-11-01',@total output
select @book_name as bookname,@total as num

8. Trigger
A trigger is a special type of stored procedure, which is mainly triggered and executed through practice.
The main function of the trigger is to realize complex referential integrity and data consistency that cannot be guaranteed by the primary key and foreign key. Other functions: strengthen constraints, track changes, cascade operations, stored procedure calls.
SQL Server 2000 supports two types of triggers:
after trigger: the trigger is required to be executed only after a certain operation is performed, and it can only be defined on the table.
instead of trigger: means that the operation defined by it is not executed, but only the trigger itself is executed. It can be defined on the table or on the view, but only one instead of trigger can be defined for the same operation.

How it works:
When the insert trigger is triggered, new data rows are inserted into the trigger table and the inserted table. A trigger checks the inserted table to determine whether or how to execute the trigger action.
When an update statement is executed on a table with a trigger defined, the original row is moved into the deleted table and the updated row is moved into the inserted table. The trigger checks the deleted and inserted tables as well as the updated table to determine if multiple rows were updated and how to execute the trigger action.
When the deleted trigger fires, the rows deleted from the affected tables are placed into a special deleted table.

Reposted from: Micro reading    https://www.weidianyuedu.com

Guess you like

Origin blog.csdn.net/weixin_45707610/article/details/131869064