with cte as (
SELECT
number
FROM
master..spt_values
WHERE
type='P'
AND number between 1 and 9
),
sumcte as (
SELECT
A.number X,
B.number Y,
A.number * B.number Val
FROM
cte A CROSS JOIN cte B
)
SELECT
[1], [2], [3], [4], [5], [6], [7], [8], [9]
FROM
sumcte
PIVOT(
SUM(Val)
FOR Y IN ([1], [2], [3], [4], [5], [6], [7], [8], [9])
) tmp
ORDER BY
X
SQL Server 2008 Express 下测试通过。
如果不支持with语法可以用派生表的方式书写,效果一样的
;with cte as(
select 1 [1],2 [2],3 [3],4 [4],5 [5],6 [6],7 [7],8 [8],9 [9]
),
cte1 as
(
select number from master..spt_values where type='P' and number between 1 and 9
)
select number*[1],number*[2],number*[3],number*[4],number*[5],number*[6],number*[7],number*[8],number*[9]
from cte1,cte
declare@asmallint,
@bsmallint,
@strvarchar(1000)
set@a=1
while@a<=9
begin
set@b=1
set@str=''
while@b<=@a
begin
select@str=@str+convert(varchar(1),@b)+'*'+convert(varchar(1),@a)+'='+convert(varchar(2),@a*@b)+space(2)
set@b=@b+1
end
print@str
set@a=@a+1
end
/*
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81 */
select
convert(char(2),I),
convert(char(2),I*2),
convert(char(2),I*3),
convert(char(2),I*4),
convert(char(2),I*5),
convert(char(2),I*6),
convert(char(2),I*7),
convert(char(2),I*8),
convert(char(2),I*9)
from
(select 1 I
union
select 2
union
select 3
union
select 4
union
select 5
union
select 6
union
select 7
union
select 8
union
select 9
) I