我有两个参数,@ ID和@Name,我也有两个单独的输入字段,只有一个必须执行,唯一一个将被执行的是非空的,或者如果你有一个其他方法的想法,请帮助
示例查询字符串:
"SELECT * FROM accounts WHERE id = @ID or name = @Name"
我的查询字符串:
select
i.ssn_or_tin,
x.name,
i.cusid,
x.account_no,
i.dateTrans,
i.transCode,
d.TransDesc,
i.transdescription_1,
i.debit_or_credit,
coalesce((case when i.debit_or_credit = 'Dr' then i.debit end),0) as Debit,
coalesce((case when i.debit_or_credit = 'Cr' then i.debit end),0) as Credit,
(coalesce(c.debit,0))as cashin,
i.source
from source_ips i left join
(select distinct * from source_cash_in_original where transCode ='966') as c on (i.ssn_or_tin =c.ssntin and i.cusid=c.cusid and i.accountNo = c.accountNo) and i.dateTrans=c.dateTrans and i.transCode='131' left join
(select distinct * from source_cash_out_original where transCode ='936') as o on (i.ssn_or_tin =o.ssntin and i.cusid=o.cusid and i.accountNo = o.accountNo) and i.dateTrans=o.dateTrans and i.transCode='131' left join
TransDescriptions d on i.transCode = d.TransCode
left join (select a.customer_id,a.account_no,d.ssn_or_tin,a.name from customer_account a left outer join customer_data d on a.customer_id =d.customer_id)as x on i.ssn_or_tin = x.ssn_or_tin and i.cusid=x.customer_id and i.accountNo = x.account_no
where (i.ssn_or_tin = @ssn_or_tin or @ssn_or_tin is null or x.name = @name or @name is null) and i.dateTrans between '2014-12-01' and '2016-08-02' order by i.dateTrans ASC
答案 0 :(得分:0)
IF @NAME is null
( SELECT * FROM accounts WHERE id = @ID ) ;
ELSE
(SELECT * FROM accounts WHERE id = @NAME) ;
答案 1 :(得分:0)
通用机制是:
SELECT a.*
FROM accounts a
WHERE a.id = @ID OR @ID IS NULL OR
a.name = @Name OR @Name IS NULL;
请注意。如果您在id
和name
上有索引,则不会使用它们(可能)。根据数据库的不同,您可能需要动态SQL才能在两种情况下都使用索引(这是因为在第一次运行存储过程时编译查询)。