[英]SQL using case in a where clause
我現在擁有的作品:
insert GroupAcceptedPaymentType (GroupID, PaymentTypeID)
select
@group_id,
pt.PaymentTypeID
from
PaymentType pt
where charindex(pt.Title, @payment_type) > 0
直到@payment_type為null,然后什么都不會插入。
誰能幫我找到一種優雅的方式嗎? (其中,子句是偽代碼)
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
怎么樣
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)
您可以使用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)
嘗試這個 -
where (@payment_type is null and PaymentTypeID = 2)
or (charindex(pt.Title, @payment_type) > 0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.