2014-04-03 75 views
0

什么我现在的工作原理:SQL的使用情况下,where子句

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

直到@payment_type为null,则没有被插入。

任何人都可以帮助我找到一个优雅的方式来做到这一点? (where子句是伪代码)

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 

编辑:我很欣赏的答案,但遗憾的是,以上答案都不对更新表。这个伪代码可以更好地解释需要发生的事情。如果@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 

编辑:我们找到了解决方案,但它不会让我回答我的问题(?8小时也许我应该把我的闹钟),但在这里它是。希望这可以帮助别人:

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 

回答

1

你可以做,使用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) 
1

试试这个 -

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

如何

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)