局部变量
1 use StudentManageDB 2 go 3 --声明学号变量 4 declare @stuid int,@stuname varchar(20) 5 6 --查询李铭的信息 7 set @stuname='李铭' 8 select StudentId,StudentName,Gender,StudentIdNo from Students 9 where StudentName=@stuname 10 11 --查询李铭的学号 12 select @stuId=StudentId from Students where StudentName=@stuname 13 14 --查询与李铭学号相邻的学员 15 select StudentId,StudentName,Gender,StudentIdNo from Students 16 where StudentId=(@stuId+1) or StudentId=(@stuId-1)
set与select比较
1 declare @stuAddress nvarchar(100) , @stuName nvarchar(100) 2 --set @stuAddress='天津', @stuName='张三' --不允许这样赋值 3 select @stuaddress='天津', @stuName='王小虎' --允许 4 5 --set @stuAddress = (select StudentAddress from Students) --不允许 6 select @stuAddress = StudentAddress from Students --得到最后一个 7 set @stuAddress = (select StudentAddress from Students where 1<0) --NULL值 8 select @stuAddress = StudentAddress from Students where 1<0 --保持原值
全局变量
1 PRINT '服务器的名称: ' + @@SERVERNAME 2 PRINT 'SQL Server的版本' + @@VERSION 3 4 SELECT @@SERVERNAME AS '服务器名称' 5 SELECT @@VERSION AS 'SQL Server的版本'
1 use StudentManageDB 2 go 3 --插入学员信息 4 insert into Students (StudentName,Gender,Age,Birthday,StudentIdNo, 5 PhoneNumber,StudentAddress,ClassId) 6 values('王小欣','男',28,'1988-08-07',120223198808071111, 7 '022-22222222','天津市南开区',10) 8 9 10 --获取最后一条SQL语句的执行错误号 11 print @@error