Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Simplifying complicated query

Author  Topic 

SergioM
Posting Yak Master

170 Posts

Posted - 2014-02-04 : 14:18:07
I need to simplify a query because the parts are often reusable & I'd rather change it in one place than go into each part & update it. I know that I can't store a query as a variable unless the query only results in 1 row of data.
Enclosed is a small excerpt of my query which is pretty easy to understand.

For several operations it has to ask itself if data appears in one column and if not, if it should pull the data from the second column. Since these conditional searches are confusing and appear regularly I was wondering if I could store them differently in one centralized place.


	,CASE 
WHEN oi.[AverageCost]='0' THEN CONVERT(DECIMAL(18,2), o.[GrandTotal] - ((oi.[SiteCost] * oi.Qty)
+ (CASE WHEN ISNULL(bO.Commission,0) > ISNULL(o.FinalValueTotal,0) THEN ISNULL(bO.Commission,0) ELSE ISNULL(o.FinalValueTotal,0) END + ISNULL(oi.PostingFee,0) + ISNULL(o.paychannelFeeTotal,0)+ ISNULL(p.[channelTransactionFee],0))
+ ISNULL(o.[FinalShippingFee],0)))
- ISNULL(o.TaxTotal,0)
+ (CASE WHEN O.TimeOfOrder BETWEEN eS.startDate AND eS.endDate THEN ISNULL(eS.subsidyAmount,0) * oi.Qty ELSE '0' END)
ELSE CONVERT(DECIMAL(18,2), o.[GrandTotal] - ((oi.[AverageCost] * oi.Qty)
+ (CASE WHEN ISNULL(bO.Commission,0) > ISNULL(o.FinalValueTotal,0) THEN ISNULL(bO.Commission,0) ELSE ISNULL(o.FinalValueTotal,0) END + ISNULL(oi.PostingFee,0) + ISNULL(o.paychannelFeeTotal,0)+ ISNULL(p.[channelTransactionFee],0))
+ ISNULL(o.[FinalShippingFee],0)))
- ISNULL(o.TaxTotal,0)
+ (CASE WHEN O.TimeOfOrder BETWEEN eS.startDate AND eS.endDate THEN ISNULL(eS.subsidyAmount,0) * oi.Qty ELSE '0' END)
END


-Sergio
I use Microsoft SQL 2008

bitsmed
Aged Yak Warrior

545 Posts

Posted - 2014-02-05 : 12:53:33
You could create a view or function
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-02-10 : 09:01:11
Can you post some sample data and explain what you want?

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -