SQL SERVER掌握变量和流控制语句使用的小demo

 前言:

     运算符和流控制语句的小例子,希望对大家有帮助。

1.计算一元二次方程根,熟悉定义变量和运算法。

--计算一元二次方程根 ax^2+bx+c=0
declare @x1 numeric(7,2),@x2 numeric(7,2)
declare @a smallint,@b smallint,@c smallint,@s int
select @a=1,@b=-2,@c=1
set @s=@b*@b-4*@a*@c
if @s>=0
begin
	set @x1=(-@b+sqrt(@b*@b-4*@a*@c))/(2*@a)
	set @x1=(-@b-sqrt(@b*@b-4*@a*@c))/(2*@a)
	select @x1,@x2
end
else
	select '无实根解'

2.熟悉if条件语句 



	--用set语句给变量赋值
	declare @one varchar(18),@two varchar(18)
	set @one='this is one'
	set @two='this is two'
	if @one='this is one'
		print 'you got one'
	if @two='this is two'
		print 'you got two'
	else
		print 'none'

 3.熟悉设置变量语句

--定义三个整数,按生序排序输出
declare @a smallint,@b smallint,@c smallint,@s smallint
select @a=300,@b=40,@c=50
if @a>@b
	select @s=@a,@a=@b,@b=@s
if @c<@a
	select @c,@a,@b
else
	if @c>@b
		select @a,@b,@c
	else
		select @a,@c,@b

4.熟悉使用循环语句 

--计算1+2+...+100的值
declare @i int
declare @sum int
set @i=1
set @sum=0
while @i<=100
begin
	set @sum=@sum+@i	
	set @i=@i+1
end
select @i,@sum

5.熟悉使用分支结构语句 

--转换成绩等级
declare @score smallint
set @score=68
SELECT 成绩级别=
	CASE	
		WHEN @score<60 THEN '不及格'
		WHEN @score<70 THEN '及格'
		WHEN @score<80 THEN '中等'
		WHEN @score<90 THEN '良好'
		WHEN @score<=10060 THEN '优秀'
		ELSE '成绩有误'
	END

 6.基于其它语言的理解编写SQL

--输入两个整数,求最大公约数和最小公倍数
create function myc(@a int,@b int)
returns int
as 
begin
if @a<=0 or @b<=0
return 0
else
if @a is null or @b is null
return null
else
declare @s int
if @a>=@b
begin
set @s=@b 
while @s>=1
begin
if @a%@s=0 and @b%@s=0
break
set @s=@s-1
end
return @s
end
else
set @s=@a
while @s>=1
begin
if @a%@s=0 and @b%@s=0
break
set @s=@s-1
end
return @s
end

7.最小公倍数 

--最小公倍数
create function Gbs(@a int,@b int)
returns int
as
begin
declare @ans int
declare @max int
declare @times int
if @a<=@b
set @max=@b
else
set @max=@a
set @times=@max
while(@times>=@max)
begin
if(@times%@a=0 and @times%@b=0)
begin
set @ans=@times
break
end
set @times=@times+1
end
return @ans
end

select dbo.Gbs(3,4)

 

后记:

     刚开始学习SQL的时候编写一些小例子也蛮有用的呀,如有误,请指出,谢谢。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章