I have the following function that returns parcel's delay:
ALTER FUNCTION [dbo].[Delay]
(#DeliveryTime int, #DeliveryHour int = 0, #Product_ID int, #Country varchar(2), #ZipCode varchar(10)
)
RETURNS int
AS
BEGIN
DECLARE #Delay int, #Guaranteed Int, #MaxDeliveryTime int, #MaxHour int, #test int
if #Country = 'FR'
begin
select top 1 #Guaranteed = pz.TProduct_Guaranteed,
#MaxDeliveryTime = pz.TProduct_delay,
#MaxHour = pz.TProduct_HourMax
from TProductZone PZ
where (pz.Country_ID = '0' OR pz.Country_ID = cast(#Country as varchar(2)))
And (Zone_ID = '0' or Zone_ID = left(#ZipCode,2))
And p.tproduct_id = #Product_ID
Order by pz.country_id desc, zone_id desc
end
Else
Begin
select top 1 #Guaranteed = pz.TProduct_Guaranteed,
#MaxDeliveryTime = pz.TProduct_delay,
#MaxHour = pz.TProduct_HourMax
from TProductZone PZ
where (pz.Country_ID = '0' OR pz.Country_ID = cast(#Country as varchar(2)))
And (Zone_ID = '0')
And p.tproduct_id = #Product_ID
Order by pz.country_id desc, zone_id desc
End
if #Guaranteed = 1
Begin
if #DeliveryTime >= #MaxDeliveryTime
Begin
set #Delay = #DeliveryTime-#MaxDeliveryTime
if #DeliveryHour > #MaxHour
begin
set #Delay = #Delay+1
end
End
else
Begin
set #Delay = 0
end
End
Else
Begin
set #Delay = 0
End
return #Delay
END
This function is used as following:
Update TShipping
Set Delay = Delay(S.TShipping_Deliverytime, cast(left(isnull(TD.Tracking_Hour,0),2) as int), S.TProduct_ID, S.Country_Code, S.ZipCode)
From TShipping S
inner Join TrackingEndDelay TD On TD.TShipping_ID = S.TShipping_ID
WHERE IsNull(TShipping_Delivered,0) = 1
And DateDiff(day,TShipping_Date,getdate()) < 90
I want to transform this function (and the call of the function) in a unique simple query in order to decrease the response time.
This is the query I did:
Update TShipping
Set Delay =
case
WHEN TProduct_Guaranteed=0 or (TShipping_Deliverytime - TProduct_delay < 0) then 0
WHEN (TShipping_Deliverytime - TProduct_delay >= 0) and cast(left(isnull(TD.Tracking_Hour,0),2) as int) <= isnull(TProduct_HourMax,24) then TShipping_Deliverytime - TProduct_delay
when (TShipping_Deliverytime - TProduct_delay >= 0) and cast(left(isnull(TD.Tracking_Hour,0),2) as int) > isnull(TProduct_HourMax,24) then TShipping_Deliverytime - TProduct_delay +1
end
from tshipping TS
inner Join TrackingEndDelay TD On TD.TShipping_ID = TS.TShipping_ID
left join dbo.TShipping_DateInDelivery DID on ts.tshipping_id=DID.tshipping_id
outer apply (select top 1 pz.TProduct_Guaranteed, pz.TProduct_delay, pz.TProduct_HourMax
from TShipping S
inner join TProductZone PZ on S.tproduct_id = pz.tproduct_id
where (pz.Country_ID = '0' OR pz.Country_ID = S.Country_Code)
And (Zone_ID = '0' or (Zone_ID = left(S.TShipping_ZipCode,2) and S.Country_Code='FR'))
and TS.TShipping_ID=S.TShipping_ID
Order by pz.country_id desc, zone_id desc) r1
WHERE IsNull(TShipping_Delivered,0) = 1
And DateDiff(day,TShipping_Date,getdate()) < 90
The problem is that I increase the response time instead of decreasing it. Has someone another better way to do it faster??
Thank you for your help!!
Related
I am trying to see if my stored procedure can return -1 some values based on a if condition, snipped stored proc is as follows.
CREATE PROCEDURE [StateMachine].[UpdateSnapshots]
(#SystemName [nvarchar](128)= 'test_system',
#IntrestingEvents VARCHAR(128)='test_event',
#StateMachine_JSON [nvarchar] (max) = 'test_json',
#StateMachine_Object [nvarchar] (max)='test_object',
#CrossbarRouter VARCHAR(128) = 'text_xbar1') AS
BEGIN
DECLARE
#SystemNameValue [nvarchar](128),
#CrossbarValue [nvarchar](128),
#IsCrossbarNotNull int,
#IsCrossbarNull int,
#CrossbarLock int
select #SystemNameValue=count(systemname) from [StateMachine].[Snapshots] with (nolock) where SystemName=#SystemName
IF #SystemNameValue=0
BEGIN
INSERT INTO [StateMachine].[Snapshots] (SystemName, IntrestingEvents, StateMachine_JSON, StateMachine_Object, CrossbarRouter) VALUES (#SystemName, #IntrestingEvents, #StateMachine_JSON, #StateMachine_Object, #CrossbarRouter)
END
select #CrossbarValue = isnull(count(CrossbarRouter),0) from [StateMachine].[Snapshots] with (nolock) where (CrossbarRouter=#CrossbarRouter and SystemName = #SystemName)
select #IsCrossbarNotNull = isnull(count(CrossbarRouter),0) from [StateMachine].[Snapshots] with (nolock) where CrossbarRouter is not null and SystemName = #SystemName
select #IsCrossbarNull = isnull(count(CrossbarRouter),0) from [StateMachine].[Snapshots] with (nolock) where CrossbarRouter is null and SystemName = #SystemName
select #CrossbarLock = isnull(count(CrossbarRouter),0) from [StateMachine].[Snapshots] with (nolock) where (CrossbarRouter != #CrossbarRouter and SystemName = #SystemName)
IF #CrossbarLock = 1
RETURN -1
IF (#CrossbarValue = 0 and #IsCrossbarNotNull = 0) OR #IsCrossbarNull = 0
BEGIN
UPDATE [StateMachine].[Snapshots] SET IntrestingEvents=#IntrestingEvents, StateMachine_JSON=#StateMachine_JSON, StateMachine_Object=#StateMachine_Object, CrossbarRouter = #CrossbarRouter WHERE SystemName=#SystemName;
END
IF #CrossbarValue = 1
BEGIN
UPDATE [StateMachine].[Snapshots] SET IntrestingEvents=#IntrestingEvents, StateMachine_JSON=#StateMachine_JSON, StateMachine_Object=#StateMachine_Object WHERE SystemName=#SystemName and CrossbarRouter=#CrossbarRouter;
END
END
GO
GRANT EXECUTE ON [StateMachine].[UpdateSnapshots] TO sp_executor
If I am trying to do this I am getting following error,
A RETURN statement with a return value cannot be used in this context.
Thanks
CREATE procedure testXIRR
(
#AmountEstimate as float = 0,
#AmountGoal as float = 0,
#AmountPrecision as float = 1e-7 ,
#AmountPrevious as float = 0,
#EndDate as date = null,
#FlagError as bit = 0,
#FlagLoop as bit = 1,
#Rate as float = 0.1,
#RateDelta as float = 1e-2,
#RateInitial as float = 0,
#RateUpDown as smallint = 0,
#TableName as varchar(20) = NULL,
#query as varchar(20) = NULL
)
AS
BEGIN
Declare #powerVariable as float
Declare #MyTable Table(
PDate date,
PAmount float
)
insert into #MyTable values('01-Jan-13',-500),('01-Feb-13',20),('01-Mar-13',50),('01-Apr-13',80),('01-May-13',110),('01-Jun-13',140),('01-Jul-13',170)
set #Rate = #RateInitial
select #AmountGoal = -PAmount, #EndDate = PDate from #MyTable where PAmount < 0
while #FlagLoop = 1
begin
if abs(#AmountEstimate - #AmountGoal) < #AmountPrecision or ABS(#Rate) > 1
set #FlagLoop = 0
else
begin
if (#AmountPrevious is not null)
begin
if #AmountPrevious < #AmountGoal and #AmountEstimate < #AmountGoal
set #RateUpDown = 1
if #AmountPrevious > #AmountGoal and #AmountEstimate > #AmountGoal
set #RateUpdown = -1
if (#AmountPrevious < #AmountGoal and #AmountEstimate > #AmountGoal) or (#AmountPrevious > #AmountGoal and #AmountEstimate < #AmountGoal)
set #RateDelta = #RateDelta / 2e0
end
set #AmountPrevious = #AmountEstimate
set #Rate = (#Rate + (#RateDelta * #RateUpDown))
select #AmountEstimate = SUM(power(1e0 + #Rate, DATEDIFF(m,#EndDate , PDate)) * PAmount) from #MyTable where PAmount >= 0
end
end
print #Rate
if Abs(#Rate) > 1
begin
set #FlagError = 1
print -100000000
end
else
begin
print #Rate
end
END
GO
For the above values excel gives irr = 43.5976392, but this sp gives -2.9%.
At first it was giving an error:
invalid float operation
To fix that I have changed the formula from
SUM(power(1e0 + #Rate, DATEDIFF(d, PDate, #EndDate) / 365e0) * PAmount)
to
SUM(power(1e0 + #Rate, DATEDIFF(m,#EndDate , PDate)) * PAmount).
This resolved the issure which i think was square root of negative but still values are wrong.
In the below example, the columns 'SecondColumn' and 'ThirdColumn' will always update each time the block of code runs. 'FirstColumn' will update to the value stored in the variable #NumberOfRows (so long as it is >0).
The problem I have is that when #NumberOfRows is 0 or less, 'FirstColumn' will be set to NULL.
Is it possible to tweak this so that if #NumberOfRows is 0 or less, then the 'FirstColumn' does not update at all rather than setting the column to NULL?
DECLARE
#NumberOfRows INT = 0
,#NewValue DATETIME = GETDATE()
,#Other INT = 99
BEGIN
UPDATE x
SET x.FirstColumn = (CASE WHEN #NumberOfRows > 0 THEN #NewValue END)
,x.SecondColumn = SYSDATETIMEOFFSET()
,x.ThirdColumn = #Other
FROM TestTable x
WHERE x.ID = 100
END
The simplest thing to do is update the field with the current value.
DECLARE
#NumberOfRows INT = 0
,#NewValue DATETIME = GETDATE()
,#Other INT = 99
BEGIN
UPDATE x
SET x.FirstColumn = (CASE WHEN #NumberOfRows > 0 THEN #NewValue ELSE x.FirstColumn END)
,x.SecondColumn = SYSDATETIMEOFFSET()
,x.ThirdColumn = #Other
FROM TestTable x
WHERE x.ID = 100
END
Do not perform the update of the given column if #NumberOfRows <= 0:
DECLARE
#NumberOfRows INT = 0
,#NewValue DATETIME = GETDATE()
,#Other INT = 99
BEGIN
IF #NumberOfRows > 0
BEGIN
UPDATE x
SET x.FirstColumn = #NewValue
,x.SecondColumn = SYSDATETIMEOFFSET()
,x.ThirdColumn = #Other
FROM TestTable x
WHERE x.ID = 100
END
ELSE
BEGIN
UPDATE x
SET x.SecondColumn = SYSDATETIMEOFFSET()
,x.ThirdColumn = #Other
FROM TestTable x
WHERE x.ID = 100
END
END
I am having issues converting a portion of my script that works in Oracle over for use in SQL Server. The portion of my script uses arrays and I have not been able to find the equivalent in TSQL (I dont believe one exists?). My main issues occur when trying to match values v_measure_map(i).v_upload_code = b.UPLOAD_CODE. Any tips or suggestions?
SELECT SCOPE_KEY,
ENRICHED_DATE,
ENRICHED_TIME,
BENCHMARK_DATE,
PROSDEALID
INTO v_xs_scope
FROM xaction_scope
WHERE TXN_ID = V_TXN_ID ;
<<loop2>> FOR i IN 1..v_measure_map.count --count returns the number of rows in the table (sy_enrich_measure_map)
LOOP
<<loop3>> FOR j IN 1..v_xs_scope.count
LOOP
SELECT COUNT(*)
INTO #v_sql_count
FROM xaction_Level_info b
WHERE v_measure_map(i).v_upload_code = b.UPLOAD_CODE
AND v_xs_scope(j).v_scope_key = b.SCOPE
AND
Use table variables, for example:
DECLARE
#v_xs_scope TABLE (
RowNum INT IDENTITY,
SCOPE_KEY INT,
ENRICHED_DATE DATE,
ENRICHED_TIME TIME,
BENCHMARK_DATE DATE,
PROSDEALID INT
)
DECLARE
#v_measure_map TABLE (
RowNum INT IDENTITY,
v_upload_code INT
)
INSERT INTO #v_xs_scope (
SCOPE_KEY, ENRICHED_DATE, ENRICHED_TIME, BENCHMARK_DATE, PROSDEALID
)
SELECT
SCOPE_KEY, ENRICHED_DATE, ENRICHED_TIME, BENCHMARK_DATE, PROSDEALID
FROM xaction_scope
WHERE
TXN_ID = V_TXN_ID;
INSERT INTO #v_measure_map(v_upload_code)
SELECT v_upload_code
FROM v_measure_map
DECLARE
#l1_CurrentRowNum INT,
#l1_MaxRowNum INT,
#l2_CurrentRowNum INT,
#l2_MaxRowNum INT,
#v_upload_code INT,
#v_scope_key INT
SELECT
#l1_CurrentRowNum = 1,
#l1_MaxRowNum = MAX(RowNum)
FROM #v_measure_map
WHILE #l1_CurrentRowNum <= #l1_MaxRowNum
BEGIN
SELECT #v_upload_code = v_upload_code
FROM #v_measure_map
WHERE
RowNum = #l1_CurrentRowNum
SELECT
#l2_CurrentRowNum = 1,
#l2_MaxRowNum = MAX(RowNum)
FROM #v_xs_scope
WHILE #l2_CurrentRowNum <= #l2_MaxRowNum
BEGIN
SELECT #v_scope_key = scope_key
FROM #v_xs_scope
WHERE
RowNum = #l2_CurrentRowNum
SELECT #v_sql_count = COUNT(*)
FROM xaction_Level_info b
WHERE
b.UPLOAD_CODE = #v_upload_code
AND b.SCOPE = #v_scope_key
SET #l2_CurrentRowNum = #l2_CurrentRowNum + 1
END
SET #l1_CurrentRowNum = #l1_CurrentRowNum + 1
END
or cursors, for example:
DECLARE
#v_upload_code INT,
#v_scope_key INT
DECLARE curs_1 CURSOR FOR
SELECT
v_upload_code
FROM v_measure_map
OPEN curs_1;
FETCH curs_1 INTO #v_upload_code;
WHILE (##FETCH_STATUS<>-1)
BEGIN
DECLARE curs_2 CURSOR FOR
SELECT
SCOPE_KEY
FROM xaction_scope
WHERE
TXN_ID = V_TXN_ID
OPEN curs_2;
FETCH curs_2 INTO #v_scope_key;
WHILE (##FETCH_STATUS<>-1)
BEGIN
SELECT #v_sql_count = COUNT(*)
FROM xaction_Level_info b
WHERE
b.UPLOAD_CODE = #v_upload_code
AND b.SCOPE = #v_scope_key
FETCH curs_2 INTO #v_scope_key;
END
CLOSE curs_2;
DEALLOCATE curs_2;
FETCH curs_1 INTO #v_upload_code;
END
CLOSE curs_1;
DEALLOCATE curs_1;
The below script takes more than 10 hours to execute..
It contains three nested cursors and i think they are the main culprit.
I have searched a lot for replacing the cursors or improve the performance of the script.And found a lot of ways to remove the cursor. e.g. simple set join operations, Marge operation etc etc. But still I am unable to implement them in my script. Please take look on the script and give some opinion on
- with out affecting the output, is it possible to remove the inner cursors or not
- if possible then how ? please give some code if possible
DECLARE #Start_Date Date = '1990-01-01'
DECLARE #End_Date Date = '2012-12-12'
DECLARE #Company_ID int = 180
declare #BP_ID [int]
DECLARE All_Client_Bp_Id CURSOR STATIC FOR
SELECT TOP 50 Bp_id FROM Client --Take All Client's BPID
OPEN All_Client_Bp_Id
FETCH NEXT FROM All_Client_Bp_Id
INTO #BP_ID
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #acrdint MONEY
DECLARE #acrdSrv MONEY
DECLARE #MaxMargLimit MONEY
DECLARE #ForceLimit MONEY
DECLARE #WarningLimit MONEY
DECLARE #MarginLimit DECIMAL(5,2)
select #MaxMargLimit=Highest_Margin_Limit*100000,#ForceLimit=Force_Sell_Limit,#WarningLimit=Margin_Warning_Limit, #MarginLimit = Margin_Limit
from Client_Margin_Constraints c
inner join (select Bp_id, max(Update_Date) as updt
from Client_Margin_Constraints
where Update_Date <= #End_Date and Bp_id = #BP_ID and Company_ID = #Company_ID
group by Bp_id) b
on c.Bp_id = b.Bp_id and c.Update_Date = b.updt
DELETE FROM Temp_Portfolio
INSERT INTO Temp_Portfolio (Client_BP_ID, tran_date, Instrument_ID, Is_Buy, Quantity, Amount, Commission, Rate, Category,Tax_Amount)
SELECT t.Client_BP_ID, t.tran_date, t.Instrument_ID, t.Is_Buy, t.Quantity, t.Amount, t.Commission,
t.Rate, t.Category, t.Tax_Amount
FROM All_Share_Txn t
WHERE t.Client_BP_ID = #BP_ID
DECLARE #Instrument_Id int,
#bqty int,
#bamt MONEY,
#brate MONEY,
#srate MONEY,
#rprofit MONEY,
#mslbqty int,
#BCost MONEY,
#SCost MONEY,
#BCqty int,
#SCqty int,
#B_Or_S CHAR(1),
#CDBL_Type CHAR(1),
#Qty INT,
#MktPrice MONEY,
#Amount MONEY,
#Commission MONEY,
#TDATE SMALLDATETIME,
#DES CHAR(30),
#TotalProfit MONEY,
#Category CHAR(1)
SET #TotalProfit = 0
DECLARE CUR_SHARE CURSOR STATIC FOR
SELECT DISTINCT Instrument_Id
FROM Temp_Portfolio
OPEN CUR_SHARE
FETCH NEXT FROM CUR_SHARE
INTO #Instrument_Id
WHILE ##FETCH_STATUS = 0
BEGIN
SET #bqty = 0
SET #bamt = 0
SET #brate = 0
SET #srate = 0
SET #rprofit = 0
SET #mslbqty = 0
SET #BCost = 0
SET #SCost = 0
SET #BCqty = 0
SET #SCqty = 0
DECLARE CUR_COST CURSOR STATIC FOR
SELECT Is_buy,Quantity,rate,Amount,Commission,Tran_date
FROM Temp_Portfolio
WHERE Client_Bp_id=#BP_ID and Instrument_Id=#Instrument_Id
ORDER BY Tran_date,Is_buy desc,Category
OPEN CUR_COST
FETCH NEXT FROM CUR_COST
INTO #B_Or_S,#Qty,#MktPrice,#Amount,#Commission,#TDATE
WHILE ##FETCH_STATUS = 0
BEGIN
IF #B_Or_S='1'
BEGIN
SET #bqty = #bqty + #Qty
SET #bamt = #bamt + #Amount + #Commission
IF #bqty > 0
SET #brate = #bamt/#bqty
END
ELSE IF #B_Or_S='0'
BEGIN
SET #srate = #MktPrice
IF #TDATE > #Start_Date and #TDATE <= #End_Date
BEGIN
SET #rprofit = #rprofit + ((#srate - #brate) * #Qty) - #Commission
SET #BCqty = #BCqty + #Qty
SET #SCqty = #SCqty + #Qty
SET #BCost = #BCost + (#Brate * #Qty)
SET #SCost = #SCost + (#Srate * #Qty) - #Commission
END
SET #bamt = #bamt - (#brate * #Qty)
SET #bqty = #bqty - #Qty
END
FETCH NEXT FROM CUR_COST
INTO #B_Or_S,#Qty,#MktPrice,#Amount,#Commission,#TDATE
END
SET #TotalProfit=#TotalProfit+#rprofit
CLOSE CUR_COST
DEALLOCATE CUR_COST
FETCH NEXT FROM CUR_SHARE
INTO #Instrument_Id
END
CLOSE CUR_SHARE
DEALLOCATE CUR_SHARE
--Select #TotalProfit as Realised_Gain
-- Equity, Purchase Power Calculation
DECLARE #Equity_All MONEY
DECLARE #Equity_Margin MONEY
DECLARE #Current_Balance MONEY
DECLARE #temp_Purchase_Power_1 MONEY
DECLARE #temp_Purchase_Power_2 MONEY
DECLARE #Purchase_Power MONEY
--Balance
select #Current_Balance = sum((case when a.Is_Share_TXN='1' and a.Is_Debit='1' then -a.amount when a.Is_Share_TXN='1' and a.Is_Debit='0' then a.amount when a.Is_Share_TXN='0' and a.Is_Debit='0' then a.amount when a.Is_Share_TXN='0' and a.Is_Debit='1' then -a.amount end) -a.Commission)
from Client_Transaction a where a.Client_Bp_id = #BP_ID and a.Transaction_Date < #End_Date and a.Company_Id=#Company_Id
group by a.Client_Bp_id--dbo.get_Current_Balance(#BP_ID, #End_Date, #Company_ID)
--Equity Margin
SELECT #Equity_Margin = SUM(CASE WHEN t_Margin.Is_Marginable_Securities = 'True' Then t_Margin.Total_Quantity * t_Margin.Market_price END),
#Equity_All = SUM(t_Margin.Total_Quantity * t_Margin.Market_price)
FROM
(
select t2.Is_Marginable_Securities, --t3.Bp_Code as Client_Code,t3.Bp_Name as Client_Name,t4.Bo_Id_DSE,t1.Instrument_ID,
sum(case when Is_buy='True' then Quantity when Is_buy='False' then -quantity end) as Total_Quantity,
--sum(case when ISNULL(t1.Mature_Date_Share,t1.tran_date) <= #Transaction_Date then (case Is_buy when '1' then quantity when '0' then -quantity end) else 0 end) as Free_Quantity,
INDX.Closing_Price AS Market_price
from dbo.View_All_Share_Transactions_with_PledgeUnpledge t1 left outer join Instrument t2 on t1.Instrument_Id=t2.Instrument_ID
left outer join (
select Closing_Price from Index_Price ip
where ip.Txn_Date=(select MAX(Txn_Date) from Index_Price ip2 where ip2.Instrument_Id=ip.Instrument_Id)
) INDX
ON t1.Instrument_ID = INDX.Closing_Price
where Client_Bp_id = #BP_ID and t1.Instrument_ID is not null and tran_date <=#End_Date and t1.Is_Pledge_Unpledge = 'False'
group by t1.Instrument_ID,t2.Is_Marginable_Securities, INDX.Closing_Price
having sum(case when Is_buy='True' then Quantity when Is_buy='False' then -quantity end)<> 0
) t_Margin --dbo.get_Equity_Margin(#BP_ID, #End_Date, #Company_ID)
SET #Equity_Margin = #Equity_Margin + #Current_Balance
SET #Equity_All = #Equity_All + #Current_Balance
SET #temp_Purchase_Power_1 = (#Equity_Margin * (#MarginLimit / 100)) + #Current_Balance
SET #temp_Purchase_Power_2 = ISNULL(#MaxMargLimit,0) + ISNULL(#Current_Balance,0)
IF (#temp_Purchase_Power_1 < #temp_Purchase_Power_2)
BEGIN
SET #Purchase_Power = #temp_Purchase_Power_1
END
ELSE
BEGIN
SET #Purchase_Power = #temp_Purchase_Power_2
END
INSERT Client_Account_Balance (
BP_ID,
Equity_All,
Equity_Margin,
Purchase_Power,
Margin_Ratio,
Total_Deposit,
Withdraw,
Charges,
Current_Balance,
Aaccured_Charges,
Max_Margin_LImit,
Margin_Limit,
Realised_Gain,
Company_ID,
Created_By,
Updated_By
)
SELECT #BP_ID, #Equity_All,#Equity_Margin ,#Purchase_Power ,
CASE WHEN (#Current_Balance - ISNULL(#acrdSrv,0)) != 0 THEN (#Equity_Margin - #Current_Balance) * (-100)/(#Current_Balance - ISNULL(#acrdSrv,0)) ELSE 0 END,
TDEP,TWDRAW,TCHARGES,BALANCE,ACC_CHARGE,#MaxMargLimit ,#MarginLimit,
#TotalProfit,
180,1,1
FROM
(SELECT SUM(DEPOSITE) AS TDEP,SUM(WDRAW) AS TWDRAW,SUM(CHARGES) AS TCHARGES,SUM(DEBCRED-Commission) AS BALANCE,SUM(ISNULL(#acrdint,0)+ISNULL(#acrdSrv,0)) AS ACC_CHARGE
FROM
(SELECT (CASE
WHEN tran_date >= #Start_Date THEN
CASE Is_Share_TXN
WHEN '0' THEN
CASE Is_Debit
WHEN '1' THEN 0
ELSE AMOUNT END
ELSE 0 END
ELSE 0 END) AS Deposite,
(CASE
WHEN tran_date >= #Start_Date THEN
CASE Is_Share_TXN
WHEN '0' THEN
CASE Is_Debit
WHEN '1' THEN
CASE T_TYPE
WHEN '1' THEN AMOUNT
WHEN '3' THEN AMOUNT
WHEN 'T' THEN AMOUNT
ELSE 0 END
ELSE 0 END
ELSE 0 END
ELSE 0 END) AS WDRAW,
(CASE
WHEN tran_date >= #Start_Date THEN
CASE Is_Share_TXN
WHEN '0' THEN
CASE Is_Debit
WHEN '1' THEN
CASE T_TYPE
WHEN '1' THEN 0
WHEN '3' THEN 0
WHEN 'T' THEN 0
ELSE AMOUNT END
ELSE 0 END
ELSE 0 END
ELSE 0 END) AS CHARGES,
(CASE Is_Share_TXN
WHEN '1' THEN
CASE Is_Debit
WHEN '1' THEN -AMOUNT
ELSE AMOUNT END
When '0' THEN
CASE Is_Debit
WHEN '1' THEN -AMOUNT
ELSE AMOUNT END
END) AS DEBCRED,Commission
FROM View_All_Transaction
WHERE tran_date <= #End_Date
AND Client_Bp_id = #BP_ID ) AS A) AS B
FETCH NEXT FROM All_Client_Bp_Id
INTO #BP_ID
END
CLOSE All_Client_Bp_Id
DEALLOCATE All_Client_Bp_Id
Hey i had a look with your script and found ..you can improve your scripts performance by excluding DISTINCT clause and create non-cluster index against column which following ORDER BY CLAUSE as well.
These 2 point will definitly help you to improve the performance.
Please let me know if you have any query.