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 2000 Forums
 SQL Server Development (2000)
 Unexpected result w/ DISTINCT and variable concat

Author  Topic 

ThreePea
Yak Posting Veteran

83 Posts

Posted - 2005-10-10 : 12:13:36
Hey everyone,

A co-op here at work just stumped me with the following:

USE Northwind
go
DECLARE @lastname_list VARCHAR(50)
SET @lastname_list = ''

SELECT
--DISTINCT
@lastname_list = @lastname_list + E.LastName + ','
FROM Employees AS E
WHERE E.EmployeeID IN (1,2)

SELECT @lastname_list

When you run this as-is, you get the expected result. However, if you uncomment the DISTINCT, you only get the first column in the variable. This surprised me. According to BOL, DISTINCT specifieds only unique rows can be in the result set; so I don't see how or why the query is stopped after the first row because it would still be unique if all the rows are processed.

(Yes, yes, I know the right answer is just "don't use the DISTINCT", but he asked me *why* and he thinks I know everything. I can't disappoint him. )

Thanks.

3P

Kristen
Test

22859 Posts

Posted - 2005-10-10 : 12:25:53
You are preventing the assignment working as you intended using DISTINCT. What you would need to do is:

SELECT @lastname_list = @lastname_list + X.LastName + ','
FROM
(
SELECT DISTINCT E.LastName
FROM Employees AS E
WHERE E.EmployeeID IN (1,2)
) X

Kristen
Go to Top of Page
   

- Advertisement -