一、变量的定义、赋值与输出
【T6-01】创建字符型局部变量@var1、@var2并赋值,然后用PRINT语句输出变量的值。
declare @var1 char,@var2 char
set @var1=1
set @var2=2
print @var1
print @var2
【T6-02】创建字符型局部变量@var1、@var2并赋值,然后用SELECT语句输出变量的值。
declare @var1 char(20),@var2 char(20)
set @var1='水'
set @var2='空气'
select @var1
select @var2
【T6-03】创建字符型局部变量@var1和数值型局部变量@var2并赋值,然后输出变量的值。
declare @var1 char,@var2 int
select @var1='a',@var2=2
print @var1
print cast( @var2 as char )
【T6-04】创建一个名为@xb的局部变量,并在SELECT语句中使用该局部变量查找Student表中所有性别为“女”的学生记录。
use fsyxscj
declare @xb char(20)
set @xb='女'
select *
from Student
where Ssex=@xb
【T6-05】创建一个名为@xm的局部变量,用它返回学号为“2012314101”的学生姓名。
use fsyxscj
declare @xm char(20)
set @xm='2012314101'
select *
from Student
where Sno=@xm
二、流程控制语句
【T6-07】给x赋值,并判断其值是“正数”还是“非正数”。
use fsyxscj
declare @xm int
set @xm='2'
if (@xm>=0)
print'其值为正数'
else
print'其值非正数'
【T6-08】给x赋值5,按公式
,计算y的值并输出
use fsyxscj
declare @x int
declare @y int
set @x=5
if (@x>=10)
Begin
set @y=3*@x+2
print @y
end
else
begin
if (@x<1)
set @y=@x
print @y
begin
set @y=2*@x-1
print @y
end
end
【T6-09】给定一个成绩,判断相应的等级。
大于90 '优'
80 AND @cj<=90良'
@cj>=70 AND @cj<=80 '中'
@cj>=60 AND @cj<=70 '及格'
use fsyxscj
declare @x int
set @x=95
if (@x>90)
print '优'
else
begin
if (@x<=90)
print '良'
else
begin
if(@x>=70 and @x<=80)
print '中'
else
print '及格'
end
end
【T6-10】输出SC表中“李勇(学号2012314101)”的“数据库(课程号1)”成绩及对应的等级。
use fsyxscj
declare @x int
select @x=Grade
from SC
where Sno='201231401'
if (@x>90)
print '优'
else
begin
if (@x<=90)
print '良'
else
begin
if(@x>=70 and @x<=80)
print '中'
else
print '及格'
end
end
【T6-11】求s=1+2+3+4+…+100的值。
use fsyxscj
declare @s int
declare @n int
select @s=0
select @n=1
while(@n<101)
begin
select @s=@s+@n
select @n=@n+1
end
print @s
【T6-12】输出九九乘法表。
declare @i int
declare @j int
declare @s int
select @i=1
select @j=1
select @s=0
while (@j<=9)
begin
select @j=1
select @j=@j+1
while(@i<=9)
begin
select @i=1
select @i=@i+1
select @s=@i*@j
print @s
end
end