数据库环境:SQL SERVER2008R2
今天我们用SQL实现一下九九乘法表的功能。
实现的逻辑不是很复杂,难点在于怎么把想要的内容从同一列里头拼接到同一行上。
在这里,我们用到了FOR XML PATH,FOR XML的用法,可以到MSDN去看,这里就不细讲了。
/*数据准备,生成自然数1-9*/ WITH x0 AS ( SELECT id FROM t100 WHERE id <= 9 ),/*生成所有可能的乘法组合*/ x1 AS ( SELECT a.id AS aid , b.id AS bid , CONVERT(VARCHAR(1), a.id) + ‘ * ‘ + CONVERT(VARCHAR(1), b.id) + ‘ = ‘ + CONVERT(VARCHAR(2), a.id * b.id) AS result FROM x0 a , x0 b WHERE a.id <= b.id ) /*把被乘数相同的转到同一行上*/ SELECT result FROM ( SELECT bid , ( SELECT ‘ ‘ + result AS [text()] FROM x1 AS t2 WHERE t2.bid = t1.bid FOR XML PATH(‘‘) ) AS result FROM x1 AS t1 GROUP BY bid ) t;
相关的说明已经在代码里进行注释。
(本文完)
时间: 2024-11-04 15:22:48