下面用while 和 if 條件寫的SQL語句的四種九九乘法表
1 --9x9 左下角 2 3 DECLARE @I INT ,@J INT,@S VARCHAR(100) 4 SET @I=1 5 WHILE @I<10 6 BEGIN 7 SET @J=1 8 SET @S='' 9 WHILE @J<=@I 10 BEGIN 11 SET @S=@S+CAST(@J AS CHAR(1))+'*'+CAST(@I AS CHAR(1))+'='+CAST((@I*@J)AS CHAR(3)) 12 SET @J=@J+1 13 END 14 PRINT @S 15 SET @I=@I+1 16 END
結果:
1 --9X9 右下角 2 DECLARE @I INT ,@J INT,@S VARCHAR(100) 3 SET @I=1 4 WHILE @I<10 5 BEGIN 6 SET @J=9 7 SET @S='' 8 WHILE @J>0 9 BEGIN 10 IF @J>@I 11 BEGIN 12 SET @S=@S+' ' --七個空格 13 END 14 ELSE 15 BEGIN 16 SET @S=@S+CAST(@I AS CHAR(1))+'*'+CAST(@J AS CHAR(1))+'='+CAST((@I*@J)AS CHAR(3)) 17 END 18 SET @J=@J-1 19 END 20 PRINT @S 21 SET @I=@I+1 22 END
結果:
--9X9右上角 DECLARE @I INT ,@J INT,@S VARCHAR(100) SET @I=1 WHILE @I<10 BEGIN SET @J=1 SET @S='' WHILE @J<10 BEGIN IF @J<@I BEGIN SET @S=@S+' '--7 END ELSE BEGIN SET @S=@S+CAST(@I AS CHAR(1))+'*'+CAST(@J AS CHAR(1))+'='+CAST((@I*@J)AS CHAR(3)) END SET @J=@J+1 END PRINT @S SET @I=@I+1 END
結果:
--9X9左上角 DECLARE @I INT ,@J INT,@S VARCHAR(100) SET @I=1 WHILE @I<10 BEGIN SET @J=@I SET @S='' WHILE @J<10 BEGIN SET @S=@S+CAST(@I AS CHAR(1))+'*'+CAST(@J AS CHAR(1))+'='+CAST((@I*@J)AS CHAR(3)) SET @J=@J+1 END PRINT @S SET @I=@I+1 END
結果: