Chapter VIII, database programming technology background

Chapter VIII, database programming technology background

Summary:

1, grasp the definition and use of stored procedures

2, able to create and use user-defined function

3, grasp the definition and use of triggers

4, grasp the definition and use of the cursor

Section Stored Procedures

1, the basic concept

When you write code using the T-SQL language, there are two ways to store and execute the code:

(1) is stored in the client code is issued to the operation request through the client program or the DBMS SQL commands, the DBMS returns the result to the user program.

(2) in the form of subroutine program modules may be stored in a database, for the user to have permission by calling repeatedly executed.

Stored Procedures : the memory for user programs, all subroutine calls in the database.

Storage process is divided into three categories

System Stored Procedures

User-defined stored procedure (if not stated, then the default)

Extended stored procedure

User-defined stored procedure

It is created by the user and can complete a particular function (such as query data required by the user information) stored procedure. This section describes in detail the user-defined stored procedures.

The following procedure shall be stored three user-defined stored procedures:

Extended stored procedure

Is SQL Server can dynamically load and execute a dynamic link library (DLL). Extended stored procedure allows you to use a programming language like C to create your own external routines. For the user, the stored procedure and extended general storage process, the same method is also performed.

The advantages of stored procedures

① high efficiency. (All commands are processed in batch mode)

② enhance the sharing and reuse of code.

③ use of stored procedures can reduce network traffic.

④ use stored procedures to ensure safety.

The main way ⑤ in large databases, applications that access the database stored procedures.

⑥ stored procedures can be executed automatically at system startup.

2, create, execute, and delete stored procedures

Stored procedure definition comprises two main components:

① explain the procedure name and its parameters;

Process ② body (which includes Transact-SQL statements executed during the operation). Creating a stored procedure syntax is as follows:

Create a stored procedure

CREATE PROCEDURE procedure_name [;number] /*定义过程名
[{@parameter data_type}                   /*定义参数的类型
[VARYING][ = default][OUTPUT]]            /*定义参数的属性
[,…n1]
[WITH {RECOMPILE | ENCRYPTION | RECOMPILE,ENCRYPTION}]
[FOR REPLICATION]                         /*执行的操作
AS sql_statement[,…n2]
/**
*RECOMPILE 是否重编译
*ENCRYPTION 是否加密
*FOR REPLICATION 是否不执行复制的存储过程
*/

Execute stored procedures

EXEC[UTE]
{   //返回状态 
    [@return_status = ]
    //procedure_name,存储过程的组名 
    //
   { procedure_name[;number] | @procedure_name_var}
   [ @parameter = ] { value | @variable[OUTPUT] | [DEFAULT]}
   [,…n]
   [WITH RECOMPILE]
}

[Example 1]

The establishment of an inquiry Region purchased the unit price higher than the price of goods specified customer purchase information, customer name lists, purchase trade name, price, date of purchase, membership points, the region where the default is "Yuelu District"

CREATE PROCEDURE p_custbuy
@area varchar(20)=‘长沙岳麓区’,@Price money
AS
SELECT……FROM……JOIN……
WHERE Address=@area AND SaleUnitPrice>@Price
//执行:
EXEC  p_custbuy @Price=1000

[Example 2]

The number of customers to establish a statistical Region and to specify gender and average age of stored procedures, and statistical results are returned as an output parameter.

CREATE PROCEDURE p_custcout @area VARCHAR (20) , @sex CHAR @count INT output @avg_age INT output AS 
SELECT 
  @count = COUNT(*),
  @ave_age = AVG(YEAR(GETDATE ()) - YEAR(BIRTHDATE)) 
FROM
  Table_Customer 
WHERE Address = @area 
  AND Sex = @sex / / 执行: DECLARE @x INT,
  @y INT EXEC p_custcount ‘长沙岳麓区’,‘F’,
  @x output, @y output 
  SELECT 
    @x AS 人数, @y AS 平均年龄 

Delete stored procedure

DROP PROCEDURE [PROCEDURE_NAME]

Example:

DROP PROCEDURE p_custbuy
DROP PROCEDURE p_custcout
DROP PROCEDURE p_update

Section User-Defined Functions

User-defined functions:

  Function similar to the programming language, and stored procedures similar structure, but the function must have a RETURN clause, for the function return value.

Two types of user-defined functions:

  Scalar and table-valued functions. The former returns a single data value, table valued function returns a table.

1, to create and call a scalar function

//定义标量函数:
CREATE  FUCTION ……RETURNS return_data_type
AS 
BEGIN
//【函数体】
  RETURN scalar_expression
END

[Example]

Create a query specified categories of goods scalar function of the number of types of goods.

CREATE FUCTION dbo.f_GoodsCount (@class VARCHAR (10)) RETURN INT AS 
BEGIN
  DECLARE @x INT 
  SELECT 
    @x = COUNT(*) 
  FROM
    Table_GoodsClass a 
    JOIN Table_Goods b 
      ON a.GoodsClassID = b.GoodsClassID 
  WHERE GoodsClassName = @class RETURN @x 
  END 

Call the scalar function:

note:

The owner needs to provide the function name and the function name when you call;

It can be called at any SQL statement appears in the expression of the same type of scalar functions.

[Example]

Query "clothing" commodity name and the number of species

SELECT GoodsName AS 商品名,dbo.f_GoodsCount(‘服装’)AS 种类数
FROM……WHERE……

2, create and invoke inline table-valued function

Creating an inline table-valued function:

CREATE FUCTION ……RETURNS TABLE
AS 
RETURN [(]select_stmt[)]

Parameters: select_stmt SELECT statement defined within a single table with the value of the return value of the function; function does not return a value variable table, there is no function body, only returns a query result.

Inline table-valued function calls:

Use inline table valued function is similar to the view, which acts view parameters.

[Example]

Create a query name specified categories of goods and inline table-valued function unit price.

CREATE FUCTION f_GoodsInfo (@class CHAR(10)) RETURNS TABLE AS RETURN 
(SELECT 
  GoodName,
  SaleUnitPrice 
FROM
  Table_GoodClass a 
  JOIN Table_Goods b 
    ON a.GoodsClassID = B.GoodsClassID 
WHERE GoodClassName = @class) 
/ / 调用: 
SELECT 
  * 
FROM
  dbo.f_GoodsInfo (‘服装’)

3, to create and call a multi-statement table-valued function

CREATE FUCTION ……RETURNS @return_variable TABLE<table_type_definition定义返回的表结构>
AS 
BEGIN
【函数体:SQL语句】
 RETURN 
END

Call to build a multi-statement table-valued function: use the SELECT FROM clause.

[Example]

Multi-statement table-valued function to create a query specified categories of goods name, price, date of manufacture and the type of merchandise.

CREATE FUCTION f_GoodsDatails (@class VARCHAR (20)) RETURNS @f_GoodsDatails TABLE( 商品名 varchar(50), 单价 money, 生产日期 datetime, 种类数 int) AS 
BEGIN
  INSERT INTO @f_GoodsDatails 
  SELECT 
    GoodName,
    SaleUnitPrice,ProductionDate,dbo.f_GoodsDatails (@class) 
  FROM
    Table_GoodClass a 
    JOIN Table_Goods b 
      ON a.GoodsClassID = B.GoodsClassID 
  WHERE GoodClassName = @class) RETURN 
  END 
  //调用:
  SELECT * FROM dbo.f_GoodsDatail(‘服装’)

4, delete user-defined functions

DROP FUNCTION

Examples

DROP FUNCTION f_GoodsCount

DROP FUNCTION f_GoodsInfo

DROP FUNCTION f_GoodsDatails

The third flip-flop

1, the basic concept

  Trigger: Special stored procedure, when the data table is UPDATE, INSERT, DELETE operation triggered automatically performed, and commonly used in business rules to ensure data integrity, the ability to enhance data integrity constraints.

SQL Server 2008 supports three types of triggers:

  DML (Data manipulation due), the DDL (data definition language), login trigger.

Applications:

  1. CHECK constraints than the completion of more complex data constraints (only be achieved between the value of the same table column constraints).

  2. Ensure database performance and maintenance of non-standardized data.

  3. You can implement complex business rules.

  4. Assess the state of the table before and after a data modification and take countermeasures.

2, create a trigger

CREATE TRIGGER trigger_name ON 
{ table | view }
[WITH ENCRYPTION]
{ FOR | AFTER | INSTEAD OF } 
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] 
[ DELETE ] }
AS 
sql_statement[…n] 

Parameter Description:

FOR or AFTER: After the trigger type, operation, inspection after the completion of the constraints triggered.

INSTEAD OF: pre-trigger type, data manipulation statements define up to a trigger. Rather than initiate execution of a trigger statement. If you need to satisfy the constraint integrity performs data operations.

note

  A table can be built a plurality of flip-flops, each flip-flop is triggered by the three operations. ALTER create multiple triggers on the same type of operation, the establishment of a INSTEAD OF trigger on the same type of operation.

All changes and build databases and database objects statement, DROP statements are not allowed in a trigger used.

  Triggers do not return any results.

There are two tables in the trigger logic

instead and deleted

instead save the data before insertion

The deleted data is saved after the deletion

[Example 1]

Maintain the integrity of the value of the trigger different columns. Guarantee "product list" column values ​​in the unit price column values ​​and "commodity price changes" in the same unit price.

CREATE TRIGGER UnitPriceConsistent 
ON Table_PriceHistory FOR 
INSERT,
UPDATE AS DECLARE 
  @NewPrice money 
  SELECT 
    @NewPrice = SaleUnitPrice 
  FROM
    inserted 
    UPDATE 
      Table_Goods 
    SET
      SaleUnitPrice = @NewPrice 
    WHERE GoodsID IN 
      (SELECT 
        GoodsID 
      FROM
        inserted)

[Example 2]

Create a trigger only allows to delete the membership card points below the 500 points of customer records.

CREATE TRIGGER DeleteCust 
ON Table_Customer INSTEAD OF 
DELETE AS IF NOT EXISTS 
  (SELECT 
    * 
  FROM
    deleted 
  WHERE CardID IN 
    (SELECT 
      CardID 
    FROM
      Table_Card 
    WHERE Score >= 500)) 
  DELETE 
  FROM
    Table_Customer 
  WHERE CardID IN 
    (SELECT 
      CardID 
    FROM
      deleted)

E: \ User \ shaoyayu \ 2020-2021 semester learning materials \ three computer database \ 38468444 \ 18 \ 64

3, delete the trigger

DROP TRIGGER

Examples

DROP TRIGGER OperateCon

DROP TRIGGER UnitPriceConsistent

DROP TRIGGER DeleteCust

Section IV cursor

Cursor: enabling the progressive processing of the SELECT result set.

1, the composition of the cursor

  Cursor result set (SELECT returns the result set) to the current cursor row pointer (points to a row in the result set)

  Features: locating a particular row; from the current position of the search line or lines; supporting the current line data modification; provides different levels of visibility support modify the results

2, use the cursor

(1) Declare the cursor

  ISO standard syntax: DECLARE cursor_name [1] CURSOR FOR select_statement [2]

  Parameters: [1] INSENSTITIVE: creates a temporary copy of a temporary table, otherwise the basic table; SCROLL: range, otherwise only supports NEXT; [2] READ ONLY: prohibits updates UPDATE Updates the specified column or columns all.

(2) open the cursor

  OPEN cursor_name

(3) Data Extraction

  FETCH [1]FROM cursor_name [INTO @ variable_name[,…n]]

(4) Close the cursor

  CLOSE cursor_name

   It can be opened again.

(5) release the cursor

  DEALLOCATE cursor_name

  Release all resources allocated to the cursor.

3, cursor sample

 For Table_Customer table, define a query "Yuelu District" name "King" of the customer name and email cursors, cursors and output the results.

DECLARE @cn VARCHAR (10 @cn VARCHAR (50) DECLARE Cname_cursor CURSOR FOR 
SELECT 
  Cname,
  Email 
FROM
  Table_Customer 
WHERE Cname LIKE ‘王 % ’AND Address LIKE ‘长沙岳麓区’ OPEN Cname_cursor FETCH NEXT 
FROM
  Cname_cursor INTO @cn,
  @Email 
  WHILE
    @@ FETCH_STATUS = 0 
    BEGIN
      PRINT’顾客姓名’ + @cn + ‘,邮箱:’ + @Email FETCH NEXT 
FROM
  Cname_cursor INTO @cn,
  @Email 
END CLOSE Cname_cursor DEALLOCATE Cname_cursor 

example

1、在SQL Server 2008中,对于更新操作的触发器,系统将产生2张逻辑工作表,其中存放更新前数据的逻辑工作表是(  )。
答案:DELETE 
更新就是
1、删除原数据
2、插入数据
2、删除用户自定义的函数使用(  )语句来实现。
答案:DROP FUNCTION
3、设在数据库应用系统设计与实现过程中有下列活动:
Ⅰ. 创建触发器
Ⅱ. 定义事务隔离性级别
Ⅲ. 数字签名
Ⅳ. 定义主码
上述活动中,用于数据库的完整性保护的是(  )
A.仅Ⅰ和Ⅳ          B.仅Ⅰ和Ⅱ
C.仅Ⅲ和Ⅳ          D.仅Ⅱ和Ⅲ
答案:B
4、利用游标机制可以实现对查询结果集的逐行操作。下列关于SQL Server 2008中游标的说法中,错误的是(  )
A. 每个游标都有一个当前行指针,当游标打开后,当前行指针自动指向结果集的第一行数据
B.如果在声明游标时未指定INSENSITIVE选项,则已提交的对基表的更新都会反映在后面的提取操作中
C.当@@FETCH_STATUS=0时,表明游标当前行指针已经移出了结果集范围
D.关闭游标之后,可以通过OPEN语句再次打开该游标
答案:C
5、在SQL Server 2008中,用于判断游标数据提取状态的全局变量是(  )。
答案:@@FETCH_STATUS
6、设在SQL Server 2008某数据库中有按如下格式定义的存储过程首部:
CREATE PROC P1
@x int, @y int, @z int output AS ...
请补全下列调用该存储过程的语句。
DECLARE @S int
EXEC P1 20, 30, @S  (  )
答案:output  
7、在SQL Server 2008中,设有教师表(教师号, 姓名, 所在部门号, 职称)和部门表(部门号, 部门名, 高级职称人数)。请编写满足下列要求的后触发型触发器(设触发器名字为tri_zc)。
  每当在教师表中插入一名具有高级职称("教授"或"副教授")的教师时,或者将非高级职称教师的职称更改为高级职称时,均修改部门表中相应部门的高级职称人数。(假设一次操作只插入或更改一名教师的职称) )

【解题思路】创建触发器的SQL语句为:CREATE TRIGGER
  根据原题要求,insert触发器会在inserted表中添加一条刚插入的记录,update触发器会在更新数据后将更新前的数据保存在deleted表中,更新后的数据保存在inserted表中。在教师表中插入或者更新的时候,都会在inserted表中增加一条记录,所以只需在触发器查询inserted表中查询有没有"教授"或者"副教授"的记录,如果有,则触发修改相应部门的高级职称人数即可。
//答案
CREATE TRIGGER tri_zc 
ON 教师表 AFTER INSERT,
UPDATE AS 
  BEGIN
    DECLATE @zc VARCHAR (10),
    @dept VARCHAR (30) 
    SELECT 
      @dept = 所在部门号, @2 c = 职称 
    FROM
      inserted IF @zc = ′教授′ 
      OR ′副教授′ 
      UPDATE 
        部门表 
      SET
        高级职称人数 = 高级职称人数 + 1 
      WHERE 部门号 = @dept 
      END 
8、设在SQL Server 2008某数据库中有商品表和销售表,两个表的定义如下:
CREATE TABLE 商品表 (
  商品号 CHAR(10) PRIMARY KEY,
  商品名 VARCHAR (40),
  类别 VARCHAR (20),
  进货单价 INT
);
CREATE TABLE 销售表 (商品号 CHAR(10),
  销售时间 DATETIME,
  销售数量 INT,
  销售单价 INT,
PRIMARY KEY (商品号, 销售时间))

下面是一个用户定义的多语句表值函数,它接受类别作为输入参数,返回该类别下的每种商品在2012年的销售总利润,并将结果按照销售总利润的降序输出。请补全该函数定义代码。 

CREATE FUNCTION f_Profit (@lb char(10))  【1】@ProfitTable【2】(
商品号 char(10),
总利润 int )
AS
BEGIN
  INSERT INTO @ProfitTable  
【3】
【4】
END
第一空:RETURNS
第二空:table
第三空:
a 
SELECT 
  a.商品号,
  SUM(
    销售数量 * (销售单价 - 进货单价)
  ) AS总利润 
FROM
  销售表 a JOIN商品表b 
  ON a.商品号 = b.商品号 
WHERE a.商品号 IN 
  (SELECT 
    商品号 
  FROM
    商品表 
  WHERE 类别 = @lb) 
GROUP BY a.商品号ORDER BY 总利润 DESC 

第四空:RETURN@Rrofit Table

Guess you like

Origin www.cnblogs.com/shaoyayu/p/12424136.html