473,794 Members | 2,748 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Compile/combine the contents of several records.

I have the following table;

CREATE TABLE [x_Note] (
[x_NoteId] [int] IDENTITY (1, 1) NOT NULL ,
[Note] [varchar] (7200) COLLATE SQL_Latin1_Gene ral_Pref_CP1_CI _AS NOT
NULL ,

CONSTRAINT [PK_x_NoteId] PRIMARY KEY CLUSTERED
(
[x_NoteId],
) WITH FILLFACTOR = 90 ON [USERDATA] ,

) ON [USERDATA]
GO

My clients want me to take the contents of the Note column for each row
and combine them. In other words, they basically want:

Note = Note [accumulated from previous rows] + Char(13) [because they
want a carriage return] + Note [from current record].

What is the most efficient and relatively painless way to do this? I
think it might require a cursor, but I'm not sure if there is a more
elegant set-based method to make this happen.

Dec 5 '05 #1
14 2413
Stu
There's not a set-based method; the BEST method is to use the client
application to accomplish this. Visual Basic, C#, Java, etc, are all
desigined for munging arrays in this fashion.

If you must do this on the SQL side (for email reports, etc), then you
can use a cursor. But cursor performance will suck.

Stu

Dec 5 '05 #2
Which kind of cursor would "suck" the least? Is there a way to
construct the code to be more efficient?

Dec 5 '05 #3
Stu
SQL Server is not really designed to handle cursors; in some cases,
they are unavoidable, but they just don't perform well compared to a
set-based solution. What client are you using to present this data to
your customers? Whatever it is has to be better than a SQL cursor.

Stu

Dec 5 '05 #4
Trust me, this has to be a cursor. I'm just wondering how I can make
it happen.

Dec 5 '05 #5
im************* ******@yahoo.co m wrote:
I have the following table;

CREATE TABLE [x_Note] (
[x_NoteId] [int] IDENTITY (1, 1) NOT NULL ,
[Note] [varchar] (7200) COLLATE SQL_Latin1_Gene ral_Pref_CP1_CI _AS NOT
NULL ,

CONSTRAINT [PK_x_NoteId] PRIMARY KEY CLUSTERED
(
[x_NoteId],
) WITH FILLFACTOR = 90 ON [USERDATA] ,

) ON [USERDATA]
GO

My clients want me to take the contents of the Note column for each row
and combine them. In other words, they basically want:

Note = Note [accumulated from previous rows] + Char(13) [because they
want a carriage return] + Note [from current record].

What is the most efficient and relatively painless way to do this? I
think it might require a cursor, but I'm not sure if there is a more
elegant set-based method to make this happen.


This looks pretty odd. If the average size of data in the Note column
is just half of your maximum size then you'll only be able to
concatenate two rows before you break the 8000 character ceiling. This
means you will most likely have to return a result set rather than a
variable (TEXT variables not allowed). But you want each value
delimited with carriage returns and most clients will display a
multiple row result set as multiple lines anyway - so what can you hope
to gain from concatenating them?

The above comments apply to SQL Server 2000. In SQL Server 2005 you can
do some fancy stuff like the following. Please always specify what
version you are using so that we don't have to guess.

WITH X (note, row_no)
AS
(
SELECT CAST(note AS VARCHAR(MAX)),
ROW_NUMBER() OVER (ORDER BY x_noteid)
FROM x_note
)
SELECT
MAX(CASE row_no WHEN 1 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE row_no WHEN 2 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE row_no WHEN 3 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE row_no WHEN 4 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE row_no WHEN 5 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE row_no WHEN 6 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE row_no WHEN 7 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE row_no WHEN 8 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE row_no WHEN 9 THEN note+CHAR(13) ELSE '' END)
/* ... etc */
AS note
FROM X ;

SELECT REPLACE( REPLACE(
(SELECT note
FROM x_note
ORDER BY
x_noteid
FOR XML PATH (''))
, '<note>', CHAR(13)),'</note>','') AS note ;

IMO clientside is the best option though.

--
David Portas
SQL Server MVP
--

Dec 5 '05 #6
im************* ******@yahoo.co m (im************ *******@yahoo.c om) writes:
I have the following table;

CREATE TABLE [x_Note] (
[x_NoteId] [int] IDENTITY (1, 1) NOT NULL ,
[Note] [varchar] (7200) COLLATE SQL_Latin1_Gene ral_Pref_CP1_CI _AS
NOT
NULL ,

CONSTRAINT [PK_x_NoteId] PRIMARY KEY CLUSTERED
(
[x_NoteId],
) WITH FILLFACTOR = 90 ON [USERDATA] ,

) ON [USERDATA]
GO

My clients want me to take the contents of the Note column for each row
and combine them. In other words, they basically want:

Note = Note [accumulated from previous rows] + Char(13) [because they
want a carriage return] + Note [from current record].

What is the most efficient and relatively painless way to do this? I
think it might require a cursor, but I'm not sure if there is a more
elegant set-based method to make this happen.


In SQL 2000, a cursor is the only defined way to do this, but you
can only compose a string which is 8000 chars long.

In SQL 2005, you can do this painlessly, thanks to some syntax from
the XML corner of SQL 2005:

select substring(List, 1, datalength(List )/2 - 1)
-- strip the last CR from the list
from
(select Note + char(13) as [text()]
from x_Note
order by x_NoteId
for xml path('')) as Dummy(List)

A bit obscure, but it works!
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for
SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Dec 5 '05 #7
Okay, now I have a new variation to this problem. Let's change the DDL
slightly:

CREATE TABLE [x_Note] (
[x_NoteId] [int] IDENTITY (1, 1) NOT NULL ,
[NoteCategory] [int] NOT NULL ,
[Note] [varchar] (7200) COLLATE
SQL_Latin1_Gene ral_Pref_CP1_CI _AS NOT
NULL ,
CONSTRAINT [PK_x_NoteId] PRIMARY KEY CLUSTERED
(
[x_NoteId],
) WITH FILLFACTOR = 90 ON [USERDATA] ,
) ON [USERDATA]
GO

Instead of combining the contents of the Note column for each row, we
need to combine the Notes within each NoteCategory. In other words, I
need to combine the Notes for all rows of NoteCategory #1, all the
Notes for NoteCategory #2, and so on.

In other words, FOR EACH NoteCategory, the clients want:

Note = Note [accumulated from previous rows within the NoteCategory] +
Char(13) [because they want a carriage return] + Note [from current
record within the NoteCategory].

Now, I have NO idea how to pull this off. I was considering nested
cursors, but I'm not sure if that is the best way, or even a practical
way. Help!!!

Dec 7 '05 #8
im************* ******@yahoo.co m wrote:
Okay, now I have a new variation to this problem. Let's change the DDL
slightly:

CREATE TABLE [x_Note] (
[x_NoteId] [int] IDENTITY (1, 1) NOT NULL ,
[NoteCategory] [int] NOT NULL ,
[Note] [varchar] (7200) COLLATE
SQL_Latin1_Gene ral_Pref_CP1_CI _AS NOT
NULL ,
CONSTRAINT [PK_x_NoteId] PRIMARY KEY CLUSTERED
(
[x_NoteId],
) WITH FILLFACTOR = 90 ON [USERDATA] ,
) ON [USERDATA]
GO

Instead of combining the contents of the Note column for each row, we
need to combine the Notes within each NoteCategory. In other words, I
need to combine the Notes for all rows of NoteCategory #1, all the
Notes for NoteCategory #2, and so on.

In other words, FOR EACH NoteCategory, the clients want:

Note = Note [accumulated from previous rows within the NoteCategory] +
Char(13) [because they want a carriage return] + Note [from current
record within the NoteCategory].

Now, I have NO idea how to pull this off. I was considering nested
cursors, but I'm not sure if that is the best way, or even a practical
way. Help!!!


You still didn't tell us what version of SQL Server you are using. Nor
have you explained why you can't do this client side.

Try:

SELECT notecategory,
MAX(CASE seq WHEN 1 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE seq WHEN 2 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE seq WHEN 3 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE seq WHEN 4 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE seq WHEN 5 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE seq WHEN 6 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE seq WHEN 7 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE seq WHEN 8 THEN note+CHAR(13) ELSE '' END)+
MAX(CASE seq WHEN 9 THEN note+CHAR(13) ELSE '' END)
/* ... etc */
AS note
FROM
(SELECT T1.notecategory , T1.x_noteid, T1.note, COUNT(*) seq
FROM x_note AS T1
JOIN x_note AS T2
ON T1.notecategory = T2.notecategory
AND T1.x_noteid >= T2.x_noteid
GROUP BY T1.notecategory , T1.x_noteid, T1.note) AS T
GROUP BY notecategory ;

--
David Portas
SQL Server MVP
--

Dec 7 '05 #9
Sorry. I am using SQL Server 2000, and we can't do this client side
because: 1) we are doing a data migration from an older app with a SQL
Server 2000 back end and 2) our clients won't let us take a client-side
approach to this problem.

Dec 7 '05 #10

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

Similar topics

1
3167
by: Ken Fine | last post by:
I want to take the contents of many fields of various datatypes (varchars and text) and combine them into a single "junk" field that I will perform SQL Server free text searching upon, e.g.: tblArticles Title Subtitle ArticleText CombinedField
9
3734
by: Steve Jorgensen | last post by:
Hi all, I'm working on the schema for a database that must represent data about stock & bond funds over time. My connundrum is that, for any of several dimension fields, including the fund name itself, the dimension may be represented in different ways over time, and may split or combine from one period to the next. When querying from the database for an arbitrary time period, I need the data to be rolled up to the smallest extent...
8
7104
by: mark | last post by:
Access2000 How do I write a query that combines the CTC field from each record below into one record? I need to concatenate the CTC field with a separator, like below: BattID VehicleID STDATE STTIME CTC LKO500HF 00000000 10/27/2003 4:13:51 AM 4 LKO500HF 00000000 10/27/2003 5:13:51 AM 5 LKO500HF 00000000 10/27/2003 10:13:51 AM 6 LKO500HF 00000000 10/27/2003 11:13:51 AM 4
1
2995
by: snOOp | last post by:
I am trying to combine the data from two similar tables into one query, but I need for all of the records from both tables to show up and I want the ones that have matching 'emplid' to be combined into one record showing both the 'empstatus' and 'strole' fields. The following query works, but does not combine the matching records: SELECT givenname, sn, empstatus, emplid, ssn FROM dbo_EmpData WHERE empstatus='A' UNION ALL SELECT...
3
1499
by: steve_h | last post by:
I think the subject says it all, but just in case: I know that I can call my own methods during an XSL transformation using <xsl:value-of select="myObject.someMethod(arg1)" /> having done something like: dim xslTrans as System.Xml.Xsl.Xsltransform
1
2197
by: Beowulf | last post by:
I have a report laid out in Design View as shown at the end of this message. I have code that performs the following steps: 1. In main report's Report_Open(), DELETE any old rows in tblTOC for this username. 2. In main report's CategoryHeader_Format(), add a row to tblTOC with the current category name and the current page number. 3. In the table of contents subreport, Cancel if NoData event fires.
4
3684
by: musicloverlch | last post by:
I have a table with multiple records in it. I am being forced to combine multiple records into one record in order to be uploaded to a website, and I only get one record per client. How can I systematically combine multiple records into 1? The table looks like this Client ID Service Status 1 Doc Pending 1 Test Pending
1
2237
by: rdraider | last post by:
Hi all, We have an app that uses SQL 2000. I am trying to track when a code field (selcode) is changed on an order which then causes a status field (status) to change. I tried a trigger but the app may use 2 different update statements to change these fields depending on what the user does. When the trigger fires (on update to selcode), the status field has already been changed. So my trigger to record the changes from inserted and...
1
3418
by: bluereign | last post by:
Thank you for your assistance. I am a novice looking to JOIN and append or combine records from 2 current Tables into 2 new Tables named below. I have been able to JOIN Tables with the script below. My problem is if I don’t use the WHERE clause in my script below, the script can query up to 3 records with the same “LoanNo” due to the fact that there can be up to 3 “TypeCodes” in each Table (Borrower, Co-Borrower 1 and Co-Borrower 2...
0
9671
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10433
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10212
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10161
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10000
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9035
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6777
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2919
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.