How can I do a 'for each' and convert 3 columns into 1 row in SQL Server?

eh57zj3b  于 2023-02-18  发布在  SQL Server
关注(0)|答案(1)|浏览(185)

I have this table in SQL Server:
| Process | ProcessedActivity | BusinessDefinition | SystemError |
| ------------ | ------------ | ------------ | ------------ |
| LADG3 | 2 | 1 | 3 |
| TEF2020 | 1 | 4 | 1 |

I need to convert it to this format:

ProcessStatus
LADG3ProcessedActivity
LADG3ProcessedActivity
LADG3BusinessDefinition
LADG3SystemError
LADG3SystemError
LADG3SystemError
TEF2020ProcessedActivity
TEF2020BusinessDefinition
TEF2020BusinessDefinition
TEF2020BusinessDefinition
TEF2020BusinessDefinition
TEF2020SystemError

I expect to convert each number from the columns ProcessedActivity , BusinessDefinition and SystemError into a message and join this information into only one new column.

How can I do this double conversion in SQL Server?

xfb7svmp

xfb7svmp1#

You need a numbers or tally table for this. If you are using sql server 2022 this is easily done with GENERATE_SERIES. But since that is really new at this point I will assume you are using an older version. I tackle that using this view which I keep on nearly all my databases.

create View [dbo].[cteTally] as

WITH
    E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
    E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
    E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
    cteTally(N) AS 
    (
        SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
    )
select N from cteTally

Regardless of how you generate your tally table this becomes fairly simple. I did this using three queries. There are other ways you could tackle this as well but this will perform reasonably quick and the coding is simple. I used the ExplodedRows cte here so it would allow adding a sort order to all the rows once they are materialized.

with ExplodedRows as
(
    select s.Process
        , ProcessName = 'ProcessedActivity'
        , SortVal = 1
    from #Something s
    join cteTally t on t.N <= s.ProcessedActivity

    union all

    select s.Process
        , 'BusinessDefinition'
        , 2
    from #Something s
    join cteTally t on t.N <= s.BusinessDefinition

    union all

    select s.Process
        , 'SystemError'
        , 3
    from #Something s
    join cteTally t on t.N <= s.SystemError
)

select er.Process
    , er.ProcessName
from ExplodedRows er
order by er.Process
    , SortVal

相关问题