Transact-SQL编程

来源:互联网 发布:e25数据 编辑:程序博客网 时间:2024/06/04 15:54
DECLARE @num int--定义变量

SELET @num = avg(分数)--赋值给变量@num
FROM 成绩信息
where 考试编号 = '0202' and '课程编号' = '2'
select @num--打印输出

if @num>60
    begin--语句块用begin end格式,下面是嵌套的if--else语句
      if @num<70
        print'刚刚及格'
      else if @num<80
        print'成绩中等'
      else if @num<90
        print'成绩良好'
      else
        print'成绩优秀'
    --print'这个老师教的很好'
    end
else
        print'没及格呢'
  ===========================================================      
        
--员工职称是根据员工姓名,所在职位虚拟出来的列
select 员工姓名,所在职位,员工职称=
case 所在职位--相当于switch(c)
when '经理' then '高级职称'--相当于case分支
when '主管' then '中级职称'
when '职员' then '初级职称'
else '其他职称'--相当于default
end--结束

from 员工信息

===========================================================

T-SQL编程求10!

--求10的阶乘10!(超过12会溢出)
--ctrl+shift+u会把选定的单词全变为大写+l会变为小写
DECLARE @i int,@num int
set @i = 1
set @num = 1
while @i<=10
begin
    set @num = @num*@i
    set @i = @i+1
end
print @num
/*select @num*/


  ===========================================================     
--利用循环嵌套实现1-100之间的素数
--下面两句定义变量i、j

declare @i int
declare @j int

set @i = 3

while @i<=100
begin
    declare @bool int
    set @bool = 1
    set @j = 2
    
    while @j<=sqrt(@i)
    begin
        if(@i%@j=0)
        begin
        set @bool = 0--不是素数
        break
        end
        set @j = @j+1
    end
    if @bool = 1 print @i
    set @i = @i+1
end

=========================================================================

--WAITFOR延迟语句
waitfor delay '20:20:01'--延迟时间执行下面的语句
exec sp_helpdb
exec sp_help
select getdate()--获取当前系统的时间


--try catch语句
begin try
declare @num int
set @num=1/0
select @num
end try

begin catch
select Error_line() as '错误行数',error_message() '错误消息'
end catch


--数学函数
select abs(-2) as '-2的绝对值'
select exp(-1) as '以e为底的指数'
select ceiling(3.4) as'大于3.4的最小整数'
select floor(3.4)  as'小于3.4的最大整数'
select square(2) as '2的平方'
select sqrt(2) as '2的平方根'

print round(12.3224,2)--直接打印输出
print power(3,4)--3的多少次方,此为3^4

--字符串函数
declare @str nvarchar(50)
set @str='hello world!'
print ascii(@str)
print ascii('h')
print char(104)

declare @str nvarchar(50)
set @str='hello world!'
print substring(@str,7,4)--7是从w开始,4是截取4个字符
print len(@str)

0 0
原创粉丝点击