简体   繁体   English

where子句中的案例表达

[英]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: 我想将此放置在我的where子句中,并等于我设置的变量:

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. 当我尝试运行自己拥有的内容时,没有返回任何记录,而在没有AND(case)的情况下运行此记录时,它们中有许多带有Returned的Retunred Status。

any help would be great. 任何帮助都会很棒。

thanks BD 谢谢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. 返回值是'R' ,而不是'Returned' ,发生这种情况是因为您没有提供变量的长度。 You should do this: 你应该做这个:

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

您为什么不只使用条件?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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