search
HomeDatabaseMysql Tutorial 第三章 T-SQL 编程

3.1 使用变量 变量是可以存储数据值的对象。可以使用局部变量向SQL语句传递数据。在T-SQL中执行一批SQL语句时,可以声明许多变量以便临时使用。声明变量以后,可以在批处理中用一条T-SQL语句设置该变量的值。该批处理中的下一条语句可以从该变量中检索数值,

3.1 使用变量

  变量是可以存储数据值的对象。可以使用局部变量向SQL语句传递数据。在T-SQL中执行一批SQL语句时,可以声明许多变量以便临时使用。声明变量以后,可以在批处理中用一条T-SQL语句设置该变量的值。该批处理中的下一条语句可以从该变量中检索数值,并给出结果。

  T-SQL中的变量分为局部变量和全局变量。局部变量的使用也是先声明,再赋值。而全局变量右系统定义和维护,我们可以直接使用,但一般不自定义全局变量。

3.1.1 局部变量

  局部变量的名称必须以标记@作为前缀。

  声明局部变量的语句如下:

  Declare @variable_name DataType

  其中, variable_name 为局部变量的名称,DataType为数据类型。

  例如:

  Declare @name varchar(8)     --- 声明一个存放学员姓名的变量name,最多可以存储8个字符

  Declare @seat int         --- 声明一个存放学员座位号的变量seat

  局部变量的赋值有两种方法:使用SET 语句或 Select 语句。

  语法:

  Set @variable_name = value

  或

  Select @variable_name = value

  假定使用insert语句,已向表stuInfo中插入了如下几条测试数据。

stuName stuNo stuSex stuAge stuSeat stuAddress

张秋丽 s25301 男 18 1 北京海淀

李文才 s25302 男 31 3 地址不详

李斯问 s25303 女 22 2 河南洛阳

欧阳俊雄 s25304 男 28 4 新疆

  示例1

  /*-- 查找'李文才'的信息 --*/

  Declare @name varchar(8)  ---学员姓名

  set @name = '李文才'     ---使用set赋值

  select * from stuInfo where stuName = @name

 

  /*-- 查找'李文才'的左右同桌 --*/

  Declare @seat int   --- 座位号

  Select @seat = stuSeat from stuInfo where stuName = @name   --- 使用Select赋值

  Select * from stuInfo where (stuSeat = @seat + 1) or (stuSeat = @seat - 1)

  从示例1可以看出,局部变量可用于在上下语句中传递数据(如本例的座位号@seat)。

  set 赋值语句一般用于赋给变量指定的数据常量,如本例“李文才”。

  Select 赋值语句一般用于从表中查询数据,然后再赋给变量。需要注意的是,Select 语句需要确保筛选的记录不多于一条。如果查询的记录多于一条,将把最后一条记录的值赋给变量。

3.1.2 全局变量

  SQL Server 中的所有全局变量都使用两个@标志作为前缀。

  常用的全局变量见下图。

变量 含义

@@ERROR 最后一个T-SQL错误的错误号

@@IDENTITY 最后一次插入的标识值

@@LANGUAGE 当前使用的语言的名称

@@MAX_CONNECTIONS 可以创建的同时连接的最大数目

@@ROWCOUNT 受上一个SQL语句影响的行数

@@SERVERNAME 本地服务器的名称

@@SERVICENAME 该计算机上的SQL服务的名称

@@TIMETICKS 当前计算机上每刻度的微妙数

@@TRANSCOUNT 当前连接打开的事务数

@@VERSION SQL SERVER的版本信息

3.2 输出语句

  T-SQL中支持的输出语句,用于输出显示处理的数据结果。

  常用的输出语句用两种,它们的语法分别如下。

  pint 局部变量或字符串

  select 局部变量 AS 自定义列名

  其中,第二种方法就是查询语句的特殊应用。

  示例2

  pint '服务器的名称:' + @@SERVERNAME

  select @@SERVERNAME AS '服务器名称'

  用print 语句输出的结果将在消息窗口中以文本方式显示,用Select 语句输出的结果将在结果窗口中以表格方式显示。

  由于使用print语句要求以单个局部变量或字符串表达式作为参数,所以如果我们这样编写SQL语句将会出错。

  print '当前错误号' + @@ERROR

  因为全局变量@@ERROR返回的是整型数值。那么如何解决呢?(转换函数,把数值转换成字符串)

  print '当前错误号' + convert(varchar(5) , @@ERROR)

  理解了输出语句后,我们再看看有关全局变量的示例。

  示例3

  insert into stuInfo( stuName, stuNo, stuSex, stuAge) values ('梅超风', 's25318', '女', '23')

  print '当前错误号' + convert(varchar(5), @ERROR)   ---如果大于0,表示上一条语句执行有错误

  print '刚才报名的学员,座位号为:' + convert(varchar(5), @@IDENTITY)

  Update stuInfo set stuAge = 85 where stuName = '李文才'

  print '当前错误号:' + convert(varchar(5), @@ERROR)

  print 'SQL Server 的版本' + @@VERSION

  GO

  @@ERROR 用于表示最近一条SQL语句是否有错误,香港虚拟主机,如果有错误,将返回非零的值。第一次“insert”语句没错,所以为0。第二次“Update”语句违反年龄15~40的检查约束,所以错误号不为零。

  @@IDENTITY可用来查询最后插入的标识值(自动编号值)。例如,本例stuInfo表的stuSeat(座位号)字段,我们前面已定义为标识列(自动标号列),香港空间,该列的值将自动生成,所以在插入时不用跳鞋座位号的数据。一旦插入数据后,我们可以通过查询@@IDENTITY全局变量,来查看目前的自动编号值,即“梅超风”的座位号。

3.3 逻辑控制语句

3.3.1 IF-ELSE 条件语句

  语法

  IF (条件)

    语句或语句块

  ELSE

    语句或语句块

  同java语言一样,ELSE为可选。

  如果有多条语句,需要使用语句块,语句块使用BEGIN···END表示,其作用类似java语言的“{}”符合。

  IF(条件)

    BEGIN

      语句1

      语句2

      ···

    END

  ELSE

    ···

  假定我们已向学员成绩表stuMarks中添加以下测试数据。

ExamNo stuNo writtenExam LabExam

s271811 s25303 80 58

s271813 s25302 50 90

s271815 s25302 65 0

s271816 s25301 77 82

  示例4

  DECLARE @myavg float

  Select @myavg = AVG(writtenExam) FROM stuMarks

  print '本班平均分' + convert(varchar(5), @myavg)

  IF(@myavg > 70)

    Begin

    print '本班笔试成绩优秀,前三名的成绩为:'

    Select top 3 * from stuMarks Order by writtenExam DESC

    End

  Else

    Begin

    print '本班笔试成绩较差,后三名的成绩为:'

    Select top 3 * from stuMarks order by writtenExam

    End

  为了把输出的表格数据和文本消息显示在同一个窗口中,需要做如下设置。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

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.