Merge all the columns value into one column as CSV

477 Views Asked by At

How can I combine all the values of the row into one single field in MS SQL Server,

Suppose my table format is ::

area_name || city || state || postal_code || country || address

Output

area||city||state||postal_code||country||

area,city,state,postal_code,country

How to merge the values of area_name, city, state, postal_code and country to make one address in CSV format.

My code

CREATE PROC [dbo].[p_insert_address]
    @ID             INT = 0,
    @area_name      VARCHAR(20)
    @city           VARCHAR(20),
    @state          VARCHAR(20),
    @postal_code    VARCHAR(20),
    @country        VARCHAR(20) 
AS
    BEGIN
        SET NOCOUNT ON;     

            INSERT INTO address (@area_name, city, state, postal_code, country)
            VALUES (@area_name, @city, @state, @postal_code, @country);     

        SET NOCOUNT OFF;

    END
1

There are 1 best solutions below

4
Simone On

This to insert data in your table:

CREATE PROC [dbo].[p_insert_address]
    @ID             INT = 0,
    @area_name      VARCHAR(20)
    @city           VARCHAR(20),
    @state          VARCHAR(20),
    @postal_code    VARCHAR(20),
    @country        VARCHAR(20) 
AS
    BEGIN
        SET NOCOUNT ON;     

            INSERT INTO address (area_name, city, state, postal_code, country,csv)
            VALUES (@area_name, @city, @state, @postal_code, @country, @area_name+','+@city+','+@state+','+@postal_code+','+@country);     

        SET NOCOUNT OFF;

    END

Otherwise:

SELECT area_name, city, state, postal_code, country,area_name+','+city+','+state+','+postal_code+','+country
FROM address