Deviland
Deviland

Reputation: 3374

concatenate values in SQL stored procedure

I have a stored procedure on SQL Server 2008 that copies certain values from one table to another, I need to take 3 of the values and make them into one value in the second (copy to) Table.

INSERT INTO copyto (FIELD_ONE, FIELD_TWO, FIELD_THREE, 
            OTHER_DATA1, OTHER_DATA2, OTHER_DATA3, 
            )
SELECT LTRIM(RTRIM(OTHER_DATA1)), LTRIM(RTRIM(OTHER_DATA2)),
       LTRIM(RTRIM(OTHER_DATA3)),LTRIM(RTRIM(FIELD_ONE)),
       LTRIM(RTRIM(FIELD_TWO)), LTRIM(RTRIM(FIELD_THREE))
       FROM copyfrom

Within the above example (which is code extracted from the stored procedure) I need to concatenate fields 1, 2 and 3.

Upvotes: 0

Views: 3262

Answers (2)

raven
raven

Reputation: 475

Note that concatenating fields with '+' will return no results if at least one of your fields happen to be NULL. Use ISNULL(myfield,'') or COALESCE(myfield,'') as pre-checks on each

Upvotes: 3

Andreas Ågren
Andreas Ågren

Reputation: 3929

You simply concatenate them as you would in any/most other programming languages:

select LTRIM(RTRIM(FIELD_ONE)) + LTRIM(RTRIM(FIELD_TWO)) + LTRIM(RTRIM(FIELD_THREE))
FROM copyfrom

This will "return" one column.

Upvotes: 1

Related Questions