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的時候編寫一些小例子也蠻有用的呀,如有誤,請指出,謝謝。

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