473,378 Members | 1,218 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Fast Way to Concat Records to Comma Sep VARCHAR

Hi All,

Here's a challenge.

If there is a 'one word' answer to this, i.e. the name of a built in
SQL Server function I can use, that would be great! However...

I have a standard 1:m relationship, e.g. tblHeader and tblDetail.

I want to create a view of records from 'tblHeader' and within that
view have a column (called e.g. DetailTypes) that provides a single
comma separated varchar of values from a varchar field (called e.g.
DetailType) that appears in related records in the 'tblDetail' table.
(hope you understood that :)

e.g. the contents of my 'tblDetail' table could be....

Detail ID | Header ID | DetailType
-----------------------------------
1 | 1 | A
2 | 1 | A
3 | 1 | B
4 | 2 | A
5 | 2 | C
6 | 3 | B

Therefore, the view I want to create should return:

Header ID | DetailTypes
-------------------------------
1 | 2A, 1B
2 | 1A, 1C
3 | 1B
i.e. the first row can be read as "Header 1 has 2 'A' detail records
and 1 'B' detail record."

I have created a view e.g. 'vqryHeaders' which calls a user defined
function that takes the HeaderID and opens a cursor on another view,
e.g. 'vqryDetailGrouped'. The other view groups the records in
tblDetail so that I can get a count of each DetailType for each Header
ID. The cursor then loops through the returned records concatenating
the count and detail type into a comma separated string (as shown
above).

However, when I run this across 20k records it is soooo sloooooww. I
have indexes on the relationship fields and I am using realistically
sized varchars - neither made any difference in speed. It is
definately the function that I wrote that slows it down as the view is
lightning fast when I remove my function call.

I can supply source code if necessary, but I think that this is a
kind-of generic problem so I don't see the point - yet.

I really hope you can help.

Regards,

Jezz
Jul 20 '05 #1
11 14849

"Jeremy Pridmore" <go*********@pridmorej.freeserve.co.uk> wrote in message
news:9b**************************@posting.google.c om...
Hi All,

Here's a challenge.

If there is a 'one word' answer to this, i.e. the name of a built in
SQL Server function I can use, that would be great! However...

I have a standard 1:m relationship, e.g. tblHeader and tblDetail.

I want to create a view of records from 'tblHeader' and within that
view have a column (called e.g. DetailTypes) that provides a single
comma separated varchar of values from a varchar field (called e.g.
DetailType) that appears in related records in the 'tblDetail' table.
(hope you understood that :)

e.g. the contents of my 'tblDetail' table could be....

Detail ID | Header ID | DetailType
-----------------------------------
1 | 1 | A
2 | 1 | A
3 | 1 | B
4 | 2 | A
5 | 2 | C
6 | 3 | B

Therefore, the view I want to create should return:

Header ID | DetailTypes
-------------------------------
1 | 2A, 1B
2 | 1A, 1C
3 | 1B
i.e. the first row can be read as "Header 1 has 2 'A' detail records
and 1 'B' detail record."

I have created a view e.g. 'vqryHeaders' which calls a user defined
function that takes the HeaderID and opens a cursor on another view,
e.g. 'vqryDetailGrouped'. The other view groups the records in
tblDetail so that I can get a count of each DetailType for each Header
ID. The cursor then loops through the returned records concatenating
the count and detail type into a comma separated string (as shown
above).

However, when I run this across 20k records it is soooo sloooooww. I
have indexes on the relationship fields and I am using realistically
sized varchars - neither made any difference in speed. It is
definately the function that I wrote that slows it down as the view is
lightning fast when I remove my function call.

I can supply source code if necessary, but I think that this is a
kind-of generic problem so I don't see the point - yet.

I really hope you can help.

Regards,

Jezz


The fastest (and easiest) way would probably be in a front end application,
as this sort of thing is very awkward in pure SQL. You might find these
links useful for more information:

http://www.aspfaq.com/show.asp?id=2279
http://tinyurl.com/bib2

Simon
Jul 20 '05 #2
The fastest way I know is to use the TSQL extension to the update
statement.
UPDATE table
SET @var = col = expression which manipulates col
WHERE condition

I won't go into the details because it's rather lengthy and my wife is
waiting for me... I've included sample code and the output. -- Louis

-----------------------------------------------------------------------------
create table #H (headerID smallint)
insert into #H values(1)
insert into #H values(2)
insert into #H values(3)

create table #D (detailID smallint,headerID smallint,detailType
char(1))
insert into #D values(1,1,'A')
insert into #D values(2,1,'A')
insert into #D values(3,1,'B')
insert into #D values(4,2,'A')
insert into #D values(5,2,'C')
insert into #D values(6,3,'B')

select
d.headerid,
cast(count(d.detailtype) as varchar)+cast(detailtype as varchar) as
detailtypes,
identity(int,1,1) as i
into #T
from #H as h
join #D as d
on h.headerid=d.headerid
group by d.headerid,d.detailtype
order by d.headerid,d.detailtype

select headerid,identity(int,1,1) as i
into #Cursor
from #T
group by headerid order by headerid

declare @i int, @text varchar(8000)
set @i=1
while exists(select * from #cursor where i=@i) begin

set @text=''
update #T
set @text=detailtypes=@text +',' + detailtypes
where headerid=(select headerid from #cursor where i=@i)

set @i=@i+1
end

select a.headerid,right(detailtypes,len(detailtypes)-1) as detailtypes
from #T as a
join
(
select headerid,max(i) as i from #T group by headerid
) as b
on a.i=b.i


OUTPUT
headerid detailtypes
-------- ------------------------------------------------------------
1 2A,1B
2 1A,1C
3 1B
Jul 20 '05 #3
>> I think that this is a kind-of generic problem .. <<

It is generic in the sense that newbies who don't understand what
First Normal Form (1NF) mean keep posting for a way to do front end
displays and reports in the SQL backend. This comes from not having
worked with a client/server architecture before, so you want to see
everything for the app written in one monolithic program.

The only safe way is to use a cursor and reutrn to slow, procedural
programming instead of declarative SQL programming. Any kludge you
use will not port to another SQL product, will run like glue and will
be almost unpredictable.
Jul 20 '05 #4
jo*******@northface.edu (--CELKO--) wrote in message news:<a2**************************@posting.google. com>...
I think that this is a kind-of generic problem .. <<


It is generic in the sense that newbies who don't understand what
First Normal Form (1NF) mean keep posting for a way to do front end
displays and reports in the SQL backend. This comes from not having
worked with a client/server architecture before, so you want to see
everything for the app written in one monolithic program.

The only safe way is to use a cursor and reutrn to slow, procedural
programming instead of declarative SQL programming. Any kludge you
use will not port to another SQL product, will run like glue and will
be almost unpredictable.


Thanks for confirming that the world still has some complete w@nkers
in it.

1. Don't make assumptions. I'm not a newbie - as my post said I
already have an answer, albeit a slow one.
2. Don't make assumptions. I have worked on several successful C/S
apps.
3. Don't make assumptions. I don't necessarily want my app complied
into one large monolithic program. Also, If it is possible to create
a reusable function into which you can pass several parameters and get
a concatenated string, that procedure would be classed as 'generic'.
4. Don't make assumptions. I don't want it to port to any other
platform. Why do you think I posted in comp.databases.ms-sqlserver
and not in comp.databases?

I already have code that runs like glue, which is why I posted. I
would expect any *intelligent* person to give a reasonable response
(such as Louis) - not a rant.

Although an appropriate procedure can be created in 'front-end' code -
in my case i'm using vbscript (more fuel?), I would expect that
varchar 'lookup' and manipulation in the database would be quicker
than having to retrieve all the data into the front end and process it
there.

Oh, and lets not forget the most inportant thing - the reason why I
want to do this! It will give me a searchable field in a view to
which I can apply my 'generic' filtering procedures.

So, how is your snow coming along?

"You're not much use to me alive are you" CELKO?
- Bricktop.

La, la, la - I'm ignoring you now.

What was that? Whatever.
Jul 20 '05 #5
lo************@hotmail.com (louis nguyen) wrote in message news:<b0*************************@posting.google.c om>...
The fastest way I know is to use the TSQL extension to the update
statement.
UPDATE table
SET @var = col = expression which manipulates col
WHERE condition

I won't go into the details because it's rather lengthy and my wife is
waiting for me... I've included sample code and the output. -- Louis

<snip>

Thanks Louis - you reminded me about temporary tables. That will go
along way in helping me - my problem probably lays with the fact that
I want to return this concatenated field in a view - not in a stored
proc, so the only way i can think of doing it is to use a function
that it aliased and pass in the primary key, select the records i need
in the function and then concatenate them.

Thanks again,

Jeremy
Jul 20 '05 #6
Jeremy Pridmore (go*********@pridmorej.freeserve.co.uk) writes:
lo************@hotmail.com (louis nguyen) wrote in message

news:<b0*************************@posting.google.c om>...
The fastest way I know is to use the TSQL extension to the update
statement.
UPDATE table
SET @var = col = expression which manipulates col
WHERE condition

I won't go into the details because it's rather lengthy and my wife is
waiting for me... I've included sample code and the output. -- Louis

<snip>

Thanks Louis - you reminded me about temporary tables. That will go
along way in helping me - my problem probably lays with the fact that
I want to return this concatenated field in a view - not in a stored
proc, so the only way i can think of doing it is to use a function
that it aliased and pass in the primary key, select the records i need
in the function and then concatenate them.


Beware that any "fast" solution to your problem will rely on
undocumented and undefined behaviour. The only safe way to this
in SQL is to it with a cursor or some other iterative method.
--
Erland Sommarskog, SQL Server MVP, so****@algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #7
>> The fastest way I know is to use the TSQL extension to the update
statement.
UPDATE table
SET @var = col = expression which manipulates col
WHERE condition

Erland:Beware that any "fast" solution to your problem will rely on
undocumented and undefined behaviour. The only safe way to this
in SQL is to it with a cursor or some other iterative method.


Erland - are you referring to the code above here? What do you mean
exactly? Is there some sneakiness of undocumented goodness you are
keeping from us?
Jul 20 '05 #8
I'll admit the code I posted is not standard sql. The extension to
the UPDATE statement is written about in Inside SQL Server 7.0 in the
brain teasers section. It was used to calculate running totals.
Jul 20 '05 #9
WangKhar (Wa******@yahoo.com) writes:
Erland - are you referring to the code above here? What do you mean
exactly? Is there some sneakiness of undocumented goodness you are
keeping from us?


No, the problem is that you have no guarantee that the code will always
produce the expected result. A change of query plan or whatever. Could
break with the next service pack.

Here is a KB article on a similar trick. Pay particular attention to
first paragraph under CAUSE:
http://support.microsoft.com/default.aspx?scid=287515.

--
Erland Sommarskog, SQL Server MVP, so****@algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #10
Thats interesting, thanks.

Erland Sommarskog <so****@algonet.se> wrote in message news:<Xn*********************@127.0.0.1>...
WangKhar (Wa******@yahoo.com) writes:
Erland - are you referring to the code above here? What do you mean
exactly? Is there some sneakiness of undocumented goodness you are
keeping from us?


No, the problem is that you have no guarantee that the code will always
produce the expected result. A change of query plan or whatever. Could
break with the next service pack.

Here is a KB article on a similar trick. Pay particular attention to
first paragraph under CAUSE:
http://support.microsoft.com/default.aspx?scid=287515.

Jul 20 '05 #11
Does this help:
http://www.sqlteam.com/item.asp?ItemID=2368

"Jeremy Pridmore" <go*********@pridmorej.freeserve.co.uk> wrote in message
news:9b**************************@posting.google.c om...
Hi All,

Here's a challenge.

If there is a 'one word' answer to this, i.e. the name of a built in
SQL Server function I can use, that would be great! However...

I have a standard 1:m relationship, e.g. tblHeader and tblDetail.

I want to create a view of records from 'tblHeader' and within that
view have a column (called e.g. DetailTypes) that provides a single
comma separated varchar of values from a varchar field (called e.g.
DetailType) that appears in related records in the 'tblDetail' table.
(hope you understood that :)

e.g. the contents of my 'tblDetail' table could be....

Detail ID | Header ID | DetailType
-----------------------------------
1 | 1 | A
2 | 1 | A
3 | 1 | B
4 | 2 | A
5 | 2 | C
6 | 3 | B

Therefore, the view I want to create should return:

Header ID | DetailTypes
-------------------------------
1 | 2A, 1B
2 | 1A, 1C
3 | 1B
i.e. the first row can be read as "Header 1 has 2 'A' detail records
and 1 'B' detail record."

I have created a view e.g. 'vqryHeaders' which calls a user defined
function that takes the HeaderID and opens a cursor on another view,
e.g. 'vqryDetailGrouped'. The other view groups the records in
tblDetail so that I can get a count of each DetailType for each Header
ID. The cursor then loops through the returned records concatenating
the count and detail type into a comma separated string (as shown
above).

However, when I run this across 20k records it is soooo sloooooww. I
have indexes on the relationship fields and I am using realistically
sized varchars - neither made any difference in speed. It is
definately the function that I wrote that slows it down as the view is
lightning fast when I remove my function call.

I can supply source code if necessary, but I think that this is a
kind-of generic problem so I don't see the point - yet.

I really hope you can help.

Regards,

Jezz

Jul 20 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Edward | last post by:
SQL Server 7.0 If I run the following in Query Analyzer I get no records returned: exec GetLeadsOutcome_Dealer '1/1/2003','12/2/2003',10, '176, 183' If, however, I run either : exec...
8
by: Neil | last post by:
I have a very puzzling situation with a database. It's an Access 2000 mdb with a SQL 7 back end, with forms bound using ODBC linked tables. At our remote location (accessed via a T1 line) the time...
15
by: AK | last post by:
Once upon a time there was a table: CREATE TABLE VENDOR(VENDOR_ID INT, NAME VARCHAR(50), STATE CHAR(2))@ in a while the developers realized that a vendor may be present in xseveral states, so...
4
by: Martin Evans | last post by:
Hi, I'm getting: DBD::DB2::db do failed: SQL0440N No authorized routine named "CONCAT" of type "FUNCTION" having compatible arguments was found. SQLSTATE=42884 for some SQL like this:
3
by: wgblackmon | last post by:
I'm currently running the following statement that is used in a Crystal Report. Basically, a record is returned when the T_PAYMENT.amount has a record in the database based on the value of the...
3
by: Cindy | last post by:
I'm trying to use the NEWID function in dynamic SQL and get an error message Incorrect syntax near the keyword 'ORDER'. Looks like I can't do an insert with an Order by clause. Here's the code:...
11
by: Bart op de grote markt | last post by:
Hello, I have a very simple problem which I will illustrate with an example: I have the following records in my table: A 1 C A 2 C A 3 C B 8 K B 9 K
4
by: waqasahmed996 | last post by:
hi to all i have three fields of name in database named as fnam,mname,lname. fname and lname is mandatory field and mname is optional. i want to make a search query on name ...
13
by: ramprakashjava | last post by:
hi, i hav "java.lang.NullPointerException" error while Deleting table records using checkbox in jsp here i enclosed files help quickly plzzz.. ...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.