简体   繁体   English

在where子句中的SQL用例

[英]SQL using case in a where clause

What I have now works: 我现在拥有的作品:

insert GroupAcceptedPaymentType (GroupID, PaymentTypeID)
    select
        @group_id,
        pt.PaymentTypeID
    from 
        PaymentType pt
    where charindex(pt.Title, @payment_type) > 0

until @payment_type is null, then nothing gets inserted. 直到@payment_type为null,然后什么都不会插入。

Can anyone help me find an elegant way to do this? 谁能帮我找到一种优雅的方式吗? (where clause is pseudocode ) (其中,子句是伪代码)

insert GroupAcceptedPaymentType (GroupID, PaymentTypeID)
    select
        @group_id,
        pt.PaymentTypeID
    from 
        PaymentType pt
    where 
        if @payment_type is null
        PaymentTypeID = 2
        else
        charindex(pt.Title, @payment_type) > 0

Edit: I really appreciate the answers, but unfortunately, none of these answers update the table. 编辑:我真的很感谢答案,但是不幸的是,这些答案都没有更新表格。 This pseudocode may explain better what needs to happen. 此伪代码可能会更好地解释需要发生的情况。 If @payment_type is null, then insert the groupID into the GroupId column, and a value of 2 into the PaymentTypeId column, else run the statement as normal. 如果@payment_type为null,则将groupID插入GroupId列,并将值2插入PaymentTypeId列,否则按常规运行该语句。

        where 
        if @payment_type is null
        INSERT INTO GroupAcceptedPaymentType (GroupID, PaymentTypeID)
        VALUES (GroupId, '2')
        else
        charindex(pt.Title, @payment_type) > 0

Edit: We found the solution, but it won't let me answer my own question(for 8 hours. Maybe I should set my alarm?), but here it is. 编辑:我们找到了解决方案,但是它不会让我回答自己的问题(持续8个小时。也许我应该设置闹钟?),但是就在这里。 Hopefully it helps someone: 希望它可以帮助某人:

if @payment_type <> ''
begin
insert GroupAcceptedPaymentType (GroupID, PaymentTypeID)
select
    @group_id,
    pt.PaymentTypeID
from 
    PaymentType pt
where charindex(pt.Title, @payment_type) > 0
end
else
begin 
INSERT INTO GroupAcceptedPaymentType (GroupID, PaymentTypeID)
    VALUES (@group_id, '2')
end

How about 怎么样

select
    @group_id,
    pt.PaymentTypeID
from 
    PaymentType pt
where 
    (@payment_type is null AND PaymentTypeID = 2)
    OR
    (@payment_type is not null AND charindex(pt.Title, @payment_type) > 0)

You can do that using OR 您可以使用OR

insert GroupAcceptedPaymentType (GroupID, PaymentTypeID)
select
    @group_id,
    pt.PaymentTypeID
from 
    PaymentType pt
where 
    (@payment_type is null AND 
    PaymentTypeID = 2 ) 
    OR 
    (charindex(pt.Title, @payment_type) > 0)

Try this - 尝试这个 -

where (@payment_type is null and PaymentTypeID = 2) 
or (charindex(pt.Title, @payment_type) > 0)

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

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