Concatenate a Column in SQL Server

There may be reason for you to concatenate a column from one SQL table to one field. In other words, you want to append or add a column’s contents into one merged string.

In SQL Server you can do this with a function pretty easily. Here’s an example.

CREATE FUNCTION FUNC_CONCAT (@ID BIGINT)RETURNS VARCHAR(8000)AS
BEGIN
DECLARE @Result VARCHAR(8000)
–We need to set result to a blank string or else it will be a null value.
–A Null string and an empty string are not the same thing.
SET @Result = ”
SELECT @Result = @Result + StringField FROM TableName WHERE ID = @ID
RETURN @Result
END
GO
SELECT DBO.FUNC_TEST(1234)
–or
SELECT
DBO.FUNC_TEST(ID) ResultString, *
FROM
MasterTable

Leave a Reply

Your email address will not be published. Required fields are marked *


9 − one =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>