Concatenate rows into one by adding spaces

1

I've been searching the internet but I do not find anything like it. In a table in SQL I have three columns, names, paternal surname and maternal surname, how can I join the columns in a new one, all three in one with their spaces? I have the following code where I added space between the records.

select nombre+' '+apPaterno+' '+apMaterno
from dbo.Empleados
    
asked by KlonDTS 13.01.2017 в 18:08
source

2 answers

0

You can add a new virtual column to the table that is the combination of the other 3 in this way:

alter table dbo.empleados
add NombreCompleto as nombre + ' ' + apPaterno + ' ' + apMaterno;

When you do select * from dbo.empleados you will see that there is the new column: Demo .

Reference: Specify columns calculated in a table .

It is also possible to add a new "normal" column to which you then assign the value of the combination of the other 3 columns. But if you do this, as you modify the values of the different columns, you would have to manually continue synchronizing the new column. That's why I suggest this form where the column is virtual and will always reflect the correct data according to the values of the other 3 columns.

Additional note: if it is possible that one of the 3 columns contains null values, then using CONCAT may be better than operator + . You should try and see how you want to handle the null values in those cases.

    
answered by 13.01.2017 / 18:29
source
0

Use the CONCAT function which unites what you send as a parameter in a single table, you only have to assign it an alias with

AS unAlias

so that the field does not have its default name which would be: (CONCAT (name, '', apPaterno, '', apMaterno)):

This is how your query would look:

SELECT CONCAT(nombre, ' ', apPaterno,' ', apMaterno) AS NOMBRE FROM dbo.Empleados;
    
answered by 13.01.2017 в 18:22