OVH Cloud OVH Cloud

ORDER BY et CASE

2 réponses
Avatar
David T
re boujour !

je cale sur une clause ORDER BY qui contient un CASE
Je souhaite faire qq chose comme :

declare @a int
select @a =3D 2

select top 10 * from UBI_KATALOG_PROD
order by case @a
when 1 then PRODUCT_ID, BU=20
when 2 then DESCR254
end

Ca marche si j'ai 1 seul champ (cas 2 dans l'exemple) mais=20
=E7a ne passe pas =E0 la compilation pour la cas 1 (erreur de=20
syntaxe - qui est ma foi logique). Je ne peux pas non plus=20
mettre de "DESC" derri=E8re le nom du champ.

Qq un aurait une id=E9e sur la bonne syntaxe ?

Merci

David Trillaud
Ubisoft Entertainment

2 réponses

Avatar
David T
ah j'ai trouvé !
si ça peut servir à qq un ...


Il faut faire qq chose comme ça :

declare @a int
select @a = 1

select top 100 * from UBI_KATALOG_PROD
order by case @a
when 1 then PRODUCT_ID
when 2 then DESCR254
end
DESC,
case @a
when 1 then BU
end
DESC


-----Original Message-----
re boujour !

je cale sur une clause ORDER BY qui contient un CASE
Je souhaite faire qq chose comme :

declare @a int
select @a = 2

select top 10 * from UBI_KATALOG_PROD
order by case @a
when 1 then PRODUCT_ID, BU
when 2 then DESCR254
end

Ca marche si j'ai 1 seul champ (cas 2 dans l'exemple)


mais
ça ne passe pas à la compilation pour la cas 1 (erreur de
syntaxe - qui est ma foi logique). Je ne peux pas non


plus
mettre de "DESC" derrière le nom du champ.

Qq un aurait une idée sur la bonne syntaxe ?

Merci

David Trillaud
Ubisoft Entertainment
.



Avatar
Steve Kass
Si les types de PRODUCT_ID et DESCR254 ne sont pas
compatible l'un à l'autre, on peut eviter l'erreur de conversion
comme:

order by
case when @a = 1 then PRODUCT_ID end,
case when @a = 2 then DESCR254 end desc,
case when @a = 1 then BU end desc

Si @a = 1, on a
order by PRODUCTID, NULL desc, BU desc
Si @a = 2, on a
order by NULL, DESCR254 desc, NULL desc
...

L'effet des NULLs sera négligeable.

Steve Kass
Drew University

David T wrote:

ah j'ai trouvé !
si ça peut servir à qq un ...


Il faut faire qq chose comme ça :

declare @a int
select @a = 1

select top 100 * from UBI_KATALOG_PROD
order by case @a
when 1 then PRODUCT_ID
when 2 then DESCR254
end
DESC,
case @a
when 1 then BU
end
DESC




-----Original Message-----
re boujour !

je cale sur une clause ORDER BY qui contient un CASE
Je souhaite faire qq chose comme :

declare @a int
select @a = 2

select top 10 * from UBI_KATALOG_PROD
order by case @a
when 1 then PRODUCT_ID, BU
when 2 then DESCR254
end

Ca marche si j'ai 1 seul champ (cas 2 dans l'exemple)




mais


ça ne passe pas à la compilation pour la cas 1 (erreur de
syntaxe - qui est ma foi logique). Je ne peux pas non




plus


mettre de "DESC" derrière le nom du champ.

Qq un aurait une idée sur la bonne syntaxe ?

Merci

David Trillaud
Ubisoft Entertainment
.