在SQL Server的每一行中按降序显示一系列字符

时间:2019-02-26 10:31:27

标签: sql sql-server tsql

我想显示一系列*,从第一行的20开始到第21行的1结束。

DECLARE @number INT
SET @number := 21
SELECT REPLICATE('*', @number := @number-1) FROM information_schema.tables where @number > 0

嗯,这行不通,我也不知道哪里出了问题。它输出:

Incorrect syntax near ':'.

我需要朝正确的方向稍加推动。

非常感谢!

4 个答案:

答案 0 :(得分:3)

您的意思是这样吗?

WITH N AS(
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
    SELECT TOP 20 ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
    FROM N N1
         CROSS JOIN N N2)
SELECT REPLICATE('*',T.I)
FROM Tally T
ORDER BY T.I DESC;

请注意,尽管如此,它仅返回20行,而不返回21行(1和20之间包含20个数字)

答案 1 :(得分:2)

您可以尝试递归CTE:

WITH rcte AS 
(
    SELECT 21 AS [Index]
    UNION ALL
    SELECT [Index] - 1
    FROM rcte
    WHERE [Index] > 1
)
SELECT REPLICATE('*', [Index])
FROM rcte
OPTION (MAXRECURSION 0);

答案 2 :(得分:2)

您可以尝试使用内置的dbo.Numbers表:

SELECT TOP 21
    REPLICATE('*', 22-n) AS output
FROM dbo.Numbers
ORDER BY n;

如果dbo.Numbers在您的SQL Server版本中不可用,则只需使用某种序列即可。

Demo

答案 3 :(得分:2)

假设您有适当的ORDER BY子句,请在相反的方向上使用ROW_NUMBER() OVER (ORDER BY ...)来生成降序数字:

-- DECLARE @number INT = 21;
-- the variable is not needed, the total number of stars will match total number of rows

WITH your_tbl AS (
    SELECT number
    FROM master..spt_values
    WHERE type = 'p' AND number BETWEEN 1 AND 21
)
SELECT number, REPLICATE('*', ROW_NUMBER() OVER (ORDER BY number DESC))
FROM your_tbl
ORDER BY number