Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Concat variable fields

Author  Topic 

WebKill
Starting Member

32 Posts

Posted - 2015-04-21 : 18:36:21
I have been searching a bit and I found solutions for similar things, but nothing that has quite got me there yet.

I need to take all data from a query and concat each row into a single one like such:

LastName | FirstName
Doe | John
Smith | Bob


results should look like this:

WholeName
Doe,John
Smith,Bob

So far I have tried for xml, but in the example below it not only squishes everything together, but its all in one row instead of each row concatenating its own columns.

DECLARE @DataTable TABLE
(
LastName nvarchar(30),
FirstName nvarchar(30)
)
INSERT INTO @DataTable VALUES
('Doe', 'John'),
('Smith', 'Bob')

select (select * from @DataTable for xml path(''), type).value('.','nvarchar(max)')



Any help would be appreciated!

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2015-04-21 : 19:10:22
I must be missing something.

SELECT LastName + ',' + FirstName AS WholeName
FROM ...

Tara Kizer
SQL Server MVP since 2007
http://weblogs.sqlteam.com/tarad/
Go to Top of Page

WebKill
Starting Member

32 Posts

Posted - 2015-04-22 : 01:26:57
Woops, I forgot the most important part. I need this to work without knowing the column names, so basically pass it * and let it still work.
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2015-04-22 : 07:12:57
It might help to know "why" you won't know the columns names. (Might be some other angle to solving your problem).
Go to Top of Page

WebKill
Starting Member

32 Posts

Posted - 2015-04-22 : 09:54:08
I am trying to use ssis to create a dynamic reporting solution, but ssis doesn't do dynamic columns ... at least not easily. So my idea is to get all data to one column, then write as a csv.
Go to Top of Page
   

- Advertisement -