我的代码运行速度非常慢。下面的伪代码。
if flag = 'y'
Begin
insert into W ( a, b, c)
select (case
when creditCard = 'N' then dbo.GetDecimal(W.USD)
when creditCard ='Y' then -dbo.GetDecimal(W.USD) end,
case
when creditCard = 'N' then dbo.GetDecimal(W.EUR)
when creditCard ='Y' then -dbo.GetDecimal(W.EUR) end,
A.c)
from table Wallet W
left outer join Country C (nolock)
on C.Location = W.Location
inner join Seller S (nolock)
on S.branch=S.branch and S.customerbase=W.customerbase and S.detail=''
where not (W.Location = 'USA' or (len(W.Location)=3 and upper(substring(W.Location,3,1))='A'))
end
else
begin
insert into W (d, e, f)
select (case
when creditCard = 'N' then dbo.GetDecimal(W.USD)
when creditCard ='Y' then -dbo.GetDecimal(W.USD) end,
case
when creditCard = 'N' then dbo.GetDecimal(W.EUR)
when creditCard ='Y' then -dbo.GetDecimal(W.EUR) end,
W.f)
from table Wallet W
left outer join Country C (nolock)
on C.Location = W.Location
inner join Seller S (nolock)
on S.branch=S.branch and S.customerbase=W.customerbase and S.detail=''
where not (W.Location = 'USA' or (len(W.Location)=3 and upper(substring(W.Location,3,1))='A'))
我可以知道将case when
条件放在外面(替换为if else)会
1.提高查询性能
和
2.还有其他优化此代码的方法吗?
* dbo.Getdecimal是一个存储过程
答案 0 :(得分:1)
您的伪代码不是很清楚,但如果您的代码真的那么做......
您" select case (...) FROM TABLE A/B
"没有WHERE
子句可能是它很慢的原因,因为你选择并插入表A或B中最初的行到表A中。
似乎链接INSERT INTO ... VALUES ...
在这里比SELECT INTO ... SELECT ...
更有意义。
然后,将外壳放在外面可能会快一点,因为你可以避免两次测试flag1 = 'N' or 'Y'
,但这更像是微优化。我不确定它会如何影响性能,但如果真的很重要,我会用SQL执行计划测试这两个解决方案。