-- 普通查询,结果为表selectcount(*)as'学生人数'from Student;
go
-- 利用变量查询,定义变量时直接赋值,结果为字符串declare@itinyint=(selectcount(*)from Student)print'学生人数:'+cast(@iaschar(2))+'人';
go
-- 利用set赋值变量查询,结果为字符串declare@itinyintset@i=(selectcount(*)from Student)print'学生人数:'+cast(@iaschar(2))+'人';
go
-- 利用select赋值变量查询,结果为字符串declare@itinyintselect@i=count(*)from Student
print'学生人数:'+cast(@iaschar(2))+'人'
go
查询出年龄最大的学生姓名
-- 普通查询select SNO,SName,Sage
from Student
where Sage=(selectmax(Sage)from Student
)
go
-- 利用变量查询declare@itinyintset@i=(selectmax(Sage)from Student)select SNO,SName,Sage from Student where Sage=@i
go
对一个变量赋值多个值
declare@itinyintset@i=(select Sage from Student)-- 报错,set不可以赋值多个值给一个变量print@i
go
declare@xtinyintselect@x=Sage from Student -- 将多个值依次赋值,并保留最后一个值print@x
go
平均年龄和最大年龄
-- cast和convert,space(整数),char(10)和char(13)表示换行、回车declare@aint,@mintset@a=(selectavg(Sage)from Student)set@m=(selectmax(Sage)from Student)print'平均年龄:'+cast(@aaschar(2))+'岁'+space(8)+'最大年龄:'+convert(char(2),@m)+'岁'
go
declare@aint,@mintselect@a=avg(Sage),@m=max(Sage)from Student
print'平均年龄:'+cast(@aaschar(2))+'岁'+char(10)+'最大年龄:'+convert(char(2),@m)+'岁'
go
字符串拼接
-- 注意空格,char和varchardeclare@ichar(10)set@i='Hello 'print@i+'World!'-- 输出 Hello World!
go
declare@ivarchar(10)set@i='Hello 'print@i+'World!'-- 输出 Hello World!
go
打印出年龄在20岁到30岁之间的学生姓名
-- 声明变量后,变量默认值为nulldeclare@ivarchar(50),@snointset@i=''select@i=@i+Sname+space(2)from Student
where Sage between20and30select@sno=count(*)from Student
where Sage between20and30print'学生姓名为:'+char(10)+@i+char(10)+'总计:'+cast(@snoaschar(2))+'人'
go
赋值NULL
declare@aint,@bintset@a=100set@b=200set@a=(select Sage from Student where1=0)-- 用set赋值null,接受null值select@b=Sage from Student where1=0-- 用select赋值null,忽略null值select@a,@b
go