以下SQL代码位于where子句中。有没有其他方法可以写我们来缩短这个。下面的代码重复了很多次。我想缩短这段代码
((Business_Unit = 'A'
and ((
convert(money, case when substring(ltrim(rtrim(premium_change)),len(ltrim(rtrim(premium_change))),1 ) = '-'
then substring(ltrim(rtrim(premium_change)),1,len(ltrim(rtrim(premium_change))) -1) else
substring(ltrim(rtrim(premium_change)),1,len(ltrim(rtrim(premium_change)))) end)
) >= 100))
OR
(Business_Unit = 'B'
AND ((
convert(money, case when substring(ltrim(rtrim(premium_change)),len(ltrim(rtrim(premium_change))),1 ) = '-'
then substring(ltrim(rtrim(premium_change)),1,len(ltrim(rtrim(premium_change))) -1) else
substring(ltrim(rtrim(premium_change)),1,len(ltrim(rtrim(premium_change)))) end)
) >=100.00)
AND (text7 != 'N')
OR
Business_Unit = 'B'
AND ((
convert(money, case when substring(ltrim(rtrim(premium_change)),len(ltrim(rtrim(premium_change))),1 ) = '-'
then substring(ltrim(rtrim(premium_change)),1,len(ltrim(rtrim(premium_change))) -1) else
substring(ltrim(rtrim(premium_change)),1,len(ltrim(rtrim(premium_change)))) end)
) >=100.00)
AND (text7 = 'N')
and (text4 != '')
OR Business_Unit = 'B'
AND ((
convert(money, case when substring(ltrim(rtrim(premium_change)),len(ltrim(rtrim(premium_change))),1 ) = '-'
then substring(ltrim(rtrim(premium_change)),1,len(ltrim(rtrim(premium_change))) -1) else
substring(ltrim(rtrim(premium_change)),1,len(ltrim(rtrim(premium_change)))) end)
) > 300.00)
AND (text7 = 'N')
and (text4 = ''))
OR
(Business_Unit = 'C'
and ((
convert(money, case when substring(ltrim(rtrim(premium_change)),len(ltrim(rtrim(premium_change))),1 ) = '-'
then substring(ltrim(rtrim(premium_change)),1,len(ltrim(rtrim(premium_change))) -1) else
substring(ltrim(rtrim(premium_change)),1,len(ltrim(rtrim(premium_change)))) end)
) >= 150)`enter code here`
and text1 != 'N')
答案 0 :(得分:2)
我会在这里使用CTE
。我们的想法是为where子句准备数据:
;with cte as
(--your current query here without where clasuse
--just add the following to the select list
convert(money, case when substring(ltrim(rtrim(premium_change)),
len(ltrim(rtrim(premium_change))),
1) = '-'
then substring(ltrim(rtrim(premium_change)), 1,
len(ltrim(rtrim(premium_change)))
- 1)
else substring(ltrim(rtrim(premium_change)), 1,
len(ltrim(rtrim(premium_change))))
end) as pc
)
select * from cte
where
(Business_Unit = 'A' and pc >= 100) or
(Business_Unit = 'B' and pc >= 100 and text7 != 'N') or
...
我无法解析你奇怪的AND OR
组合(这看起来似乎不正确)。
如果无法使用CTE
,您可以缩短以下内容:
substring(ltrim(rtrim(premium_change)),len(ltrim(rtrim(premium_change))),1 )
变为:
right(ltrim(rtrim(premium_change)), 1 )
和
substring(ltrim(rtrim(premium_change)),1,len(ltrim(rtrim(premium_change))) -1)
变为:
left(ltrim(rtrim(premium_change)), len(ltrim(rtrim(premium_change))) -1)
和
substring(ltrim(rtrim(premium_change)),1,len(ltrim(rtrim(premium_change))))
变为:
ltrim(rtrim(premium_change))