欢迎进入Windows社区论坛,与300万技术人员互动交流 >>进入 引言 我们先不讲游标的什么概念,步骤及语法,先来看一个例子: 表一 OriginSalary 表二 AddSalary 现在有2张表,一张是OriginSalary表--工资表,有三个字段0_ID 员工号(NVARCHAR)、O_Name员工姓名
欢迎进入Windows社区论坛,与300万技术人员互动交流 >>进入
引言
我们先不讲游标的什么概念,步骤及语法,先来看一个例子:


表一 OriginSalary 表二 AddSalary
现在有2张表,一张是OriginSalary表--工资表,有三个字段0_ID 员工号(NVARCHAR)、O_Name员工姓名(NVARCHAR)、O_Salary工资(FLOAT)。
另一张表AddSalary表―加薪表。有2个字段,O_ID员工号、A_Salary增加工资。两张表的O_ID是一一对应的,现在求将加薪的工资+原来的工资=现在的工资,也就是O_Salary=O_Salary+A_Salary,修改表OriginSalary的工资字段。
对于一些不熟悉游标的程序员来说,这个并不是什么很难的问题,这个问题用程序来实现可能也很简单。我先说说,用ASP.NET程序解决这个问题的思路:
1. 先获得表OriginSalary的记录数,写个循环。
2. 写SQL语句“select * from dbo.OriginSalary as A left join dbo.AddSalary as B on A.O_ID=B.O_ID”获得视图。
3. 使用Dataset获得O_Salary=O_Salary+A_Salary。
4. 写UPDATE语句“update OriginSalary set O_Salary=”相加的值” where O_ID=”获得值”
5. 循环3次,完成此功能。
还有一种方法就是写存储过程,在这里我就不列出来了。
我想大家在学习游标之前好好想想这个问题,及一些批量处理的例子。可能有的人会说:“难道数据库不能一行一行的处理数据吗?将表AddSalary的数据逐行的取出,然后表 OriginSalary数据逐行的修改?”答案当然是肯定。这就是游标概念。接下来的一章我们会好好的讲讲什么是游标?我会用游标来解决刚才留给大家的问题。
1.1游标的概念
游标(Cursor)它使用户可逐行访问由SQL Server返回的结果集。使用游标(cursor)的一个主要的原因就是把集合操作转换成单个记录处理方式。用SQL语言从数据库中检索数据后,结果放在内存的一块区域中,且结果往往是一个含有多个记录的集合。游标机制允许用户在SQL server内逐行地访问这些记录,按照用户自己的意愿来显示和处理这些记录。
1.2 游标的优点
从游标定义可以得到游标的如下优点,这些优点使游标在实际应用中发挥了重要作用:
1)允许程序对由查询语句select返回的行集合中的每一行执行相同或不同的操作,而不是对整个行集合执行同一个操作。
2)提供对基于游标位置的表中的行进行删除和更新的能力。
3)游标实际上作为面向集合的数据库管理系统(RDBMS)和面向行的程序设计之间的桥梁,使这两种处理方式通过游标沟通起来。
1.3 游标的使用
讲了这个多游标的优点,现在我们就亲自来揭开游标的神秘的面纱。
使用游标的顺序: 声名游标、打开游标、读取数据、关闭游标、删除游标。
1.3.1声明游标
最简单游标声明:DECLARE CURSOR FOR;
其中select语句可以是简单查询,也可以是复杂的接连查询和嵌套查询
例子:[已表2 AddSalary为例子]
Declare mycursor cursor for select * from AddSalary
这样我就对表AddSalary申明了一个游标mycursor
【高级备注】
DECLARE [INSENSITIVE] [SCROLL] CURSORFOR
这里我说一下游标中级应用中的[INSENSITIVE]和[SCROLL]
INSENSITIVE
表明MS SQL SERVER 会将游标定义所选取出来的数据记录存放在一临时表内(建立在tempdb 数据库下)。对该游标的读取操作皆由临时表来应答。因此,对基本表的修改并不影响游标提取的数据,即游标不会随着基本表内容的改变而改变,同时也无法通过游标来更新基本表。如果不使用该保留字,那么对基本表的更新、删除都会反映到游标中。
另外应该指出,当遇到以下情况发生时,游标将自动设定INSENSITIVE 选项。
a.在SELECT 语句中使用DISTINCT、 GROUP BY、 HAVING UNION 语句;
b.使用OUTER JOIN;
c.所选取的任意表没有索引;
d.将实数值当作选取的列。
SCROLL
表明所有的提取操作(如FIRST、 LAST、 PRIOR、 NEXT、 RELATIVE、 ABSOLUTE)都可用。如果不使用该保留字,那么只能进行NEXT 提取操作。由此可见,SCROLL 极大地增加了提取数据的灵活性,可以随意读取结果集中的任一行数据记录,而不必关闭再
重开游标。
1.3.2 打开游标
非常简单,我们就打开刚才我们声明的游标mycursor
OPEN mycursor
1.3.3读取数据
FETCH [ NEXT | PRIOR | FIRST | LAST] FROM { 游标名 | @游标变量名 } [ INTO @变量名 [,…] ]
参数说明:
NEXT 取下一行的数据,并把下一行作为当前行(递增)。由于打开游标后,行指针是指向该游标第1行之前,所以第一次执行FETCH NEXT操作将取得游标集中的第1行数据。NEXT为默认的游标提取选项。
INTO @变量名[,…] 把提取操作的列数据放到局部变量中。列表中的各个变量从左到右与游标结果集中的相应列相关联。各变量的数据类型必须与相应的结果列的数据类型匹配或是结果列数据类型所支持的隐性转换。变量的数目必须与游标选择列表中的列的数目一致。
现在我们就取出mycursor游标的数据吧!
当游标被打开时,行指针将指向该游标集第1行之前,如果要读取游标集中的第1行数据,必须移动行指针使其指向第1行。就本例而言,可以使用下列操作读取第1行数据:
Eg: Fetch next from mycursor 或则 Fetch first from mycursor
这样我就取出了游标里的数据,但是光光这样可不够,我们还需要将取出的数据赋给变量
//声明2个变量
declare @O_ID NVARCHAR(20)
declare @A_Salary float
//将取出的值传入刚才声明的2个变量
Fetch next from mycursor into @ O_ID,@ A_Salary
1.3.4关闭游标
CLOSE mycursor
1.3.5删除游标
DEALLOCATE mycursor
1.3.6 实例训练
如上我介绍完了游标使用的5个步骤,那现在我们就来上上手,练习用游标取出表2 AddSalary的数据。
为了运行我们自己创建的游标,我们将游标写在存储过程里,方便我们看到游标的整个使用过程。
在sqlserver2000中新建一个存储过程:
CREATE PROCEDURE PK_Test
AS
//声明2个变量
declare @O_ID nvarchar(20)
declare @A_Salary float
//声明一个游标mycursor,select语句中参数的个数必须要和从游标取出的变量名相同
declare mycursor cursor for select O_ID,A_Salary from AddSalary
//打开游标
open mycursor
//从游标里取出数据赋值到我们刚才声明的2个变量中
fetch next from mycursor into @O_ID,@A_Salary
//判断游标的状态
//0 fetch语句成功
//-1 fetch语句失败或此行不在结果集中
//-2被提取的行不存在
while (@@fetch_status=0)
begin
//显示出我们每次用游标取出的值
print '游标成功取出一条数据'
print @O_ID
print @A_Salary
//用游标去取下一条记录
fetch next from mycursor into @O_ID,@A_Salary
end
//关闭游标
close mycursor
//撤销游标
deallocate mycursor
GO
通过上面的注释,我想大家都明白了整个游标的创建过程了吧。但是我们现在还是一个抽象的了解,我们学任何知识,都要用于实践,这样才能使抽象的东西变的具体。
[1] [2]

ACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.

MySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.

MySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.

MySQL is an efficient relational database management system suitable for storing and managing data. Its advantages include high-performance queries, flexible transaction processing and rich data types. In practical applications, MySQL is often used in e-commerce platforms, social networks and content management systems, but attention should be paid to performance optimization, data security and scalability.

The relationship between SQL and MySQL is the relationship between standard languages and specific implementations. 1.SQL is a standard language used to manage and operate relational databases, allowing data addition, deletion, modification and query. 2.MySQL is a specific database management system that uses SQL as its operating language and provides efficient data storage and management.

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor