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

2 comments:

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

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

    ReplyDelete