473,757 Members | 10,754 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Select Distinct - Incorrect result

I have a function that is designed to return a variable that contains
concatenated values from a partinular field in the returned rows:

DECLARE @output varchar(8000)
SELECT
@output =
CASE
WHEN @output IS NULL THEN CAST(TSD.Schedu ledTime AS
varchar(4))
ELSE @output+ ', '+ ISNULL(CAST(TSD .ScheduledTime AS
varchar(4)),'')
END
FROM TSD
WHERE ClientGUID = 200000144702000 1 AND
ParentGUID = 600000668406800 1
Select @output

The variable returned with this code contains:

"1200, 1400, 1200, 1400"

I want to only get the unique values so that the variable returns "1200,
1400". Seems simple enough just to add DISTINCT to the SELECT statement.
However, what is returned is simply "1400".

I cannot figure out why that is the case. Is there any explanation to this
result?

Side note: I can work around this by using a cursor but I would like to
know why DISTINCT does not work.

Many thanks in advance for any help that can be provided!

Pat

Jul 20 '05 #1
5 5390
Pat L (is****@telusZ. net) writes:
I have a function that is designed to return a variable that contains
concatenated values from a partinular field in the returned rows:

DECLARE @output varchar(8000)
SELECT
@output =
CASE
WHEN @output IS NULL THEN CAST(TSD.Schedu ledTime AS
varchar(4))
ELSE @output+ ', '+ ISNULL(CAST(TSD .ScheduledTime AS
varchar(4)),'')
END
FROM TSD
WHERE ClientGUID = 200000144702000 1 AND
ParentGUID = 600000668406800 1
Select @output


The result of this query is undefined. You may get what you want, you
may get something else. It appears that when you use DISTINCT, the latter
applies.

See http://support.microsoft.com/default.aspx?scid=287515. Pay
particular attention to the first paragraph under CAUSE.

So a cursor is the way to go this time.
--
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 #2

"Erland Sommarskog" <so****@algonet .se> wrote in message
news:Xn******** *************@1 27.0.0.1...
<snip> The result of this query is undefined. You may get what you want, you
may get something else. It appears that when you use DISTINCT, the latter
applies.

See http://support.microsoft.com/default.aspx?scid=287515. Pay
particular attention to the first paragraph under CAUSE.

So a cursor is the way to go this time.
--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp


Thanks you so much for the quick response Erland!

I read the article but since it does not actually use or refer to DISTINCT,
and I don't use the order by clause, where is the connection?

Pat
Jul 20 '05 #3
DISTINCT performs an implict sort of the table with the same effect.

From the doc that Erland posted: "The correct behavior for an aggregate
concatenation query is undefined". In other words the behaviour your query
assumes is an undocumented feature and there are no guarantees that the
result will always be what you expect.

The result you described with SELECT DISTINCT is actually correct according
to BOL:

SELECT @local_variable is usually used to return a single value into the
variable. It can return multiple values if, for example, expression is the
name of a column. If the SELECT statement returns more than one value, the
variable is assigned the last value returned.

http://msdn.microsoft.com/library/en...a-ses_978l.asp

Returning a comma-delimited list from a table is a presentational task which
may be better done in your client application or reporting tool.

--
David Portas
SQL Server MVP
--
Jul 20 '05 #4
Pat L (is****@telusZ. net) writes:
I read the article but since it does not actually use or refer to
DISTINCT, and I don't use the order by clause, where is the connection?


There is no connection to DISTINCT, but there is a connection to things
like "SELECT @x = @x + col FROM tbl" in general, and the article says
that a statement like this has no defined result.
--
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 #5
Thanks David (and again to Erland).

Pat

"David Portas" <RE************ *************** *@acm.org> wrote in message
news:3r******** ************@gi ganews.com...
DISTINCT performs an implict sort of the table with the same effect.

From the doc that Erland posted: "The correct behavior for an aggregate
concatenation query is undefined". In other words the behaviour your query
assumes is an undocumented feature and there are no guarantees that the
result will always be what you expect.

The result you described with SELECT DISTINCT is actually correct according to BOL:

SELECT @local_variable is usually used to return a single value into the
variable. It can return multiple values if, for example, expression is the
name of a column. If the SELECT statement returns more than one value, the
variable is assigned the last value returned.

http://msdn.microsoft.com/library/en...a-ses_978l.asp

Returning a comma-delimited list from a table is a presentational task which may be better done in your client application or reporting tool.

--
David Portas
SQL Server MVP
--

Jul 20 '05 #6

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

Similar topics

5
6262
by: Ralph Freshour | last post by:
I have a question about the following PHP script - I got it off a web site tutorial on how to count users logged into your site - my question is the $PHP_SELF variable - it writes the name of the web page to the 'file' field in the table - I don't understand why it is doing that - I mean, isn't the SELECT DISTINCT statement only pulling those records from that one web page? I guess I just don't follow what it is doing with that SELECT...
5
11690
by: Martin Feuersteiner | last post by:
Dear Group I'm having trouble with the clause below. I would like to select only records with a distinct TransactionDate but somehow it still lists duplicates. I need to select the TransactionDate once as smalldatetime and once as varchar as I'm populating a drop-down with Text/Value pairs. So I can't just use 'SELECT DISTINCT TransactionDate FROM...' I'm grateful for any hints.
17
5028
by: kalamos | last post by:
This statement fails update ded_temp a set a.balance = (select sum(b.ln_amt) from ded_temp b where a.cust_no = b.cust_no and a.ded_type_cd = b.ded_type_cd and a.chk_no = b.chk_no group by cust_no, ded_type_cd, chk_no)
6
5557
by: John M | last post by:
Hi, The line below is used to feed a combobox. (It is from a database which is used to log pupil behaviour!) The 'incidents' table contains a list of students who have been involved in incidents. Some may appear several times, hence the Distinct. However, thelist generated should still be sorted by Surname. When I add Order by I'm told it conflict with the 'Distinct'. Surely it does not? SELECT DISTINCT ., . & " " & . FROM...
18
3061
by: mathilda | last post by:
My boss has been adamant that SELECT DISTINCT is a faster query than SELECT all other factors being equal. I disagree. We are linking an Access front end to a SQL Server back end and normally are only returning one record. She states that with disctinct the query stops as soon as it finds a matching record. Both of us are relative novices in database theory (obviously). Can someone help settle this?
6
13570
by: Bob Stearns | last post by:
I am getting unwanted duplicate rows in my result set, so I added the DISTINCT keyword to my outermost SELECT. My working query then returned the following message: DB2 SQL error: SQLCODE: -214, SQLSTATE: 42822, SQLERRMC: CASE...;ORDER BY;2 Message: An expression in the ORDER BY clause in the following position, or starting with "CASE..." in the "ORDER BY" clause is not valid. Reason code = "2".  More exceptions ... DB2 SQL error:...
3
12874
by: chrisg | last post by:
Hi all. I'm really stuck with getting the right output from a XML query. Given this structure: create table GENCMP.SCRIPTS ( SCRIPT_ID CHAR(10) not null, PAGE_NO INTEGER not null );
4
3536
by: WiseG1rly | last post by:
Hey everyone! Still working on a site I posted for a while ago. Essentially I have a search function that is populated through by a database in mySQL and PHP. I need a few things to help the finishing touches on this... I need to have a "select all" option in each pulldown menu that will select all rows, and pass them onto the next page so that they can still be selected. Hopefully this makes sense. Here is the code for the first...
0
2660
enfuego
by: enfuego | last post by:
The code below give an error of Msg 170, Level 15, State 1, Line 5 Line 5: Incorrect syntax near '='. Msg 170, Level 15, State 1, Line 8 Line 8: Incorrect syntax near '='. I Am not sure why. Plz advize. Thank you in advance. SELECT xxx.reviews.id, xxx.reviews.techCompany, xxx.reviews.jobSummary, xxx.reviews.inspectionDate, xxx.callTypeReview.reviewId, xxx.callTypeReview.callType, xxx.findingsComments.reviewId,...
0
9489
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
10072
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...
1
9885
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
8737
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
6562
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
5329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3829
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2698
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.