beta
beta

Reputation: 5666

SQL Server: Multiply a result row

I have several result rows from a SELECT query.

SELECT a.code, CONCAT('text output', a.result)
FROM table1 a

Result looks like

code |  text
a    | 'text output a'
b    | 'text output b'

One column contains concatenated text output. I simply want to have each result row duplicated with slightly different text outputs (which can be hardcoded).

The expected result should be like

code |  text
a    | 'example 1: text output a'
a    | 'example 2: text output a'
b    | 'example 1: text output b'
b    | 'example 2: text output b'

In essence, I want - for each result - to put example 1 and example 2 in front. How can this be done efficiently?

Upvotes: 0

Views: 67

Answers (2)

user1080381
user1080381

Reputation: 1786

This can be done with recursive query

DECLARE @table TABLE(
    code CHAR(1)
    , txt VARCHAR(20)
)

INSERT INTO @table VALUES 
('a', 'text output a')
,('b', 'text output b')
,('c', 'text output c')

;WITH q1 AS(
    SELECT 1 ex, tbl1.code, tbl1.txt
    FROM @table tbl1
        UNION ALL
            SELECT ex+1, q1.code, q1.txt 
            FROM q1
            WHERE q1.ex < 3
)
SELECT q1.code, concat('Example ', q1.ex, ': ', q1.txt) [text]
FROM q1
ORDER BY q1.code, q1.ex

you can change number 3 according how many times you want each row to be displayed

Upvotes: 0

Andrey Korneyev
Andrey Korneyev

Reputation: 26846

Probably the easiest way in your case is following:

SELECT a.code, CONCAT('example 1: text output', a.result)
FROM table1 a
union all
SELECT a.code, CONCAT('example 2: text output', a.result)
FROM table1 a

Upvotes: 1

Related Questions