以下是学习sql基础算法的三个例子,分别是九九乘法表、空心菱形的两种实现方法,供大家参考。
一、九九乘法表
复制代码 代码如下:
DECLARE @i INT;
DECLARE @j INT;
DECLARE @k VARCHAR(63);
SET @i=0
WHILE @i<9
BEGIN
SET @i=@i+1
SET @j=0
SET @k=''
WHILE @j<@i
BEGIN
SET @j=@j+1
IF(@j=1)
BEGIN
SET @k=@k+CAST(@i AS CHAR(1))+'*'+CAST(@j AS CHAR(1))+'='+CAST(@i*@j AS CHAR(1))+';'
END
ELSE
BEGIN
SET @k=@k+CAST(@i AS CHAR(1))+'*'+CAST(@j AS CHAR(1))+'='+CAST(@i*@j AS CHAR(2))+';'
END
END
PRINT @k
END
二、实心菱形(修改@num改变行数)
复制代码 代码如下:
DECLARE @num INT;
DECLARE @i INT;
SET @num=5;
SET @i=@num;
IF(@num<3 OR @num%2=0)
BEGIN
PRINT N'请输入大于1的奇数^_^'
END
ELSE
BEGIN
WHILE @i>0
BEGIN
IF(@i>(@num/2))
BEGIN
SET @i=@i-1
PRINT SPACE(@i-(@num/2))+REPLACE(SPACE(((@num-1)-@i)*2+1),' ','*')
END
ELSE
BEGIN
PRINT SPACE((@num/2+1)-@i)+REPLACE(SPACE(@i*2-1),' ','*')
SET @i=@i-1
END
END
END
三、空心菱形(修改@num改变行数)
复制代码 代码如下:
DECLARE @num INT;
DECLARE @i INT;
SET @num=5;
SET @i=@num;
IF(@num<3 OR @num%2=0)
BEGIN
PRINT N'请输入大于1的奇数^_^'
END
ELSE
BEGIN
WHILE @i>0
BEGIN
IF(@i>(@num-1))
BEGIN
SET @i=@i-1
PRINT SPACE(@i-@num/2)+REPLACE(SPACE(1),' ','*')
END
ELSE IF(@i>(@num/2))
BEGIN
SET @i=@i-1
PRINT SPACE(@i-@num/2)+REPLACE(SPACE(1),' ','*')
+SPACE(((@num-2)-@i)*2+1)+REPLACE(SPACE(1),' ','*')
END
ElSE IF(@i>1)
BEGIN
PRINT SPACE((@num/2+1)-@i)+REPLACE(SPACE(1),' ','*')
+SPACE(2*@i-3)+REplACE(SPACE(1),' ','*')
SET @i=@i-1
END
ELSE
BEGIN
PRINT SPACE((@num/2+1)-@i)+REPLACE(SPACE(1),' ','*')
SET @i=@i-1
END
END
END