J'ai une requête qui fonctionne:mot-clé SQL Distinct dans l'instruction d'affectation
DECLARE @ProductID int
SET @ProductID = '1234'
SELECT DISTINCT TOP 12 a.ProductID
FROM A a
WHERE a.CategoryID IN (SELECT b.CategoryID FROM B b WHERE b.ProductID = @ProductID)
AND a.ProductID != @ProductID
Il retourne une liste de 12 numéros de produits, tous uniques.
Je dois stocker ces résultats dans une variable, séparée par des virgules, car c'est ce dont la procédure stockée par un tiers a besoin. J'ai donc ceci:
DECLARE @ProductID int
DECLARE @relatedprods varchar(8000)
SET @ProductID = '1234'
SET @relatedprods = ''
SELECT TOP 12 @relatedprods = @relatedprods + CONVERT(VARCHAR(20), a.ProductID) + ', '
FROM A a
WHERE a.CategoryID IN (SELECT b.CategoryID FROM B b WHERE B.ProductID = @ProductID)
AND a.ProductID != @ProductID
SELECT @relatedprods
Maintenant, aucun d'entre eux sont distincts, mais il retourne 12 lignes.
Maintenant, j'ajouter la « distincte » revenir, comme dans la première requête:
DECLARE @ProductID int
DECLARE @relatedprods varchar(8000)
SET @ProductID = '1234'
SET @relatedprods = ''
SELECT DISTINCT TOP 12 @relatedprods = @relatedprods + CONVERT(VARCHAR(20), a.ProductID) + ', '
FROM A a
WHERE a.CategoryID IN (SELECT b.CategoryID FROM B b WHERE B.ProductID = @ProductID)
AND a.ProductID != @ProductID
SELECT @relatedprods
Un seul produit est retourné dans la liste séparée par des virgules! Est-ce que 'distinct' ne fonctionne pas dans les instructions d'affectation? Qu'ai-je fait de mal? Ou y a-t-il un moyen de contourner cela?
Merci d'avance!
CONCLUSION:
Je ne sais pas ce qui cause ce problème, bien que la conjecture proposée semble logique. Je suis en mesure de résoudre ce problème par la sous-requête, et je l'afficher pour que les autres puissent voir la solution:
DECLARE @ProductID int
DECLARE @relatedprods varchar(8000)
SET @ProductID = '1234'
SET @relatedprods = ''
SELECT @relatedprods = @relatedprods + CONVERT(VARCHAR(20), c.ProductID) + ','
FROM (SELECT DISTINCT TOP 12 a.ProductID FROM A a WHERE a.CategoryID IN
(SELECT b.CategoryID
FROM B b
WHERE B.ProductID = @ProductID)
AND a.ProductID != @ProductID) c
SET @relatedprods = SUBSTRING(@relatedprods, 0, LEN(@relatedprods))
SELECT @relatedprods
@Brandi - Quelle version de SQL Server? – Thomas
@Thomas - SQL Server 2008 – Brandi