1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| CREATE PROCEDURE PsGetAnnonces
AS
BEGIN
SET NOCOUNT ON
-- Recherche le nombre d'annonceurs prioritaires
DECLARE @nbAnnonceursPrioritaires TINYINT
SELECT @nbAnnonceursPrioritaires = COUNT(DISTINCT annonceur_id)
FROM dbo.Annonces
WHERE misenvaleur = 1
-- S'il y a 5 annonceurs prioritaires, on tire au "hasard" 5 annonces de ces annonceurs
IF @nbAnnonceursPrioritaires = 5
BEGIN
WITH
CTE_ANNONCEURS_PRIORITAIRES AS
(
SELECT DISTINCT annonceur_id
FROM dbo.Annonces
WHERE misenvaleur = 1
)
SELECT TOP 5 annonce_id, descriptif, prix
FROM dbo.Annonces AS A
JOIN AS CTE_ANNONCEURS_PRIORITAIRES AS C
ON C.annonceur_id = A.annonceur_id
ORDER BY NEWID()
END
ELSE -- il y a moins de 5 annonceurs prioritaires
BEGIN
WITH
-- Recherche les annonceurs prioritaires
CTE_ANNONCEURS_PRIORITAIRES AS
(
SELECT DISTINCT annonceur_id
FROM dbo.Annonces
WHERE misEnValeur = 1
),
-- Recherche les annonceurs non prioritaires
CTE_ANNONCEURS_NON_PRIORITAIRES AS
(
SELECT annonceur_id
FROM dbo.Annonceurs
EXCEPT
SELECT annonceur_id
FROM CTE_ANNONCEURS_PRIORITAIRES
),
-- Extrait les annonces des annonceurs prioritaires
CTE_ANNONCES_PRIORITAIRES AS
(
SELECT TOP (@nbAnnonceursPrioritaires) annonce_id,
descriptif,
prix,
ROW_NUMBER() OVER(ORDER BY NEWID())
FROM dbo.Annonces AS A
JOIN AS CTE_ANNONCEURS_PRIORITAIRES AS C
ON C.annonceur_id = A.annonceur_id
),
-- Extrait les annonces des annonceurs non prioritaires
CTE_ANNONCES_NON_PRIORITAIRES
(
SELECT TOP (5 - @nbAnnonceursPrioritaires) annonce_id,
descriptif,
prix,
ROW_NUMBER() OVER(ORDER BY NEWID())
FROM dbo.Annonces AS A
JOIN CTE_ANNONCEURS_NON_PRIORITAIRES AS NP
ON A.annonceur_id = NP.annonceur_id
)
SELECT annonce_id, descriptif, prix
FROM CTE_ANNONCES_PRIORITAIRES
UNION
SELECT annonce_id, descriptif, prix
FROM CTE_ANNONCES_NON_PRIORITAIRES
END
END |
Partager