第三章 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
为了把输出的表格数据和文本消息显示在同一个窗口中,需要做如下设置。

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











How to remove duplicate values from PHP array using regular expressions: Use regular expression /(.*)(.+)/i to match and replace duplicates. Iterate through the array elements and check for matches using preg_match. If it matches, skip the value; otherwise, add it to a new array with no duplicate values.

1. Programming can be used to develop various software and applications, including websites, mobile applications, games, and data analysis tools. Its application fields are very wide, covering almost all industries, including scientific research, health care, finance, education, entertainment, etc. 2. Learning programming can help us improve our problem-solving skills and logical thinking skills. During programming, we need to analyze and understand problems, find solutions, and translate them into code. This way of thinking can cultivate our analytical and abstract abilities and improve our ability to solve practical problems.

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Build browser-based applications with Golang Golang combines with JavaScript to build dynamic front-end experiences. Install Golang: Visit https://golang.org/doc/install. Set up a Golang project: Create a file called main.go. Using GorillaWebToolkit: Add GorillaWebToolkit code to handle HTTP requests. Create HTML template: Create index.html in the templates subdirectory, which is the main template.

Through GoGet, you can quickly and easily obtain Go modules. The steps are as follows: Run in the terminal: goget[module-path], where module-path is the module path. GoGet automatically downloads the module and its dependencies. The location of the installation is specified by the GOPATH environment variable.

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

The GoFmt command is a code formatting tool that can automatically format Go source code so that it conforms to the conventions of the Go language style guide, thereby improving the readability, consistency, and beauty of the code. Usage: Enter gofmtsource_files.go in the terminal. Advanced options include: use -w to write formatted code to the source file; use -d to display only the changes to be made; use -e to report unformatted files.
