简体   繁体   中英

Case Expression inside where clause

I have found a few posts that were very similar to what I am wanting to do, but it didn't seem to work. I have this case in my select:

case 
        when h.Posted_Flag=-1 and h.Returned_Flag=0 then 'Posted'
        when h.Posted_Flag=0 then 'Unposted'
        when h.Returned_Flag=1 and h.Posted_Flag=-1 then 'Returned'
        when h.Returned_Flag = 2 then 'Partial Return'
        else '*****'
end as Return_Status,

I would like to place this in my where clause and equal to a variable I have set:

Declare @TicketStatus nvarchar
set @TicketStatus = 'Returned'

and @TicketStatus=(case 
            when h.Posted_Flag=-1 and h.Returned_Flag=0 then 'Posted'
            when h.Posted_Flag=0 then 'Unposted'
            when h.Returned_Flag=1 and h.Posted_Flag=-1 then 'Returned'
            when h.Returned_Flag = 2 then 'Partial Return'
            end)

When I try to run what I have, I get no records returned, when I run this without the AND(case) there are many Retunred Status's with Returned in them.

any help would be great.

thanks BD

This is a problem with how you declared your variable. What happens if you do this?

Declare @TicketStatus nvarchar
set @TicketStatus = 'Returned'

SELECT @TicketStatus

The returned value is 'R' , not 'Returned' , this happens because you didn't give a length to your variable. You should do this:

Declare @TicketStatus nvarchar(15)
set @TicketStatus = 'Returned'

您为什么不只使用条件?

h.Returned_Flag=1 and h.Posted_Flag=-1

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