Is there a good way on SQL Server to concatenate only the columns which are not empty? I tried with CASE WHEN
but it was a complete mess, I don't want to concatenate the whole line with the name+field+', ' whenever the field is either empty or NULL.
Example:
'Sub-título: ', p.[config_metadata subtitle],', ',
Is not null, but
'Descrição: ', p.[last_timeline descricao],', ',
Is null, so I don't want to concat this whole line (name+field+', '), and so on.
Desired output, if first and third line are not empty and second line is:
'Sub-título: field content, Fwd_descrição: field content, "
SELECT
p._id AS id_documento,
'16' AS id_fluxo,
p.nP AS np,
t.evento,
YEAR(created_at) AS ano_doc,
p.[config_metadata title] AS assunto,
CONCAT ('Sub-título: ', p.[config_metadata subtitle],', ',
'Descrição: ', p.[last_timeline descricao],', ',
'Fwd_descrição: ', p.[last_timeline forwardingDescription],', ',
'Justificativa: ', p.[last_version Justificativa],', ',
'Motivo: ', p.[last_version motivo],', ',
'Área propriedade: ', p.[last_version areapropriedade],', ',
'Endereço: ', p.[last_version endereco],', ',
'Atividade: ', p.[last_version atividade],', ',
'Atividade empreendida: ', p.[last_version atividadeempreend],', ',
'Descreva finalidade: ', p.[last_version descrevafinalidade],', ',
'Nome: ', p.[last_version nome],', ',
'Nome empreendimento: ', [last_version nomeempreendimento],', ',
'Quantidade: ', [last_version quantidade],', ',
'Outros: ', [last_version outros],', ',
'Data finalizado: ', p.[finalizado date] ) AS conteudo,
'' as codigo,
'0' as prioridade,
t.from_id,
t.from_nome,
t.to_id,
t.to_nome,
CONVERT(DATE,[created_at]) AS dia,
CONVERT(TIME(0), [created_at]) AS hora,
created_at
FROM
my_table AS p
JOIN
my_table2 AS t ON p._id = t.pid
WHERE
t.evento = 'Processo criado'
SQL Server version:
Microsoft SQL Server 2022 (RTM-GDR) (KB5021522) - 16.0.1050.5 (X64)
Jan 23 2023 17:02:42
Copyright (C) 2022 Microsoft Corporation
Developer Edition (64-bit) on Windows 10 Home Single Language 10.0 <X64> (Build 22621: ) (Hypervisor)
3条答案
按热度按时间eulz3vhy1#
Use
+
to concatenate the values in each parameter to getNULL
when the column has the valueNULL
instead.NULLIF
can be used to change "empty" (I assume zero length strings (''
) toNULL
as well. Also, I recommend usingCONCAT_WS
too:This assumes that all your columns are a string based value. If a column isn't, you'll need to explicitly
CAST
/CONVERT
the value to a(n)varchar
of an appropriate length (and style if wanted/needed).ncecgwcz2#
A minimal reproducible example is not provided.
Please try the following conceptual solution. It will work starting from SQL Server 2017 onwards.
SQL
Output
k7fdbhmy3#
If you had something like an EAV table with lots of columns and data normalization was not an option, you can take advantage of XML (and potentially JSON) methods to dynamically retrieve column names. This way, if the column names are updated or more are added "horizontally" to the table (for example you have no control over the data design, but you are still required to query it), the query will continue to "work". While PIVOT/UNPIVOT operations are possible as well, these have to have a 'hardcoded' list of values that would need to be maintained or utilize dynamic multi-statement SQL.
While the above example from the OP shows generating a concatenation where the "label" portion is different than the column name specifically, the following example of the query technique could be adapted to join to a "Lookup" table to match a column name to a description needed for the runtime query. The basic premise is to :
COLUMN_SET
forSPARSE
columns)nodes()
as needed for the query (for example, non empty, equals value, etc.)APPLY
statements in combination withlocal-name(.)
to get the field name associated with the filtered value. (applying any 'formatting' to the name)In this example, both
COLUMN_SET
/SPARSE
as well as 'filter out the non-field columns' techniques are shown to dynamically summarizeBIT
fields that are set to 'true' for a record (tested in SQL2022 LocalDB):The results in either method include : | SerialNo | HasFields | |----------|------------| | AB | FieldA,FieldB | | ABC | FieldA,FieldB,FieldC | | BC | FieldB,FieldC | | C | FieldC |
The key point here (😉), is that the source tables could be expanded to any number of columns, and the query would not need to change to select them specifically. (As is the case in
CONCAT
/CONCAT_WS
orPIVOT
based methods)