2013-06-13 4 views
1

J'ai un sql qui continue à me donner une exception, et je n'arrive pas à comprendre pourquoi, mon quess est que l'avg (x.Points) renvoie null pour une raison quelconque, comment puis-je le faire retourner 0 dans ce cas?TSQL update check if null

UPDATE a 
SET a.Points = (SELECT avg(x.Points) FROM 
    (SELECT TOP 5 * 
    FROM [dbo].[AlbumImages] i 
    WHERE i.AlbumId = a.Id 
    AND i.Points > 0 
    ORDER BY i.Points Desc) x) 
FROM [dbo].[Albums] a 
    join [dbo].[Users] u on a.UserId = u.Id 
WHERE u.DoRanking = 1 

Cela me donne l'exception

Cannot insert the value NULL into column 'Points', 
table 'Cosplay.dbo.Albums'; column does not allow nulls. UPDATE fails. 
+0

faire un cas où le (SELECT avg (x.Points) FROM (SELECT TOP 5 * FROM [dbo]. [AlbumImages] i où i.AlbumId = a.Id ET i.points> 0 ORDER BY i.Points Desc) x) –

+0

Peut-être intéressant, la raison pour laquelle vous obtenez NULL est qu'il n'y a pas de valeurs. 'AVG' sur un ensemble vide est' NULL'. –

Répondre

3

Vous pouvez vérifier avec ISNULL la fonction AVG. ISNULL prend un second paramètre à renvoyer lorsque l'expression est nulle.

UPDATE a 
SET a.Points = (SELECT ISNULL(avg(x.Points),0) 
       FROM (SELECT TOP 5 * 
         FROM [dbo].[AlbumImages] i 
         WHERE i.AlbumId = a.Id 
         AND i.Points > 0 
         ORDER BY i.Points Desc) x) 
FROM [dbo].[Albums] a 
    join [dbo].[Users] u on a.UserId = u.Id 
WHERE u.DoRanking = 1 
+0

Merci, acception en 9 min, une limite sur quand je peux accepter! – Androme

+0

Ça a marché comme un charme! – Androme

+0

@DoomStone acceptation –