开发者

Batched output in SQL Server

I have a tables like the following

CREATE TABLE Company
(
Id INT
)

CREATE TABLE CompanyNumbers
(
CompanyId INT,
NumberText VARCHAR (255)
)

What I want as an output is this in pseudo code

Give me all the numbers for comp开发者_JS百科any A as a single comma separated string, if the string contains more than 150 numbers output another row with next 150 until complete.

What is the best way to achieve this? basically output batches of 150 numbers like this:

CompanyId | Batch
1         | 3344,444,5555,6444, 444, 44, 44555, 5555... > 150 of them 
2         | 33343,33, 2233,3 (second row if more than 150)

I want this to be done within a stored procedure.


WITH    cb AS
        (
        SELECT  CompanyId, NumberText, ROW_NUMBER() OVER (PARTITION BY CompanyID ORDER BY NumberText) AS rn
        FROM    CompanyNumbers
        )
SELECT  CompanyID, batch,
        (
        SELECT  CASE WHEN rn % 150 = 1 THEN '' ELSE ', ' END + NumberText AS [text()]
        FROM    cb
        WHERE   cb.CompanyID = cbd.CompanyID
                AND rn BETWEEN cbd.batch * 150 + 1 AND cbd.batch * 150 + 150
        FOR XML PATH('')
        )
FROM    (
        SELECT  DISTINCT CompanyID, FLOOR((rn - 1) / 150) AS batch
        FROM    cb
        ) AS cbd
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜