On the SQL Server query optimization and transaction processing

Before we understand the usage of a variety of simple queries, but will be used in some of the more advanced data processing and query in the actual development, including indexes, views, stored procedures and triggers . Thus better able to achieve operation of the database, diagnosis and optimization.

What is indexing it, indexing method is an internal SQL Server setup data, he provided a way for SQL Server to orchestrate routing query data, so as to achieve to improve the retrieval speed of the database by using the index to improve database performance.

Index is divided into the following six categories:
1, the only index: the index does not allow two rows have the same value, create a unique constraint, it will automatically create a unique index.
2, the primary key index: the index is a special kind of unique, automatically created when the primary key index tables define a primary key, he requires that each primary key values are unique.
3, the clustered index: the index in the aggregate, the physical order of the rows in the table and the logical index key value in the same order. (Note: A table can contain only one clustered index)
4, non-clustered index: based on the index page, you can find the location of stored records from the index when querying data, clustered index data faster than non-clustered index access speed.
5, a composite index: a plurality of columns can be combined into an index.
6, full-text index: is a special type of functionality based on the index mark is mainly used in a large number of the text search string.
:( can not create a unique index duplicate values)

create unique nonclustered index U_cardID 
on TStudent (cardID)

View index on the table:

Select * from sys.sysindexes 
where id=(select object_id from sys.all_objects where name='Tstudent')

Query the specified index:

SELECT * FROM xueyuan
    WITH (INDEX = IX_name)
    WHERE 学员姓名 LIKE '孙%'

View is a virtual table, usually as a sub-table from one or more rows or columns of sets created.
View action is:
1, filtering the data in the table
2, to prevent unauthorized users from accessing sensitive data
3, a plurality of physical data table abstract data table is a logical
user benefits is: result is more readily understood, the data obtained more likely to
benefit to developers is: to limit data retrieval easier and more convenient to maintain the application
Note:
1, each view can use multiple tables
2, similar to the query, a view can be nested another view, the most Do not exceed three good
3, attempts to define the select statement can not include the following:

  • ORDER BY clause, unless the select list in the select statement also has a TOP clause
  • INTO keyword
  • References a temporary table or table variable
    to create a view:
    create view netstudent
    as
    select Sname,sex,Class from dbo.TStudent where Class='网络班'

    Find data from a view:

    select * from netstudent 
    where sex='男'

    Create a view, change the header columns:

    create view V_Tstudent1
    as
    select StudentID  学号,Sname 姓名,sex  性别,cardID  ×××号码,Birthday  生日,Class  班级 from dbo.TStudent
    select * from V_Tstudent1

    What is a stored procedure, the stored procedure is a precompiled collection of SQL statements and control statements, stored in the database, the application can be called.
    Why need a stored procedure, it is because sent from the client (client) via the network to the server (server) SQL code and execution is not appropriate, resulting in data may leak unsafe impression of the running performance of the application, and network traffic Big.
    The advantages of using stored procedure is:
    1, modular design
    2, execution speed, high efficiency
    3, reducing network traffic
    4, has a good safety
    storage process is divided into two categories: systems stored procedure stored procedures and user-defined
    system stored procedures:
    a set of pre-compiled T-SQL statement that provides a mechanism to update the table management database and serves to retrieve the shortcut information from the system tables
    that begin with "sp", stored in the Resource database, common system stored procedures are as follows:
    On the SQL Server query optimization and transaction processing
    using T-SQL syntax statement calls the stored procedure execution:

    EXEC [UTE] 存储过程名 [参数值]
    EXEC为EXECUTE的简写

    Common system stored procedure usage:

    exec  sp_databases      --列出当前系统中的数据库
    exec  sp_renamedb  'mybank','bank'   --改变数据库名称(单用户访问)
    use  MySchool
    go 
    exec sp_tables                       --当前数据库中可查询对象的列表
    exec sp_columns student            --查看表student中列的信息
    exec  sp_help student               --查看表student的所有信息
    exec sp_helpconstraint student       --查看表student表的约束
    exec sp_helptext view_student_result   --查看视图的语句文本
    exec sp_stored_procedures      --返回当前数据库中的存储过程列表

    Depending on the role of system stored procedures, system stored procedures can be divided into different classes, SQL Server extended stored procedures is to provide various types of system stored procedure in a class.
    Allows the use of other programming languages (such as C #) to create an external stored procedures, provide examples from SQL Server to external programs interface
    begins with "xp", DLL form alone
    a common extended stored procedure xp_cmdshell his to be completed by DOS command some operations, it is exemplified by its
    syntax is:
    **EXEC xp_cmdshell DOS命令 [NO_OUTPUT]**
    part of the general xp_cmdshell as a server security configuration is turned off, you should use the following statement to enable:

    exec sp_configure  'show advanced options', 1   --显示高级配置选项(单引号中的只能一个空格隔开)
    go 
    reconfigure                                    --重新配置
    go 
    exec sp_configure  'xp_cmdshell',1                 --打开xp_cmdshell选项
    go
    reconfigure                                    --重新配置

    After enabling the implementation of the following statement:

    exec  xp_cmdshell  'mkdir  c:\bank',no_output  --创建文件夹c:\bank
    exec  xp_cmdshell  'dir c:\bank\'               --查看文件 

    User-defined stored procedure:
    a complete storage process includes

  • Input and output parameters
  • Executed in a stored procedure T-SQL statement
  • Return value stored procedures
    create a storage process SSMS
    a complete storage process includes the following three parts:
    1, input and output parameters
    2, performed in the storage process T-SQL statement
    3, the stored procedure return value
    using T-SQL statement creating a stored procedure syntax is:
    CREATE  PROC[EDURE]  存储过程名 
        [ {@参数1  数据类型 } [= 默认值] [OUTPUT],
           ……,
          {@参数n  数据类型 } [= 默认值] [OUTPUT]
        ]
    AS
        SQL语句

    Syntax delete stored procedure is as follows:
    DROP PROC[EDURE] 存储过程名
    For example, the average score for query the course of a recent examination:

    use schoolDB
    go
    if exists  (select  *  from  sysobjects where name='usp_getaverageresult')
    drop  procedure  usp_getaverageresult
    go
    create  procedure  usp_getaverageresult
    as
    declare  @subjectid  nvarchar(4)
    select  @subjectid=subjectid  from  dbo.TSubject where subJectName='网络管理'
    declare  @avg decimal (18,2)
    select  @avg=AVG(mark)  from  dbo.TScore where subJectID=@subjectid
    print  '网络管理专业平均分是:'+convert(varchar(5),@avg)
    go

    After the completion of the implementation of write: exec usp_getaverageresult
    Trigger:
    is increasing in the table, the stored procedure is automatically executed when change or delete operations
    than with the more complex constraint CHECK constraint to enforce business rules can be defined
    by a trigger event to be executed with
    trigger is divided into three categories:
    the iNSERT triggers: trigger when inserting data into the table
    uPDATE trigger: updating the table when a column, multi-row trigger
    dELETE triggers: trigger when deleting records in the table
    inserted and deleted tables
    by the systems management, stored in memory rather than in a database, so you can not directly modify its
    temporary storage to modify information in the data row of the table
    when the trigger is completed, they are also deleted
    On the SQL Server query optimization and transaction processing

Trigger role is to: strengthen the constraints, track changes, run cascading
create a trigger syntax is:

create trigger *triggername(触发器名)*
on *tablename(表名)*
[with encryption]
for {[delete,insert,update]}
as SQL 语句

Example: create a trigger, prohibit modify data in the table admin

create  trigger  reminder
on  admin
for  update
as
print  '禁止修改,请联系DBA'
rollback  transaction
go

And then execute the statement to see the error message:

update Admin set  LoginPwd='123'  where  LoginId='benet'
select  *  from  Admin

On the SQL Server query optimization and transaction processing
Affairs (generally used in banking transactions in this regard, such as transfers)
is an indivisible logical unit of work
a set of commands to either perform or not to perform
a series of operations of transactions executed as a single logical unit of work, a logical unit must It has four properties: atomicity, consistency, isolation, durability , these properties commonly referred to as the ACID .
For example, to transfer whichever
first creates a table named bank:
On the SQL Server query optimization and transaction processing
for Check constraints Currentmoney column:
On the SQL Server query optimization and transaction processing
Insert two data:

INSERT INTO bank(customerName,currentMoney) VALUES('张三',1000)
INSERT INTO bank(customerName,currentMoney) VALUES('李四',1)

Then enter the code transaction execution:

select customername,currentmoney as 转帐事务前的余额 from bank    --查看转账事务前的余额
go
begin transaction     -- 开始事务(指定事务从此开始,后续的T-SQL语句是一个整体)
declare @errorsum int   --定义变量,用于累计事务执行过程中的错误 
set @errorsum=0    --初始化为0,即无错误
update bank set currentmoney=currentmoney-1000  --转账,张三账户少1000 李四账户多1000 
where customername='张三'
set @errorsum=@errorsum+@@ERROR    --累计是否有错误
update bank set currentmoney=currentmoney+1000
where customername='李四'
set @errorsum=@errorsum+@@ERROR   --累计是否有错误
select customername,currentmoney as 转帐事务过程中的余额 from bank    --查看那转账过程中的余额
if @errorsum<>0  --如果有错误
begin 
print '交易失败,回滚事务'
rollback transaction 
end
else 
begin 
print '交易成功,提交事务,写入硬盘,永久的保存'
commit transaction 
end
go
select customername,currentmoney as 转帐事务后的余额 from bank   --查看转账后的余额

Transfer failed:
On the SQL Server query optimization and transaction processing
Transfer Success:
On the SQL Server query optimization and transaction processing
Lock :
multiple users can simultaneously manipulate data in the same database, data inconsistencies can occur, the lock is to be able to ensure the integrity and consistency of the data in a multi-user environment
three modes locks:
shared lock (S locks): for reading resource lock applied.
Exclusive lock (X lock): and other locks are not compatible, including other exclusive lock.
Update lock (U lock): U S latch lock and can be seen in conjunction with X lock for the update data.
View Lock:
Use sys.dm_tran_locks dynamic management view
using Profiler to capture the information locked
deadlock
deadlock is essentially a stalemate, the body is composed of a plurality of resource contention caused.
Deadlock conditions are formed:
1, mutually exclusive conditions: the resource is exclusive body
2, request wait condition
3, not deprivation
4, loop wait condition
deadlock prevention:
destruction exclusive conditions
destruction request wait condition
destruction not deprivation

Guess you like

Origin blog.51cto.com/14227204/2416342