How to Concatenate Column Values in SQL Server 2005

At times, we need to concatenate the values of columns and present it to the user. Let us see how to Concatenate Column Values in SQL Server 2005, espcially when one column is a varchar and the other is an integer.

-- SCRIPT To Create Table

CREATE TABLE #Customers (id integer, cname varchar(20), pincode int)

-- INSERT sample rows

INSERT INTO #Customers VALUES (1, 'Jack',45454 )
INSERT INTO #Customers VALUES (2, 'Jill', 43453)
INSERT INTO #Customers VALUES (3, 'Tom', 43453)
INSERT INTO #Customers VALUES (4, 'Kathy', 34544)
INSERT INTO #Customers VALUES (5, 'David', 65443)
INSERT INTO #Customers VALUES (6, 'Kathy', 65445)
INSERT INTO #Customers VALUES (7, 'Kim', 65443)

-- Concatenate Values

SELECT ID, 'Employee ' + cname + ' has a pincode ' + CAST(pincode as varchar(8)) as Info
FROM #Customers


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

2 comments:

Kevin said...

While I know its not proper, What if we want to store the output of the concatenation in a table using INSERT () VALUES()

Shashank said...

Fine Answer
I quickly used this in my project
Thanks Dude.