Errore di conversione del tipo di dati Varchar in galleggiante - è correlato
-
29-10-2019 - |
Domanda
Nota: ho letto thread simili su SO ma non sono stato di aiuto in questa query.
Ho riprodotto il seguente codice dove è simile al mio vero problema. Devo usare questa sintassi perché è già stata utilizzata nel database, a meno che non vi sia un consiglio convincente, la logica è sbagliata qui.
Nel mio vero problema, questa query funziona più del tempo ma fallisce in un certo tempo. Dopo aver studiato ho scoperto che il problema è
ISNULL(amount,0)
Questo perché se una categoria ha entrambi valori 0,0 o entrambi i valori null, null, ISNULL
li rende una stringa e quindi ottengo
Errore di conversione del tipo di dati Varchar in galleggiante
Quello che segue è il mio codice di prova con commenti
create table #table1 (
id int not null primary key identity,
category varchar(10),
amount float null
)
insert into #table1 values('A',23)
insert into #table1 values('A',23)
insert into #table1 values('B',NULL)
insert into #table1 values('B',0)
insert into #table1 values('C',NULL)
insert into #table1 values('C',NULL)
insert into #table1 values('D',0)
insert into #table1 values('D',0)
select * from #table1 -- works
select category, sum1 -- works
from
(select category, SUM(Round(ISNULL(amount,0),0)) as Sum1 from #table1
group by category) D
select category, sum2 = -- does not work
case Sum1
when 'A' then Sum1 * 1 -- my problem is here
when 'B' then Sum1 * 2 -- this is the logic in my actual code
when 'C' then Sum1 * 3 -- would like to make this query work
when 'D' then Sum1 * 4
else Sum1
end
from
(select category, SUM(Round(ISNULL(amount,0),0) ) as Sum1 from #table1
group by category) D
Che cosa sto facendo di sbagliato?
Soluzione
La tua dichiarazione del caso non dovrebbe essere "Categoria dei casi" e non "Case Sum1"?
Se lo cambi, la query funziona come previsto.
Altri suggerimenti
Il tuo caso deve guardare a categoria non sum1
select category, sum2 = -- does not work
case category
when 'A' then Sum1 * 1 -- my problem is here
when 'B' then Sum1 * 2 -- this is the logic in my actual code
when 'C' then Sum1 * 3 -- would like to make this query work
when 'D' then Sum1 * 4
else Sum1
end
from
(select category, SUM(Round(ISNULL(amount,0),0) ) as Sum1 from #table1
group by category) D