简体   繁体   中英

SQL - CASE STATEMENT - Count statement and case function

I'm trying to write a case when function within a count statement, but I have a error 4145.

select @CountResult = count(*) from ViewDefinition where DefinitionID = @ObjektID and
    (case 
         when IsGepa=0 and Gepa is not null then @CountResult  
         when NotGepa=0 and GepaListeID is not null then @CountResult  
    end  )

select @CountResult

Try this:

select @CountResult = SUM
(
    CASE when (IsGepa=0 and Gepa is not null ) OR (NotGepa=0 and GepaListeID is not null) THEN 1 ELSE 0 END
)
from ViewDefinition 
where DefinitionID = @ObjektID

Your CASE conditions need to go into the WHERE:

select @CountResult = count(*) 
from ViewDefinition 
where DefinitionID = @ObjektID and
  ((IsGepa=0 and Gepa is not null) or  
   (NotGepa=0 and GepaListeID is not null)  
  )

select @CountResult

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM