Use variables
Local variables
-
@ As a prefix must be marked as @age
-
Use local variables be declared (using the keyword declare), then the assignment
DECLARE @age INT --声明局部变量@age --SET @age=20 --赋值局部变量 SELECT @age=20 SELECT @age --查看局部变量的值
Use SELECT assignment to ensure that screening is only one record
Global Variables
- Tag as a prefix must @@, @@ version as
- Can only be read by the system defined and maintained, you can not modify the global variable values
Use variables
Question: write T-SQL query Xiaoming students and their adjacent school number
DECLARE @StuId INT --声明学号变量,这个变量记录小明的学号
SELECT @StuId=ID FROM Student WHERE Name='小明'--根据学生姓名查询出改学生的学号
SELECT * FROM Student WHERE ID=(@StuId+1) OR ID=(@StuId-1)--根据这个学号查询相邻的学员信息
The difference between SET and SELECT
scenes to be used | SET | SELECT |
---|---|---|
At the same time multiple variable assignment | not support | stand by |
When the expression returns multiple values | Error | The last value returned to a variable |
When the expression does not return value | Variable is assigned a NULL value | Variable holds its value |
DECLARE @age INT,@name VARCHAR(20)
--SET @age=20,@name='张三'--不允许这样做
SELECT @age=20,@name='张三'
SELECT @name
--SET @name=(SELECT Name FROM Student)
SELECT @name=Name FROM Student
--SET @name=(SELECT NAME FROM Student WHERE ID=0)
SELECT @name=NAME FROM Student WHERE ID=0
SELECT @name
The use of global variables
variable | meaning |
---|---|
@@ERROR | The last T-SQL error error number |
@@IDENTITY | Last inserted identity value |
@@LANGUAGE | The name of the current language used |
@@MAX_CONNECTIONS | The maximum number of simultaneous connections that can be created |
@@ROWCOUNT | The number of rows affected by a SQL statement on the subject |
@@SERVERNAME | The name of the local server |
@@TRANSCOUNT | Number of transactions currently open connections |
@@VERSION | SQL Server version information of |
Data type conversion
Data type conversion
-
Use the Convert function to achieve cast
CONVERT(数据类型,表达式,样式)--第三个参数可以省略。它一般用于日期类型数据转换为字符类型,
PRINT '平均年龄是:'+CONVERT(VARCHAR(20),@avgAge)
-
Using the function to convert CAST
CASR(表达式 AS 数据类型)
PRINT '平均年龄是:'+CAST(@avgAge AS VARCHAR(20))