What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 2055 |  Welcome, Guest!   Register  Login
Home > Articles > Sql Server > Data Concatenation - SQL Server

Data Concatenation - SQL Server

1 vote(s)
Rating: 5 out of 5
Article posted by Pandians on 7/21/2009 | Views: 8250 | Category: Sql Server | Level: Intermediate red flag


In this article, I shall show how to concatenate data from COLUMN1 by grouping against COLUMN2 without looping CURSOR.

Download


 Download source code for Data Concatenation - SQL Server


Scenario 
I want to concatenate data from COLUMN1 by grouping against COLUMN2 without looping CURSOR.

  1. Creating Sample Table
  2. Inserting Sample Data
  3. Fetching All Rows
  4. Concatenating data to Single Result (Row)
      1. Using COALESCE 
      2. Using FOR XML PATH 
  5. Concatenating data with Multiple Result(s)


Introduction
We can Concatenate data in various way(s) in various scenarios using COALESCE, FOR XML PATH, LOOP with CURSOR(s).Etc.,

But. we are going to do with COALESCE and FOR XML PATH(Not loop with CURSOR

1. Creation Sample Table

IF OBJECT_ID('DataTypeCategory','U') IS NULL
CREATE
TABLE DataTypeCategory
(

ID              INT IDENTITY(1,1)    ,
Category     VARCHAR(50)           ,
DataType    VARCHAR(20)
)

GO

2. Inserting Sample Data


INSERT DataTypeCategory VALUES('Exact Numerics','Bigint')
INSERT
DataTypeCategory VALUES('Exact Numerics','Decimal')
INSERT
DataTypeCategory VALUES('Exact Numerics','Int')
INSERT
DataTypeCategory VALUES('Exact Numerics','Numeric')
INSERT
DataTypeCategory VALUES('Exact Numerics','Smallint')
INSERT
DataTypeCategory VALUES('Exact Numerics','Money')
INSERT
DataTypeCategory VALUES('Exact Numerics','Tinyint')
INSERT
DataTypeCategory VALUES('Exact Numerics','Smallmoney')
INSERT
DataTypeCategory VALUES('Exact Numerics','Bit')
INSERT
DataTypeCategory VALUES('Approximate Numerics','Float')
INSERT
DataTypeCategory VALUES('Approximate Numerics','Real')
INSERT
DataTypeCategory VALUES('Date and Time','Datetime')
INSERT
DataTypeCategory VALUES('Date and Time','Smalldatetime')
INSERT
DataTypeCategory VALUES('Character Strings','Char')
INSERT
DataTypeCategory VALUES('Character Strings','Text')
INSERT
DataTypeCategory VALUES('Character Strings','Varchar')
INSERT
DataTypeCategory VALUES('Unicode Character Strings','Nchar')
INSERT
DataTypeCategory VALUES('Unicode Character Strings','Ntext')
INSERT
DataTypeCategory VALUES('Unicode Character Strings','Nvarchar')
INSERT
DataTypeCategory VALUES('Binary Strings','Binary')
INSERT
DataTypeCategory VALUES('Binary Strings','Image')
INSERT
DataTypeCategory VALUES('Binary Strings','Varbinary')
INSERT
DataTypeCategory VALUES('Other Data Types','Cursor')
INSERT
DataTypeCategory VALUES('Other Data Types','Timestamp')
INSERT
DataTypeCategory VALUES('Other Data Types','Sql_variant')
INSERT
DataTypeCategory VALUES('Other Data Types','Uniqueidentifier')
INSERT
DataTypeCategory VALUES('Other Data Types','Table')
INSERT
DataTypeCategory VALUES('Other Data Types','Xml')
GO

3. Fetching All Rows

Fetching all row(s) from the table 
SELECT * FROM DataTypeCategory
GO




4. Concatenating data with Single Result
If we want to concatenate all DataType data only for Category='Exact Numerics' only


4.1. Using COALESCE

DECLARE @StrConcate_COALESCE VARCHAR(MAX)
SELECT @StrConcate_COALESCE = COALESCE(@StrConcate_COALESCE,'') + DataType + ',' FROM DataTypeCategory WHERE Category='Exact Numerics'
SELECT LEFT(@StrConcate_COALESCE,LEN(@StrConcate_COALESCE)-1) 'COALESCE'
GO



4.2. Using FOR XML PATH 

DECLARE @StrConcate_FORXMLPATH VARCHAR(MAX)
SELECT @StrConcate_FORXMLPATH = (SELECT DataType + ',' FROM DataTypeCategory WHERE Category='Exact Numerics' FOR XML PATH(''))
SELECT LEFT(@StrConcate_FORXMLPATH,LEN(@StrConcate_FORXMLPATH)-1) 'FOR XML PATH'
GO


5. Concatenating data with Multiple Result(s)
If we want to concatenate all DataType data for each Category wise.


;
WITH Concatenation(Category,Concatenated) AS
(
SELECT A.Category,
(
SELECT B.DataType + ',' FROM DataTypeCategory B WHERE B.Category=A.Category FOR XML PATH('')) 'Concatinated'
FROM
DataTypeCategory A
GROUP
BY A.Category
)

SELECT
Category,LEFT(Concatenated,LEN(Concatenated)-1) 'Concatenated' FROM Concatenation
GO




Conclusion

Each group wise concatenation can be done by Looping with CURSOR also. But doing FOR XML PATH is less code and we can avoid of CURSORs.

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:7 year(s)
Home page:http://sqlserverbuddy.blogspot.com/
Member since:Monday, May 11, 2009
Level:Silver
Status: [Member] [MVP]
Biography:Microsoft Certification
- Microsoft Certified IT Professional(MCITP) - SQL Server 2008 Database Administrator
- Microsoft Certified Technology Specialist(MCTS) - SQL Server 2005
- Microsoft Certified Professional(MCP) - SQL Server 2000
 Responses
Posted by: Raja | Posted on: 21 Jul 2009 11:12:14 AM

Very efficient code, Thanks Sathappan.

>> Write Response - Respond to this post and get points
Related Posts

You might get the error related to "Exclusive access could not be obtained because the database is in use" so, in this article we will gain over this error.

This Article will Show you , how to rebuild all the indexes in table in all the Databases in SQL 2005/200

In this article, we will look into the Percent Rank function of SQL Server 2012 (Denali).

This Article explains you how to Encrypt and Decrypt a text

XML Data type one of the important data types available in SQL Server, offers to declare variable and table columns to store data in the XML format, comes up with 5 main methods to use with the XQuery in SQL Server.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/24/2013 1:34:48 AM