
/****** Object:  StoredProcedure [dbo].[UpdateScriptMaster]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateScriptMaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[UpdateScriptMaster]
GO
/****** Object:  StoredProcedure [dbo].[UpdateData_withTaxAmount_INNetAmount]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateData_withTaxAmount_INNetAmount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[UpdateData_withTaxAmount_INNetAmount]
GO
/****** Object:  StoredProcedure [dbo].[tmpupdateholdings]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tmpupdateholdings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[tmpupdateholdings]
GO
/****** Object:  StoredProcedure [dbo].[t_transferstock]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[t_transferstock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[t_transferstock]
GO
/****** Object:  StoredProcedure [dbo].[StockInTradePurchaseAndSaleAccount_Amount]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[StockInTradePurchaseAndSaleAccount_Amount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[StockInTradePurchaseAndSaleAccount_Amount]
GO
/****** Object:  StoredProcedure [dbo].[SplitAutoUploadEntry ]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SplitAutoUploadEntry ]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SplitAutoUploadEntry ]
GO
/****** Object:  StoredProcedure [dbo].[spAddProject]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAddProject]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spAddProject]
GO
/****** Object:  StoredProcedure [dbo].[Sp_TradeFileData1]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Sp_TradeFileData1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Sp_TradeFileData1]
GO
/****** Object:  StoredProcedure [dbo].[Sp_TradeFileData]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Sp_TradeFileData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Sp_TradeFileData]
GO
/****** Object:  StoredProcedure [dbo].[sp_Insert_AccountData]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_Insert_AccountData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_Insert_AccountData]
GO
/****** Object:  StoredProcedure [dbo].[Securities_Transcation_Tax_Scriptwsie_Calculation]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Securities_Transcation_Tax_Scriptwsie_Calculation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Securities_Transcation_Tax_Scriptwsie_Calculation]
GO
/****** Object:  StoredProcedure [dbo].[ScriptLedger]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ScriptLedger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ScriptLedger]
GO
/****** Object:  StoredProcedure [dbo].[SaveRights]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SaveRights]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SaveRights]
GO
/****** Object:  StoredProcedure [dbo].[SaveBrokerage_Rate]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SaveBrokerage_Rate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SaveBrokerage_Rate]
GO
/****** Object:  StoredProcedure [dbo].[rpt_TrailBalance_Yearwise]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_TrailBalance_Yearwise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[rpt_TrailBalance_Yearwise]
GO
/****** Object:  StoredProcedure [dbo].[rpt_Final_Statement_Report]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_Final_Statement_Report]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[rpt_Final_Statement_Report]
GO
/****** Object:  StoredProcedure [dbo].[rpt_Family_Memberwise_Account_Ledger_Report]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_Family_Memberwise_Account_Ledger_Report]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[rpt_Family_Memberwise_Account_Ledger_Report]
GO
/****** Object:  StoredProcedure [dbo].[rpt_Consaltant_Transfer]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_Consaltant_Transfer]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[rpt_Consaltant_Transfer]
GO
/****** Object:  StoredProcedure [dbo].[rpt_BrokerBill_Register_Scriptwise]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_BrokerBill_Register_Scriptwise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[rpt_BrokerBill_Register_Scriptwise]
GO
/****** Object:  StoredProcedure [dbo].[rpt_BrokerBill_Register]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_BrokerBill_Register]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[rpt_BrokerBill_Register]
GO
/****** Object:  StoredProcedure [dbo].[rpt_Account_Master]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_Account_Master]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[rpt_Account_Master]
GO
/****** Object:  StoredProcedure [dbo].[rpt_Account_Ledger_Report]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_Account_Ledger_Report]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[rpt_Account_Ledger_Report]
GO
/****** Object:  StoredProcedure [dbo].[ReTransfer_Account_Master]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ReTransfer_Account_Master]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ReTransfer_Account_Master]
GO
/****** Object:  StoredProcedure [dbo].[Report_Bank_Reconsilation]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Report_Bank_Reconsilation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Report_Bank_Reconsilation]
GO
/****** Object:  StoredProcedure [dbo].[R_JournalVoucher]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[R_JournalVoucher]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[R_JournalVoucher]
GO
/****** Object:  StoredProcedure [dbo].[r_bankreco]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[r_bankreco]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[r_bankreco]
GO
/****** Object:  StoredProcedure [dbo].[Purchar_Sale_MonthWise_Report]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Purchar_Sale_MonthWise_Report]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Purchar_Sale_MonthWise_Report]
GO
/****** Object:  StoredProcedure [dbo].[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency_Summary]
GO
/****** Object:  StoredProcedure [dbo].[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency]
GO
/****** Object:  StoredProcedure [dbo].[proc_WithTaxStockholding_Equity_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_WithTaxStockholding_Equity_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_WithTaxStockholding_Equity_Summary]
GO
/****** Object:  StoredProcedure [dbo].[proc_WithTaxStockholding_Equity]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_WithTaxStockholding_Equity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_WithTaxStockholding_Equity]
GO
/****** Object:  StoredProcedure [dbo].[proc_validation]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_validation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_validation]
GO
/****** Object:  StoredProcedure [dbo].[proc_TransferStocksToNewYear_Imp]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TransferStocksToNewYear_Imp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_TransferStocksToNewYear_Imp]
GO
/****** Object:  StoredProcedure [dbo].[proc_TransferStocksToNewYear]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TransferStocksToNewYear]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_TransferStocksToNewYear]
GO
/****** Object:  StoredProcedure [dbo].[proc_TransferStockEntriesNew]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TransferStockEntriesNew]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_TransferStockEntriesNew]
GO
/****** Object:  StoredProcedure [dbo].[proc_TransferStockEntries]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TransferStockEntries]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_TransferStockEntries]
GO
/****** Object:  StoredProcedure [dbo].[proc_TransferStock_BrokerBill_Entries]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TransferStock_BrokerBill_Entries]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_TransferStock_BrokerBill_Entries]
GO
/****** Object:  StoredProcedure [dbo].[proc_transferEntries]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_transferEntries]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_transferEntries]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TransferClosingBalanceTo_Mst_Account]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TransferClosingBalanceTo_Mst_Account]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TransferClosingBalanceTo_Mst_Account]
GO
/****** Object:  StoredProcedure [dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency_Summary]
GO
/****** Object:  StoredProcedure [dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency]
GO
/****** Object:  StoredProcedure [dbo].[proc_Stockposition_Equity_ROI_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockposition_Equity_ROI_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Stockposition_Equity_ROI_Summary]
GO
/****** Object:  StoredProcedure [dbo].[proc_Stockposition_Equity_ROI]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockposition_Equity_ROI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Stockposition_Equity_ROI]
GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Summary]
GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Monthwise]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Monthwise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Monthwise]
GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency]
GO
/****** Object:  StoredProcedure [dbo].[proc_Stockholdingposition_FamilyWise_Equity_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockholdingposition_FamilyWise_Equity_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Stockholdingposition_FamilyWise_Equity_Summary]
GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_FamilyWise_Equity_Monthwise]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_FamilyWise_Equity_Monthwise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_Equity_Monthwise]
GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_FamilyWise_Equity]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_FamilyWise_Equity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_Equity]
GO
/****** Object:  StoredProcedure [dbo].[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary]
GO
/****** Object:  StoredProcedure [dbo].[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency]
GO
/****** Object:  StoredProcedure [dbo].[proc_Stockholdingposition_Equity_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockholdingposition_Equity_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Stockholdingposition_Equity_Summary]
GO
/****** Object:  StoredProcedure [dbo].[proc_Stockholdingposition_Equity_LTCG]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockholdingposition_Equity_LTCG]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Stockholdingposition_Equity_LTCG]
GO
/****** Object:  StoredProcedure [dbo].[proc_Stockholdingposition_Equity]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockholdingposition_Equity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Stockholdingposition_Equity]
GO
/****** Object:  StoredProcedure [dbo].[proc_Stockholdingposition_CapitalStock_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockholdingposition_CapitalStock_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Stockholdingposition_CapitalStock_Summary]
GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency_Summary]
GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency]
GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_BrokerWise_Equity_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_BrokerWise_Equity_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_StockholdingPosition_BrokerWise_Equity_Summary]
GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_BrokerWise_Equity]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_BrokerWise_Equity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_StockholdingPosition_BrokerWise_Equity]
GO
/****** Object:  StoredProcedure [dbo].[proc_StockFilter_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockFilter_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_StockFilter_F_And_O_AND_MCX_And_Currency]
GO
/****** Object:  StoredProcedure [dbo].[proc_StockFilter_Equity]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockFilter_Equity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_StockFilter_Equity]
GO
/****** Object:  StoredProcedure [dbo].[proc_Script_Ledger]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Script_Ledger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Script_Ledger]
GO
/****** Object:  StoredProcedure [dbo].[proc_Reports_All]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Reports_All]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Reports_All]
GO
/****** Object:  StoredProcedure [dbo].[proc_Report_All]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Report_All]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Report_All]
GO
/****** Object:  StoredProcedure [dbo].[proc_Physical_Demate]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Physical_Demate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Physical_Demate]
GO
/****** Object:  StoredProcedure [dbo].[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary]
GO
/****** Object:  StoredProcedure [dbo].[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency]
GO
/****** Object:  StoredProcedure [dbo].[proc_MonthWise_Stockholdingposition_Equity_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_MonthWise_Stockholdingposition_Equity_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_MonthWise_Stockholdingposition_Equity_Summary]
GO
/****** Object:  StoredProcedure [dbo].[proc_MonthWise_Stockholdingposition_Equity]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_MonthWise_Stockholdingposition_Equity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_MonthWise_Stockholdingposition_Equity]
GO
/****** Object:  StoredProcedure [dbo].[proc_Monthwise_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Monthwise_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Monthwise_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency]
GO
/****** Object:  StoredProcedure [dbo].[proc_MonthWise_StockholdingPosition_BrokerWise_Equity]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_MonthWise_StockholdingPosition_BrokerWise_Equity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_MonthWise_StockholdingPosition_BrokerWise_Equity]
GO
/****** Object:  StoredProcedure [dbo].[proc_InsertMyDataTable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_InsertMyDataTable]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_InsertMyDataTable]
GO
/****** Object:  StoredProcedure [dbo].[proc_InsertInternalInvestment]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_InsertInternalInvestment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_InsertInternalInvestment]
GO
/****** Object:  StoredProcedure [dbo].[Proc_InsertInternalExternalEntries]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_InsertInternalExternalEntries]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_InsertInternalExternalEntries]
GO
/****** Object:  StoredProcedure [dbo].[proc_InsertInternalDemat]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_InsertInternalDemat]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_InsertInternalDemat]
GO
/****** Object:  StoredProcedure [dbo].[proc_InsertInternalConsultant]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_InsertInternalConsultant]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_InsertInternalConsultant]
GO
/****** Object:  StoredProcedure [dbo].[proc_InsertInternal_External_Ac_Settings]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_InsertInternal_External_Ac_Settings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_InsertInternal_External_Ac_Settings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_InsertFinancialYearEntries]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_InsertFinancialYearEntries]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_InsertFinancialYearEntries]
GO
/****** Object:  StoredProcedure [dbo].[proc_InsertExpenseMapping]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_InsertExpenseMapping]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_InsertExpenseMapping]
GO
/****** Object:  StoredProcedure [dbo].[proc_InsertBrokerageMaster]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_InsertBrokerageMaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_InsertBrokerageMaster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_GetShortCutKeysData]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_GetShortCutKeysData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_GetShortCutKeysData]
GO
/****** Object:  StoredProcedure [dbo].[proc_getInvestmentType]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_getInvestmentType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_getInvestmentType]
GO
/****** Object:  StoredProcedure [dbo].[proc_getInternalData]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_getInternalData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_getInternalData]
GO
/****** Object:  StoredProcedure [dbo].[proc_Get_AllCodes]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Get_AllCodes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Get_AllCodes]
GO
/****** Object:  StoredProcedure [dbo].[proc_FamilyWiseAccountLedger]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_FamilyWiseAccountLedger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_FamilyWiseAccountLedger]
GO
/****** Object:  StoredProcedure [dbo].[Proc_ClosingBalanceTransferTo_Mst_Account]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_ClosingBalanceTransferTo_Mst_Account]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_ClosingBalanceTransferTo_Mst_Account]
GO
/****** Object:  StoredProcedure [dbo].[proc_Brokeragestatement_OtherCharges]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Brokeragestatement_OtherCharges]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Brokeragestatement_OtherCharges]
GO
/****** Object:  StoredProcedure [dbo].[proc_Advisory_Equity_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Advisory_Equity_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Advisory_Equity_Summary]
GO
/****** Object:  StoredProcedure [dbo].[proc_Advisory_BrokerWise_Equity_Summary]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Advisory_BrokerWise_Equity_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_Advisory_BrokerWise_Equity_Summary]
GO
/****** Object:  StoredProcedure [dbo].[Postal_Otherinvestment_Report]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Postal_Otherinvestment_Report]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Postal_Otherinvestment_Report]
GO
/****** Object:  StoredProcedure [dbo].[Multipal_BrokerBill_Entry_Delete]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Multipal_BrokerBill_Entry_Delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Multipal_BrokerBill_Entry_Delete]
GO
/****** Object:  StoredProcedure [dbo].[Merger_Openning_Report]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Merger_Openning_Report]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Merger_Openning_Report]
GO
/****** Object:  StoredProcedure [dbo].[Match_Bank_Statement]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Match_Bank_Statement]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Match_Bank_Statement]
GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Scriptmaster]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Scriptmaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MasterReport_Scriptmaster]
GO
/****** Object:  StoredProcedure [dbo].[MasterReport_narrationmaster]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_narrationmaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MasterReport_narrationmaster]
GO
/****** Object:  StoredProcedure [dbo].[MasterReport_MFFamilymaster]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_MFFamilymaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MasterReport_MFFamilymaster]
GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Membermaster]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Membermaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MasterReport_Membermaster]
GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Mastersnew]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Mastersnew]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MasterReport_Mastersnew]
GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Investmentnmaster]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Investmentnmaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MasterReport_Investmentnmaster]
GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Industrymaster]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Industrymaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MasterReport_Industrymaster]
GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Groupmaster_Insert]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Groupmaster_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MasterReport_Groupmaster_Insert]
GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Groupmaster]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Groupmaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MasterReport_Groupmaster]
GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Familymaster]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Familymaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MasterReport_Familymaster]
GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Dematmaster]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Dematmaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MasterReport_Dematmaster]
GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Consultantmaster]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Consultantmaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MasterReport_Consultantmaster]
GO
/****** Object:  StoredProcedure [dbo].[MasterReport]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MasterReport]
GO
/****** Object:  StoredProcedure [dbo].[IPO_Report]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[IPO_Report]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[IPO_Report]
GO
/****** Object:  StoredProcedure [dbo].[Insert_UnMatchAccount_Master]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Insert_UnMatchAccount_Master]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Insert_UnMatchAccount_Master]
GO
/****** Object:  StoredProcedure [dbo].[Groupmaster_Insert]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Groupmaster_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Groupmaster_Insert]
GO
/****** Object:  StoredProcedure [dbo].[GetUserMenu]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetUserMenu]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetUserMenu]
GO
/****** Object:  StoredProcedure [dbo].[GetTransactionNo]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetTransactionNo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetTransactionNo]
GO
/****** Object:  StoredProcedure [dbo].[GetScriptCode]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetScriptCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetScriptCode]
GO
/****** Object:  StoredProcedure [dbo].[GetIndustryCode]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetIndustryCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetIndustryCode]
GO
/****** Object:  StoredProcedure [dbo].[GetExpense_Rate]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetExpense_Rate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetExpense_Rate]
GO
/****** Object:  StoredProcedure [dbo].[GetBrokerage_Rate]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetBrokerage_Rate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetBrokerage_Rate]
GO
/****** Object:  StoredProcedure [dbo].[GetAutoIntraDayMarkingDetail]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetAutoIntraDayMarkingDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetAutoIntraDayMarkingDetail]
GO
/****** Object:  StoredProcedure [dbo].[GetAccountCode]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetAccountCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetAccountCode]
GO
/****** Object:  StoredProcedure [dbo].[FD_Interest_Calculation]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FD_Interest_Calculation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[FD_Interest_Calculation]
GO
/****** Object:  StoredProcedure [dbo].[eventpopup]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[eventpopup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[eventpopup]
GO
/****** Object:  StoredProcedure [dbo].[Dividend_Report]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Dividend_Report]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Dividend_Report]
GO
/****** Object:  StoredProcedure [dbo].[CreateUser]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CreateUser]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CreateUser]
GO
/****** Object:  StoredProcedure [dbo].[CheckIfAccounExists]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CheckIfAccounExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CheckIfAccounExists]
GO
/****** Object:  StoredProcedure [dbo].[CalculateStockInTrade]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CalculateStockInTrade]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CalculateStockInTrade]
GO
/****** Object:  StoredProcedure [dbo].[BrokerScriptUpdate_information]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BrokerScriptUpdate_information]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[BrokerScriptUpdate_information]
GO
/****** Object:  StoredProcedure [dbo].[Broker_Format_Configuration]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Broker_Format_Configuration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Broker_Format_Configuration]
GO
/****** Object:  StoredProcedure [dbo].[Auto_Pnl_Entry]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Auto_Pnl_Entry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Auto_Pnl_Entry]
GO
/****** Object:  StoredProcedure [dbo].[Annexure_2]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Annexure_2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Annexure_2]
GO
/****** Object:  StoredProcedure [dbo].[Account_Master_Report_groupwise]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Account_Master_Report_groupwise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Account_Master_Report_groupwise]
GO
/****** Object:  UserDefinedFunction [dbo].[Scriptcodestable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Scriptcodestable]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Scriptcodestable]
GO
/****** Object:  UserDefinedFunction [dbo].[membercodestable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[membercodestable]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[membercodestable]
GO
/****** Object:  UserDefinedFunction [dbo].[GroupDetailscodestable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GroupDetailscodestable]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[GroupDetailscodestable]
GO
/****** Object:  UserDefinedFunction [dbo].[fnGetGainnLoss]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fnGetGainnLoss]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fnGetGainnLoss]
GO
/****** Object:  UserDefinedFunction [dbo].[fn_Split]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_Split]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fn_Split]
GO
/****** Object:  UserDefinedFunction [dbo].[consultantcodestable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[consultantcodestable]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[consultantcodestable]
GO
/****** Object:  UserDefinedFunction [dbo].[AccountGroupcodestable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AccountGroupcodestable]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[AccountGroupcodestable]
GO
/****** Object:  UserDefinedTableType [dbo].[MyDataTable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'MyDataTable' AND ss.name = N'dbo')
DROP TYPE [dbo].[MyDataTable]
GO
/****** Object:  UserDefinedTableType [dbo].[InvestMentDataTable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'InvestMentDataTable' AND ss.name = N'dbo')
DROP TYPE [dbo].[InvestMentDataTable]
GO
/****** Object:  UserDefinedTableType [dbo].[DematDataTable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'DematDataTable' AND ss.name = N'dbo')
DROP TYPE [dbo].[DematDataTable]
GO
/****** Object:  UserDefinedTableType [dbo].[BrokerMonthWiseEquityOpenings]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'BrokerMonthWiseEquityOpenings' AND ss.name = N'dbo')
DROP TYPE [dbo].[BrokerMonthWiseEquityOpenings]
GO
/****** Object:  UserDefinedTableType [dbo].[BrokerBill_Format_Expense]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'BrokerBill_Format_Expense' AND ss.name = N'dbo')
DROP TYPE [dbo].[BrokerBill_Format_Expense]
GO
/****** Object:  UserDefinedTableType [dbo].[BrokerageDataTable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'BrokerageDataTable' AND ss.name = N'dbo')
DROP TYPE [dbo].[BrokerageDataTable]
GO
/****** Object:  UserDefinedTableType [dbo].[ACSettingsDataTable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'ACSettingsDataTable' AND ss.name = N'dbo')
DROP TYPE [dbo].[ACSettingsDataTable]
GO
/****** Object:  UserDefinedTableType [dbo].[AccountDataTable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'AccountDataTable' AND ss.name = N'dbo')
DROP TYPE [dbo].[AccountDataTable]
GO
/****** Object:  UserDefinedTableType [dbo].[AC_Settings]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'AC_Settings' AND ss.name = N'dbo')
DROP TYPE [dbo].[AC_Settings]
GO
/****** Object:  User [IrecordSoftware]    Script Date: 01/11/2019 12:09:53 PM ******/
IF  EXISTS (SELECT * FROM sys.database_principals WHERE name = N'IrecordSoftware')
DROP USER [IrecordSoftware]
GO
/****** Object:  User [IrecordSoftware]    Script Date: 01/11/2019 12:09:53 PM ******/
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'IrecordSoftware')
CREATE USER [IrecordSoftware] WITHOUT LOGIN WITH DEFAULT_SCHEMA=[dbo]
GO
/****** Object:  UserDefinedTableType [dbo].[AC_Settings]    Script Date: 01/11/2019 12:09:53 PM ******/
IF NOT EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'AC_Settings' AND ss.name = N'dbo')
CREATE TYPE [dbo].[AC_Settings] AS TABLE(
	[Member_Code] [varchar](7) NULL,
	[Year_Code] [varchar](10) NULL,
	[Description] [varchar](7) NULL,
	[AC_Code] [varchar](200) NULL,
	[InternalEntry] [int] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[AccountDataTable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF NOT EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'AccountDataTable' AND ss.name = N'dbo')
CREATE TYPE [dbo].[AccountDataTable] AS TABLE(
	[Member_Code] [varchar](10) NULL,
	[Year_Code] [varchar](10) NULL,
	[Description] [varchar](max) NULL,
	[AC_Code] [varchar](20) NULL,
	[InternalEntry] [int] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[ACSettingsDataTable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF NOT EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'ACSettingsDataTable' AND ss.name = N'dbo')
CREATE TYPE [dbo].[ACSettingsDataTable] AS TABLE(
	[Member_Code] [varchar](7) NULL,
	[Year_Code] [varchar](10) NULL,
	[Description] [varchar](7) NULL,
	[Ac_Code] [varchar](200) NULL,
	[InternalEntry] [int] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[BrokerageDataTable]    Script Date: 01/11/2019 12:09:53 PM ******/
IF NOT EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'BrokerageDataTable' AND ss.name = N'dbo')
CREATE TYPE [dbo].[BrokerageDataTable] AS TABLE(
	[Ac_Code] [varchar](max) NULL,
	[Investment_Type] [varchar](10) NULL,
	[Buy_Brokrage] [float] NULL,
	[Sell_Brokerage] [float] NULL,
	[Per_Order] [int] NULL,
	[Max_Brokrage] [float] NULL,
	[Min_Brokrge] [float] NULL,
	[Member_Code] [varchar](max) NULL,
	[Year_Code] [varchar](10) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[BrokerBill_Format_Expense]    Script Date: 01/11/2019 12:09:53 PM ******/
IF NOT EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'BrokerBill_Format_Expense' AND ss.name = N'dbo')
CREATE TYPE [dbo].[BrokerBill_Format_Expense] AS TABLE(
	[Member_code] [varchar](max) NULL,
	[Tax_code] [varchar](max) NULL,
	[year_code] [varchar](max) NULL,
	[InvestmentType] [int] NULL,
	[Tax_Name] [varchar](max) NULL,
	[BrokerBill_Format_No] [int] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[BrokerMonthWiseEquityOpenings]    Script Date: 01/11/2019 12:09:53 PM ******/
IF NOT EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'BrokerMonthWiseEquityOpenings' AND ss.name = N'dbo')
CREATE TYPE [dbo].[BrokerMonthWiseEquityOpenings] AS TABLE(
	[id] [int] NULL,
	[Trans_No] [varchar](20) NULL,
	[script_name] [varchar](500) NULL,
	[script_Code] [varchar](50) NULL,
	[holding_type] [varchar](200) NULL,
	[Broker_Name] [varchar](100) NULL,
	[bill_no] [varchar](100) NULL,
	[trans_dt] [datetime] NULL,
	[qty] [float] NULL DEFAULT ((0)),
	[rate] [float] NULL DEFAULT ((0)),
	[amount] [float] NULL DEFAULT ((0)),
	[isintraday] [bit] NULL DEFAULT ((0)),
	[BillType] [varchar](20) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[DematDataTable]    Script Date: 01/11/2019 12:09:54 PM ******/
IF NOT EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'DematDataTable' AND ss.name = N'dbo')
CREATE TYPE [dbo].[DematDataTable] AS TABLE(
	[Member_Code] [varchar](7) NULL,
	[Year_Code] [varchar](10) NULL,
	[DP_Code] [varchar](7) NULL,
	[DP_Name] [varchar](200) NULL,
	[InternalEntry] [int] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[InvestMentDataTable]    Script Date: 01/11/2019 12:09:54 PM ******/
IF NOT EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'InvestMentDataTable' AND ss.name = N'dbo')
CREATE TYPE [dbo].[InvestMentDataTable] AS TABLE(
	[Member_Code] [varchar](7) NULL,
	[Year_Code] [varchar](10) NULL,
	[Investment_Code] [varchar](7) NULL,
	[Investment_Name] [varchar](200) NULL,
	[InternalEntry] [int] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[MyDataTable]    Script Date: 01/11/2019 12:09:54 PM ******/
IF NOT EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'MyDataTable' AND ss.name = N'dbo')
CREATE TYPE [dbo].[MyDataTable] AS TABLE(
	[Member_Code] [varchar](7) NULL,
	[Year_Code] [varchar](10) NULL,
	[AC_Code] [varchar](7) NULL,
	[AC_Name] [varchar](100) NULL,
	[Grp_Name] [varchar](50) NULL,
	[Grp_id] [int] NULL,
	[Effect] [varchar](1) NULL,
	[Effect1] [varchar](1) NULL,
	[Op_Bal] [money] NULL,
	[Op_Cal] [money] NULL,
	[InternalEntry] [int] NULL,
	[Contact_Person] [varchar](50) NULL,
	[Add1] [varchar](50) NULL,
	[Add2] [varchar](50) NULL,
	[Add3] [varchar](50) NULL,
	[Mobile_No] [varchar](25) NULL,
	[Tel_No] [varchar](25) NULL,
	[Fax_No] [varchar](25) NULL,
	[email] [varchar](75) NULL,
	[website] [varchar](75) NULL,
	[Pan_No] [varchar](50) NULL,
	[UCC_Code] [varchar](50) NULL,
	[DecimalPlaces] [int] NULL,
	[DefaultAcInBrokerBill] [int] NULL,
	[IsBrokeragePerUnit] [int] NULL,
	[EQB_Brokerage] [money] NULL,
	[EQS_Brokerage] [money] NULL,
	[FOB_Brokerage] [money] NULL,
	[FOS_Brokerage] [money] NULL,
	[IDB_Brokerage] [money] NULL,
	[IDS_Brokerage] [money] NULL,
	[Investment_Code] [varchar](7) NULL,
	[CURB_Brokerage] [real] NULL,
	[CURS_Brokerage] [real] NULL,
	[MCXB] [real] NULL,
	[MCXS] [real] NULL,
	[MFB] [real] NULL,
	[MFS] [real] NULL,
	[eqintradaybuy] [real] NULL,
	[eqintradaysell] [real] NULL,
	[NCDEXB_Brokerage] [real] NULL,
	[NCDEXS_Brokerage] [real] NULL,
	[ExpenseSetting] [varchar](1) NULL
)
GO
/****** Object:  UserDefinedFunction [dbo].[AccountGroupcodestable]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AccountGroupcodestable]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
CREATE FUNCTION [dbo].[AccountGroupcodestable]
(
@list as varchar(Max), @delim as varchar(10))
RETURNS @listTable table( Value varchar(Max)
)
AS
BEGIN
    --Declare helper to identify the position of the delim
    DECLARE @DelimPosition INT
    
    --Prime the loop, with an initial check for the delim
    SET @DelimPosition = CHARINDEX(@delim, @list)

    --Loop through, until we no longer find the delimiter
    WHILE @DelimPosition > 0
    BEGIN
        --Add the item to the table
        INSERT INTO @listTable(Value)
            VALUES(CAST(RTRIM(LEFT(@list, @DelimPosition - 1)) AS varchar(Max)))
    
        --Remove the entry from the List
        SET @list = right(@list, len(@list) - @DelimPosition)

        --Perform position comparison
        SET @DelimPosition = CHARINDEX(@delim, @list)
   end 

    --If we still have an entry, add it to the list
    IF len(@list) > 0
        insert into @listTable(Value)
        values(CAST(RTRIM(@list) AS varchar(Max)))
		
  RETURN
END













' 
END

GO
/****** Object:  UserDefinedFunction [dbo].[consultantcodestable]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[consultantcodestable]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
CREATE FUNCTION [dbo].[consultantcodestable]
(
@list as varchar(Max), @delim as varchar(10))
RETURNS @listTable table( Value varchar(Max)
)
AS
BEGIN
    --Declare helper to identify the position of the delim
    DECLARE @DelimPosition INT
    
    --Prime the loop, with an initial check for the delim
    SET @DelimPosition = CHARINDEX(@delim, @list)

    --Loop through, until we no longer find the delimiter
    WHILE @DelimPosition > 0
    BEGIN
        --Add the item to the table
        INSERT INTO @listTable(Value)
            VALUES(CAST(RTRIM(LEFT(@list, @DelimPosition - 1)) AS varchar(Max)))
    
        --Remove the entry from the List
        SET @list = right(@list, len(@list) - @DelimPosition)

        --Perform position comparison
        SET @DelimPosition = CHARINDEX(@delim, @list)
   end 

    --If we still have an entry, add it to the list
    IF len(@list) > 0
        insert into @listTable(Value)
        values(CAST(RTRIM(@list) AS varchar(Max)))
		
  RETURN
END













' 
END

GO
/****** Object:  UserDefinedFunction [dbo].[fn_Split]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_Split]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
CREATE  FUNCTION [dbo].[fn_Split](@text varchar(Max), @delimiter varchar(20) = '' '')
RETURNS @Strings TABLE
(   
  position int IDENTITY PRIMARY KEY,
  value varchar(Max)  
)
AS
BEGIN

DECLARE @index int
SET @index = -1

WHILE (LEN(@text) > 0)
  BEGIN 
    SET @index = CHARINDEX(@delimiter , @text) 
    IF (@index = 0) AND (LEN(@text) > 0) 
      BEGIN  
        INSERT INTO @Strings VALUES (@text)
          BREAK 
      END 
    IF (@index > 1) 
      BEGIN  
        INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))  
        SET @text = RIGHT(@text, (LEN(@text) - @index)) 
      END 
    ELSE
      SET @text = RIGHT(@text, (LEN(@text) - @index))
    END
  RETURN
END








' 
END

GO
/****** Object:  UserDefinedFunction [dbo].[fnGetGainnLoss]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fnGetGainnLoss]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'


--  Select [dbo].[fnGetGainnLoss](1,''K0028'', 0, 29.6000, 45.6000, 2006-02-01 ,2019-01-28, 40, 40)
CREATE function [dbo].[fnGetGainnLoss]
(@investmentType int, 
@Script_Code varchar(10), 
@IsBSE varchar(2),
@PurchaseRate float,
@soldRate float, 
@PurchasesDate DateTime, 
@SoldDate DateTime,
@PurchagseQTy float, 
@SoldQty float )
returns float
As
	BEGIN
	
		IF(@IsBSE = '''')
			SET @IsBSE = 1

		DECLARE @NewPurchaseRate float
		DECLARE @GainNLoss float
		DECLARE @31stPriceRate float
		DECLARE @31stDate Datetime = CONVERT(DATETIME,''31/01/2018'',103) 
		
		SET @31stPriceRate	= CASE WHEN (@investmentType = 0)  -- Equity
								   THEN 
										CASE
										WHEN (@IsBSE = 1 AND (Select top(1) BSE_High_Rate  from dbo.DailyRate Where Trans_Dt = @31stDate and Script_Code = @Script_Code) IS NOT NULL)
												THEN  (Select top(1) BSE_High_Rate  from dbo.DailyRate Where Trans_Dt =@31stDate  and Script_Code = @Script_Code)
										WHEN (@IsBSE = 1 AND (Select top(1) NSE_High_Rate  from dbo.DailyRate Where Trans_Dt = @31stDate and Script_Code = @Script_Code) IS NOT NULL)
												THEN (Select top(1) NSE_High_Rate  from dbo.DailyRate Where Trans_Dt = @31stDate and Script_Code = @Script_Code)
										ELSE
											(Select top(1) BSE_High_Rate  from dbo.DailyRate Where Trans_Dt = @31stDate and Script_Code = @Script_Code)
										END
								   WHEN (@investmentType = 2)  -- Mutual Fund
								   THEN 
										CASE WHEN @IsBSE = 1 AND (Select top(1) NSE_Rate  from dbo.DailyRate Where Trans_Dt = @31stDate and Script_Code = @Script_Code and  InvestmentType=@investmentType) IS NOT NULL
												THEN  (Select top(1) NSE_Rate  from dbo.DailyRate Where Trans_Dt =@31stDate  and Script_Code = @Script_Code and InvestmentType=@investmentType)
											 
											     ELSE (Select top(1) NSE_Rate  from dbo.DailyRate Where Trans_Dt = @31stDate and Script_Code = @Script_Code and InvestmentType=@investmentType)
										END
									WHEN (@investmentType = 1 OR @investmentType = 3 OR @investmentType = 4) -- F&O,MCX,Currency
									THEN 	
										CASE WHEN @IsBSE = 1 AND (Select top(1) Bse_FO_Rate  from dbo.DailyRate Where Trans_Dt = @31stDate and Script_Code = @Script_Code) IS NOT NULL
												THEN  (Select top(1) Bse_FO_Rate  from dbo.DailyRate Where Trans_Dt = @31stDate and Script_Code = @Script_Code)
											 WHEN @IsBSE = 0 AND (Select top(1) Nse_FO_Rate  from dbo.DailyRate Where Trans_Dt =@31stDate and Script_Code = @Script_Code) IS NOT NULL
												THEN  (Select top(1) Nse_FO_Rate  from dbo.DailyRate Where Trans_Dt = @31stDate and Script_Code = @Script_Code)
											 ELSE (Select top(1) Bse_FO_Rate  from dbo.DailyRate Where Trans_Dt = @31stDate and Script_Code = @Script_Code)
										END
									ELSE (Select top(1) Bse_Rate  from dbo.DailyRate Where Trans_Dt = @31stDate and Script_Code = @Script_Code)
								END
		--RETURN @31stPriceRate
	   
		if((@31stPriceRate is null or @31stPriceRate=0) and (@SoldDate >= @31stDate ) and (@PurchasesDate < @31stDate ))
			return (@soldRate * @SoldQty) - (@PurchaseRate * @PurchagseQTy)

		SET @NewPurchaseRate =  CASE 
									--WHEN @PurchasesDate > CONVERT(DATE,''31/01/2018'',103) 
									WHEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME, @PurchasesDate,101)),CONVERT(VARCHAR,CONVERT(DATETIME,''2018-01-31'',101))) < 0
										THEN @PurchaseRate
									WHEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME, @SoldDate,101)),CONVERT(VARCHAR,CONVERT(DATETIME,''2018-01-31'',101))) > 0
										THEN @PurchaseRate
									WHEN @PurchaseRate > ISNULL(@31stPriceRate,0) 
										THEN @PurchaseRate
									ELSE 									
										CASE WHEN ISNULL(@31stPriceRate,0) > @soldRate AND  @soldRate > @PurchaseRate   THEN    ISNULL(@soldRate,0)
											 WHEN ISNULL(@31stPriceRate,0) > @soldRate AND  @soldRate < @PurchaseRate   THEN   ISNULL(@PurchaseRate,0)-- @PurchaseRate
											 WHEN ISNULL(@31stPriceRate,0) < @soldRate AND @soldRate > @PurchaseRate    THEN  ISNULL(@31stPriceRate,0) --1
										END
								END

     
		SET @GainNLoss = (@soldRate * @SoldQty) - (@NewPurchaseRate * @PurchagseQTy)
		RETURN Round(@GainNLoss,4)
	END














' 
END

GO
/****** Object:  UserDefinedFunction [dbo].[GroupDetailscodestable]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GroupDetailscodestable]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
CREATE  FUNCTION [dbo].[GroupDetailscodestable]
(
@list as varchar(Max), @delim as varchar(10))
RETURNS @listTable table( Value varchar(Max)
)
AS
BEGIN
    --Declare helper to identify the position of the delim
    DECLARE @DelimPosition INT
    
    --Prime the loop, with an initial check for the delim
    SET @DelimPosition = CHARINDEX(@delim, @list)

    --Loop through, until we no longer find the delimiter
    WHILE @DelimPosition > 0
    BEGIN
        --Add the item to the table
        INSERT INTO @listTable(Value)
            VALUES(CAST(RTRIM(LEFT(@list, @DelimPosition - 1)) AS varchar(Max)))
    
        --Remove the entry from the List
        SET @list = right(@list, len(@list) - @DelimPosition)

        --Perform position comparison
        SET @DelimPosition = CHARINDEX(@delim, @list)
   end 

    --If we still have an entry, add it to the list
    IF len(@list) > 0
        insert into @listTable(Value)
        values(CAST(RTRIM(@list) AS varchar(Max)))
		
  RETURN
END













' 
END

GO
/****** Object:  UserDefinedFunction [dbo].[membercodestable]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[membercodestable]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
CREATE FUNCTION [dbo].[membercodestable]
(
@list as varchar(MAx), @delim as varchar(10))
RETURNS @listTable table( Value varchar(Max)
)
AS
BEGIN
    --Declare helper to identify the position of the delim
    DECLARE @DelimPosition INT
    
    --Prime the loop, with an initial check for the delim
    SET @DelimPosition = CHARINDEX(@delim, @list)

    --Loop through, until we no longer find the delimiter
    WHILE @DelimPosition > 0
    BEGIN
        --Add the item to the table
        INSERT INTO @listTable(Value)
            VALUES(CAST(RTRIM(LEFT(@list, @DelimPosition - 1)) AS varchar(Max)))
    
        --Remove the entry from the List
        SET @list = right(@list, len(@list) - @DelimPosition)

        --Perform position comparison
        SET @DelimPosition = CHARINDEX(@delim, @list)
   end 

    --If we still have an entry, add it to the list
    IF len(@list) > 0
        insert into @listTable(Value)
        values(CAST(RTRIM(@list) AS varchar(Max)))
		
  RETURN
END













' 
END

GO
/****** Object:  UserDefinedFunction [dbo].[Scriptcodestable]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Scriptcodestable]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
--Script Function Define--

CREATE FUNCTION [dbo].[Scriptcodestable]
(
@list as varchar(Max), @delim as varchar(10))
RETURNS @listTable table( Value varchar(Max)
)
AS
BEGIN
    --Declare helper to identify the position of the delim
    DECLARE @DelimPosition INT
    
    --Prime the loop, with an initial check for the delim
    SET @DelimPosition = CHARINDEX(@delim, @list)

    --Loop through, until we no longer find the delimiter
    WHILE @DelimPosition > 0
    BEGIN
        --Add the item to the table
        INSERT INTO @listTable(Value)
            VALUES(CAST(RTRIM(LEFT(@list, @DelimPosition - 1)) AS varchar(Max)))
    
        --Remove the entry from the List
        SET @list = right(@list, len(@list) - @DelimPosition)

        --Perform position comparison
        SET @DelimPosition = CHARINDEX(@delim, @list)
   end 

    --If we still have an entry, add it to the list
    IF len(@list) > 0
        insert into @listTable(Value)
        values(CAST(RTRIM(@list) AS varchar(Max)))
		
  RETURN
END











' 
END

GO
/****** Object:  StoredProcedure [dbo].[Account_Master_Report_groupwise]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Account_Master_Report_groupwise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Account_Master_Report_groupwise] AS' 
END
GO
ALTER Procedure [dbo].[Account_Master_Report_groupwise]
(

 
 @Account Varchar(50),
 @group   Varchar(50),
 @yearcode varchar(10),
 @memcode varchar(10)
)
--..........Account Master ....
As



---Group with Account Details.......
if(@Account!='')
Begin
SET NOCOUNT ON;

Select Mst_Account.Grp_Name ,Mst_Account.AC_Name,Mst_Account.Contact_Person,Mst_Account.Add1,Mst_Account.Tel_No,
Mst_Account.Fax_No,Mst_Account.email from Mst_Account
where InternalEntry='0' and Mst_Account.AC_Code  in(SELECT Value FROM membercodestable(@Account,','))and Mst_Account.Grp_id in (SELECT Value FROM  Scriptcodestable(@group,',')) and Mst_Account.Year_Code=@yearcode and Mst_Account.Member_Code=@memcode;
End
else if(@Account='')
Begin
Select Mst_Account.Grp_Name ,Mst_Account.AC_Name,Mst_Account.Contact_Person,Mst_Account.Add1,Mst_Account.Tel_No,
Mst_Account.Fax_No,Mst_Account.email from Mst_Account
where InternalEntry='0'  and Mst_Account.Grp_id in (SELECT Value FROM  Scriptcodestable(@group,',')) and Mst_Account.Year_Code=@yearcode and Mst_Account.Member_Code=@memcode
End
































GO
/****** Object:  StoredProcedure [dbo].[Annexure_2]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Annexure_2]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Annexure_2] AS' 
END
GO


  -- EXEC Annexure_2 '04/01/2018','03/31/2019','0','J0007','1120182019','','','','0','',0,''
 
ALTER PROCEDURE [dbo].[Annexure_2]
(
	@Fromdate varchar(50),
	@Todate varchar(50),
	@holdingtype VARCHAR(50),
	@membercode VARCHAR(Max),
	@YearCode VARCHAR(50),
	@scriptcode VARCHAR(max),
	@familycode NVARCHAR(max),
	@consultantcode NVARCHAR(max),
	@Investmenttype NVARCHAR(250),
	@Brokercode VARCHAR(max),
	@IsBfCF bit = 0,
	@Script_Name varchar(max) = ''
) 
                                 
AS 
  BEGIN 
  SET NOCOUNT ON;

      DECLARE @sqlstr AS NVARCHAR(max) 

	  CREATE TABLE #mainoutputtable_1_Final_ledger 
        ( 
		   opening_bill_no varchar(10),
           id INT,
		   prioritys INT,
		   ScriptCode varchar(10),
		   Family_Name VARCHAR(500),
		   Member_Name VARCHAR(500),
		   Family_Code VARCHAR(500),
		   Member_Code VARCHAR(500),
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200),
           opening_date VARCHAR(50),
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date VARCHAR(50),
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date VARCHAR(50),
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain FLOAT DEFAULT 0,
		   loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   sort   VARCHAR(5),
		   broker_code varchar(MAx)
        ) 

	  if (@Investmenttype = 2)
			set @holdingtype = ''
	
		if(@Investmenttype = 0 OR @Investmenttype = 2)
			BEGIN
				IF(@Brokercode <> '' AND @familycode = '' )
				BEGIN
					Insert into #mainoutputtable_1_Final_ledger
					EXEC proc_StockholdingPosition_BrokerWise_Equity   0, @Investmenttype ,@holdingtype,@membercode,@yearcode,@Fromdate,@Todate,@ScriptCode,@Brokercode,'','','0','0','Annexture'
				END
				ELSE
				BEGIN
					Insert into #mainoutputtable_1_Final_ledger
					EXEC proc_StockholdingPosition_FamilyWise_Equity   0, @Investmenttype ,@holdingtype,@membercode,@yearcode,@Fromdate,@Todate,@ScriptCode,@consultantcode,'','','0',0,'ScriptwiseTotal',@familycode,0
				END
			END
		ELSE 
			BEGIN
				IF(@Brokercode <> '' AND @familycode = '' )
				BEGIN
					Insert into #mainoutputtable_1_Final_ledger
					EXEC proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency   0, @Investmenttype ,'0',@membercode,@yearcode,@Fromdate,@Todate,@ScriptCode,@BrokerCode,'',@IsBfCF,'0','0','Annexture',0,@Script_Name
				END
				ELSE
				BEGIN
					Insert into #mainoutputtable_1_Final_ledger
					EXEC proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency   0, @Investmenttype ,'0',@membercode,@yearcode,@Fromdate,@Todate,@ScriptCode,'','',@IsBfCF,'0','0','ScriptwiseTotal',@familycode,@Script_Name
				END
			END
		--Select * from #mainoutputtable_1_Final_ledger
			CREATE TABLE #temp1
			(
				Family_Name varchar(50),Member_Name varchar(50),Member_Code varchar(50), script_code varchar(50),script_name varchar(50), 
				Opening_Qty varchar(50),Purchases varchar(50),Sales varchar(50),Closing_Stock  varchar(50)  
			)
			
			DECLARE @TempMemberCode varchar(1000)
			IF(@membercode = '' AND @familycode != '')
				BEGIN 
					Select Member_Code 
					INTO #Members 
					FROM Mst_Member Where Family_Code IN (SELECT Value FROM membercodestable(@familycode,','))
			
					declare @tmp varchar(250)
					SET @tmp = ''
					select @tmp = @tmp + Member_Code + ',' from #Members
					SET @TempMemberCode = 	IsNULL((select SUBSTRING(@tmp, 0, LEN(@tmp))),'')
				END
			ELSE 
					SET @TempMemberCode = 	@membercode

		
		
			IF(@Investmenttype='0'or @Investmenttype='2')
				BEGIN
					SET @sqlstr = 'Select BrokerBill_Trans.script_code,Mst_Script.Script_Name as Script_Name, '''' as Last_Date'
				END
			ELSE
				BEGIN
				
					DECLARE @ScriptName varchar(500)  = 'Mst_Script.Script_Name 
						 + ''/'' +  CONVERT(VARCHAR(10),Last_Date,103) 
						 +	CASE WHEN ISNULL(Strike_Price,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),Strike_Price) ELSE '''' END
						 +  CASE WHEN ISNULL(OptionType,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),OptionType) ELSE '''' 
							END As Script_Name'
						
					
					SET @sqlstr = 'Select BrokerBill_Trans.script_code,' + @ScriptName + ',Last_Date as Last_Date'
					
				END
            
			SET @sqlstr=@sqlstr+',Mst_Family.Family_Name as Family_Name'
			
			IF ( @TempMemberCode <> '' ) 
				BEGIN 
					SET @sqlstr = @sqlstr + ',Mst_Member.Member_Name as Member_Name'
				END
			ELSE
				BEGIN
					SET @sqlstr = @sqlstr + ', '''' as Member_Name'
				END   
		
		    IF ( @consultantcode <> '' ) 
				BEGIN 
					SET @sqlstr = @sqlstr + ',BrokerBill_Trans.Consultant_code,c.Consultant_Name '
				END
			ELSE
				BEGIN
					--SET @sqlstr = @sqlstr + ', '''' Consultant_code, '''' Consultant_Name'
					SET @sqlstr = @sqlstr +  ',BrokerBill_Trans.Consultant_code, c.Consultant_Name'
				END   
			SET @sqlstr = @sqlstr +',BrokerBill.Broker_Code '
			
			SET @sqlstr = @sqlstr + ',BrokerBill_Trans.Member_Code as Member_Code ,Mst_Account.AC_Name,BrokerBill.Trans_no ' 
			SET @sqlstr = @sqlstr + ',Sum(CASE When BrokerBill_Trans.Bill_no=''opening'' Then Qty else 0 End ) As Opening_Qty, ' 
			SET @sqlstr = @sqlstr + 'SUM(CASE WHEN TransType = ''Bought''and BrokerBill_Trans.Bill_no !=''opening'' THEN Qty ELSE 0 END) AS Purchases_Qty,'
			SET @sqlstr = @sqlstr + 'SUM(CASE WHEN TransType = ''Sold'' THEN Qty ELSE 0 END) Sales_Qty,' 
			SET @sqlstr = @sqlstr + '((Sum(CASE When BrokerBill_Trans.Bill_no=''opening'' Then Qty else 0 End ) +   SUM(CASE WHEN TransType = ''Bought'' and BrokerBill_Trans.Bill_no!=''opening'' THEN Qty ELSE 0 END)) - SUM(CASE WHEN TransType = ''Sold'' THEN Qty ELSE 0 END)) as Closing_Stock '
			SET @sqlstr = @sqlstr + ' into #temp1 from BrokerBill_Trans ' 
			SET @sqlstr = @sqlstr + ' join Mst_Member on BrokerBill_Trans.Member_code = Mst_Member.Member_Code ' 
			SET @sqlstr = @sqlstr + ' Join Mst_Script on Mst_Script.Script_Code = BrokerBill_Trans.Script_Code ' 
			SET @sqlstr = @sqlstr + ' join Mst_Family on Mst_Family.Family_Code = Mst_Member.Family_Code ' 
			SET @sqlstr = @sqlstr + ' Join Mst_Consultant c on BrokerBill_Trans.Consultant_code = c.Consultant_code '
			SET @sqlstr = @sqlstr + ' Inner Join BrokerBill On BrokerBill.Trans_no=BrokerBill_Trans.Trans_No and BrokerBill.Member_Code IN (SELECT Value FROM membercodestable(' + Char(39) + @TempMemberCode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  and BrokerBill.YearCode='+ Char(39) + @YearCode + Char(39)+ ''
			SET @sqlstr = @sqlstr + ' Inner join Mst_Account on Mst_Account.AC_Code=BrokerBill.Broker_Code and Mst_Account.Member_Code IN (SELECT Value FROM membercodestable(' + Char(39) + @TempMemberCode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  and Mst_Account.Year_Code='+ Char(39) + @YearCode + Char(39)+ '' 
			SET @sqlstr = @sqlstr + ' where  BrokerBill_Trans.isFNOBill= ' + Char(39) + @Investmenttype + Char(39) 
			if(@Investmenttype = 0)
				SET @sqlstr = @sqlstr + ' and BrokerBill_Trans.Ac_Type =  (select case  when ' + Char(39) +  @holdingtype + Char(39) + ' = 0 then BrokerBill_Trans.Ac_Type  else '+ @holdingtype +' end)' 
			SET @sqlstr = @sqlstr + ' and BrokerBill_Trans.Member_code in (SELECT Value FROM membercodestable(' + Char(39) + @TempMemberCode + Char(39) + ',' + Char(39) + ',' + Char(39) + ')) ' 
			SET @sqlstr = @sqlstr + ' and BrokerBill_Trans.YearCode = ' + @YearCode 
			
			IF ( @familycode <> '' ) 
				BEGIN
					SET @sqlstr = @sqlstr + ' and Mst_Family.Family_Code in (SELECT Value FROM membercodestable(' + Char(39) + @familycode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
				END

		    IF(@Investmenttype='0'or @Investmenttype='2')
				BEGIN
					IF ( @scriptcode <> '' ) 
						BEGIN 
						  SET @sqlstr = @sqlstr + ' and BrokerBill_Trans.Script_Code in (SELECT Value FROM membercodestable(' + Char(39) + @scriptcode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
						END 
				END
			ELSE
				BEGIN
					IF ( @Script_Name <> '' ) 
						BEGIN 
							DECLARE @ScriptNametemp varchar(500)  = 'Mst_Script.Script_Name 
						 + ''/'' +  CONVERT(VARCHAR(10),Last_Date,103) 
						 +	CASE WHEN ISNULL(Strike_Price,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),Strike_Price) ELSE '''' END
						 +  CASE WHEN ISNULL(OptionType,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),OptionType) ELSE '''' 
							END'
						  SET @sqlstr = @sqlstr + ' and ' + @ScriptNametemp + ' in (SELECT Value FROM membercodestable(' + Char(39) + @Script_Name + Char(39) + ',' + Char(39) + ',' + Char(39) + ')) ' 
						END 
				END 

			IF ( @Brokercode <> '')
				BEGIN
				   SET @sqlstr =@sqlstr + ' and BrokerBill.Broker_Code in(SELECT Value FROM membercodestable(' + Char(39) + @Brokercode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  '
				END
			IF ((@familycode = '' OR @membercode <> '') and @consultantcode <> '' ) 
			  BEGIN 
				  SET @sqlstr = @sqlstr + ' and BrokerBill_Trans.Consultant_code in (SELECT Value FROM membercodestable('+ Char(39) + @consultantcode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
			  END
			

			IF(@TempMemberCode <> '')
				BEGIN 
					SET @sqlstr= @sqlstr +' GROUP BY Family_Name,Member_Name,BrokerBill.Broker_Code,BrokerBill_Trans.Script_Code,Mst_Script.Script_Name,BrokerBill_Trans.Last_Date,BrokerBill_Trans.OptionType,BrokerBill_Trans.Strike_Price,BrokerBill_Trans.Member_Code,Mst_Account.AC_Name,BrokerBill.Trans_no,BrokerBill_Trans.Consultant_code,c.Consultant_Name'	
				END
			ELSE
				BEGIN
					SET @sqlstr= @sqlstr +' GROUP BY Family_Name,BrokerBill.Broker_Code,BrokerBill_Trans.Script_Code,Mst_Script.Script_Name,BrokerBill_Trans.Last_Date,BrokerBill_Trans.OptionType,BrokerBill_Trans.Strike_Price,BrokerBill_Trans.Member_Code,Mst_Account.AC_Name,BrokerBill.Trans_no,BrokerBill_Trans.Consultant_code,c.Consultant_Name'			
				END

			IF ( @consultantcode <> '' ) 
			  BEGIN 
				  SET @sqlstr = @sqlstr +  ',BrokerBill_Trans.Consultant_code, c.Consultant_Name'
			  END 
			 
			--select 'test'
			--print @sqlstr
		
				
				if(@Brokercode <> '' AND  @FamilyCode = '')
					BEGIN
						
						SET @sqlstr=@sqlstr +    ' Select * Into #Temp_1 From #temp1
													SELECT 
													t.Last_Date,
													t.script_code, 
													t.Script_Name, 
													t.Family_Name,
													t.Member_Name, 
													t.Member_Code,
													t.Consultant_code,
													t.Consultant_Name,
													t.AC_Name,
													sl.broker_code,
												    sl.opening_qty as ''Opening_Qty'' , 
													sl.purchase_qty as ''Purchases_Qty'' , 
													sl.sold_qty as ''Sales_Qty'' , 
													sl.closing_qty as ''Closing_Stock'','

						SET @sqlstr=@sqlstr +     ' CASE 
														WHEN SUM(sl.closing_qty) <> 0 
														THEN ROUND((ISNULL(sl.closing_rate,0)),4)     
														ELSE 0 
													END as  ''Closing_Rate'' ,
													Round(ISNULL(sl.Closing_Value,0),4) as ''Closing_Amount'', 
													Round(ISNULL(sl.opening_rate,0),4) as ''Opening_rate'', 
													Round(ISNULL(sl.opening_amount,0),4) as ''Opening_amount'',
													Round(ISNULL(sl.purchase_rate,0),4) as ''purchase_rate'', 
													Round(ISNULL(sl.purchase_amount,0),4) as ''purchase_amount'',
													Round(ISNULL(sl.sold_rate,0),4) as ''sold_rate'',  
													Round(ISNULL(sl.sold_amount,0),4) as ''sold_amount''
													
													FROM   #Temp_1 t
													left Join #mainoutputtable_1_Final_ledger sl on t.Script_Name =  sl.Script_Name and t.Broker_Code = sl.broker_code 
													Group By    
													t.Family_Name,
													t.Consultant_code,
													t.Consultant_Name,
													t.Member_Name, 
													t.Member_Code,
													t.script_code, 
													t.Script_Name,
													t.AC_Name,
													sl.broker_code,
													t.Last_Date,
													sl.closing_rate,
													sl.purchase_rate,
													sl.sold_rate,
													sl.Closing_Value,
													sl.purchase_qty,
													sl.closing_qty,
													sl.opening_qty,
													sl.sold_qty,
													sl.purchase_amount,
													sl.sold_amount,
													sl.purchase_amount,
													sl.Opening_amount,
													sl.Opening_Rate
												--	ORDER BY  9,4,5,2,1'
					END
				ELSE 
					BEGIN		
						SET @sqlstr=@sqlstr +    ' 
												Select * Into #Temp_1 From #temp1 
												SELECT 
												t.Last_Date,
												t.script_code, 
												t.Script_Name, 
												t.Family_Name,
												t.Member_Name, 
												t.Member_Code,
												t.Consultant_code,
												t.Consultant_Name,
												'''' as AC_Name,
												'''' as broker_code,
												sl.opening_qty as ''Opening_Qty'' , 
												sl.purchase_qty as ''Purchases_Qty'' , 
												sl.sold_qty as ''Sales_Qty'' , 
												sl.closing_qty as ''Closing_Stock'' ,
												sl.holding_type as''holding_type'','
					SET @sqlstr=@sqlstr +     ' CASE 
													WHEN SUM(sl.closing_qty) <> 0 
													THEN ROUND((ISNULL(sl.closing_rate,0)),4)     
													ELSE 0 
												END as  ''Closing_Rate'' ,
												Round(ISNULL(sl.Closing_Value,0),4) as ''Closing_Amount'', 
												Round(ISNULL(sl.opening_rate,0),4) as ''Opening_rate'', 
												Round(ISNULL(sl.opening_amount ,0),4) as ''Opening_amount'',
												Round(ISNULL(sl.purchase_rate,0),4) as ''purchase_rate'', 
												Round(ISNULL(sl.purchase_amount,0),4) as ''purchase_amount'',
												Round(ISNULL(sl.sold_rate,0),4) as ''sold_rate'',  
												Round(ISNULL(sl.sold_amount,0),4) as ''sold_amount''
												FROM   #Temp_1 t
												left Join #mainoutputtable_1_Final_ledger sl on t.Script_Name =  sl.Script_Name and t.Member_Name = sl.Member_Name and sl.consultant_name=t.Consultant_Name
												Group By    
												t.Family_Name,
												t.Consultant_code,
												t.Consultant_Name,
												t.Member_Name, 
												t.Member_Code,
												t.script_code, 
												t.Script_Name,										
												t.Last_Date,
												sl.sold_rate,
												sl.purchase_rate,
												sl.closing_rate,
												sl.Closing_Value,
												sl.purchase_qty,
												sl.closing_qty,
												sl.opening_qty,
												sl.sold_qty,
												sl.sold_amount,
												sl.purchase_amount,
												sl.Opening_amount,
												sl.Opening_Rate,
												sl.holding_type
												--ORDER BY 4,5,2,1'
					END
						 
					SET @sqlstr=@sqlstr +    ' DROP TABLE #temp1 DROP TABLE #Temp_1'	
				
		--select 'test'
				
		--END 
		--Select @sqlstr
		EXEC sp_executesql   @sqlstr 
		
	Select BBT.qty,BBT.Rate, BBT.Script_Code,
	case WHEN BBt.isFNOBill = 0 OR BBt.isFNOBill=2 Then MS.Script_Name 
	     ELSE  MS.Script_Name 
					 + '/' +  CONVERT(VARCHAR(10),Last_Date,103) 
					 +	CASE WHEN ISNULL(Strike_Price,'') != '' THEN '/' + CONVERT(VARCHAR(10),Strike_Price) ELSE '' END
					 +  CASE WHEN ISNULL(OptionType,'') != '' THEN '/' + CONVERT(VARCHAR(10),OptionType) ELSE ''  END
	END AS 'Script_Name',

	BBT.Member_code ,MA.AC_Name,BBt.Consultant_code,MAA.AC_Name as'holding_type'
	from  BrokerBill_Trans BBT 
	LEFT JOIN BrokerBill BB ON BB.Trans_no=BBT.Trans_No AND  BB.Member_Code=BBT.Member_Code AND  BB.YearCode=BBT.YearCode
	LEFT JOIN Mst_Account MA ON MA.Ac_Code=BB.Broker_Code AND  MA.Member_Code=BB.Member_Code AND  MA.Year_Code=BB.YearCode
	LEFT JOIN Mst_Script MS On MS.Script_Code=BBT.Script_Code 
	LEFT JOIN Mst_Account MAA ON MAA.Ac_code=BBT.Ac_Type AND  MAA.Member_Code=BBT.Member_Code AND  MAA.Year_Code=BBT.YearCode
	Where BBT.Bill_no = 'Opening' and BBT.YearCode = @YearCode and BBT.Member_code=@membercode
                                      AND BBT.isFNOBill=@Investmenttype

	Group By MS.Script_Name ,BBT.qty,BBT.Rate, BBT.Script_Code,BBt.isFNOBill,Last_Date,Strike_Price,OptionType,
	BBT.Member_code,MA.AC_Name,BBt.Consultant_code,BBT.Sr_No,MAA.AC_Name
	order by BBT.Script_Code
 END 


--drop table ##tmp2 























GO
/****** Object:  StoredProcedure [dbo].[Auto_Pnl_Entry]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Auto_Pnl_Entry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Auto_Pnl_Entry] AS' 
END
GO
--exec Auto_Pnl_Entry '1100001325','03/31/2018','Y0001','1120172018','1100020','1100019',18254021.59
ALTER Procedure [dbo].[Auto_Pnl_Entry]
(
 @Transaction_No bigint,
 @Trans_Dt  DateTime,
 @Member_Code varchar(Max),
 @Year_Code varchar(20),
 @DRCode varchar(Max),
 @CRCode varchar(Max),
 @Amount  float

)

AS 
BEGIN
SET NOCOUNT ON;
	DELETE From AC_Trans Where Vouch_No='P&L' and Member_Code=@Member_Code and Year_Code=@Year_Code
 
    Insert INTO AC_Trans 

			(Trans_No,Sr_No,Trans_Dt,Member_Code,Year_Code,Vouch_No,Dr_Code,Cr_Code,Book_Type1,Narr1,Internal,Amount,InvestmentType,PayAgtBill,frmpg,EntryType)
	Values 
			(@Transaction_No,'1',@Trans_Dt,@Member_Code,@Year_Code,'P&L',@DRCode,@CRCode,'JV','Capital Gain/Loss','N',@Amount,'0','0','FinalStatement',0)

END
























GO
/****** Object:  StoredProcedure [dbo].[Broker_Format_Configuration]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Broker_Format_Configuration]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Broker_Format_Configuration] AS' 
END
GO
ALTER  Procedure [dbo].[Broker_Format_Configuration]
(
  @Format_Number int
)
As
	BEGIN

	   SET NOCOUNT ON;

		SELECT * FROM BrokerBill_Format_Configuration  WHERE Format_No = @Format_Number

		SELECT * FROM BrokerBill_Format_Column_Configuration WHERE Format_No = @Format_Number

		SELECT * FROM BrokerBill_Format_Expense_Column_Configuration WHERE Format_No = @Format_Number	


	END
























GO
/****** Object:  StoredProcedure [dbo].[BrokerScriptUpdate_information]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BrokerScriptUpdate_information]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[BrokerScriptUpdate_information] AS' 
END
GO
ALTER Procedure [dbo].[BrokerScriptUpdate_information]
	 @ID int,
	 @YearCode varchar(15),
	 @MemberCode varchar(Max),
     @BrokerCode varchar(MAx),
	 @InvestmentType int,
	 @ScriptName varchar(MAx),
	 @ScriptCode varchar(MAx)

As
BEGIN
SET NOCOUNT ON;
	IF(@ID != 0)
		BEGIN
			Update Broker_Script_Master
			SET Script_Code = @ScriptCode,
				Script_Name = @ScriptName
			where ID = @ID
		END
	ELSE
		BEGIN
			Insert INTO Broker_Script_Master ([Member_code],[Ac_code],[year_code],[Script_Code],[InvestmentType],[Script_Name])
			Values(@MemberCode,@BrokerCode,@YearCode,@ScriptCode,@InvestmentType,@ScriptName)

			SET @ID  = scope_identity() 
		END

	Select @ID
END























GO
/****** Object:  StoredProcedure [dbo].[CalculateStockInTrade]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CalculateStockInTrade]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[CalculateStockInTrade] AS' 
END
GO
ALTER Procedure [dbo].[CalculateStockInTrade]
(
 @Membercode Varchar(MAx),
 @Yearcode Varchar(1000),
 @Fromdate varchar(30),
 @Todate varchar(30)
 
 )
AS
BEGIN
SET NOCOUNT ON;

Create Table  #Brought
(
  Scriptcode Varchar(500),
  ScriptName Varchar(500),
  bought_sale Varchar(50),
  Qty Int,
  Consultantcode Varchar(500),
  
)
 
Insert Into #Brought (Scriptcode,ScriptName,Qty,bought_sale,Consultantcode)
(
	Select BrokerBill_Trans.Script_Code,  Ms.Script_Name,
	SUM(Qty),TransType,BrokerBill_Trans.Consultant_code from BrokerBill_Trans  
	Inner Join  Mst_Script MS On MS.Script_Code=BrokerBill_Trans.Script_Code 
	Where BrokerBill_Trans.Member_code=@Membercode and YearCode=@Yearcode and BrokerBill_Trans.Ac_Type='1100001' 
	and TransType='Bought' and isFNOBill='0' and Trans_Dt>=@Fromdate and Trans_Dt<=@Todate
	Group By BrokerBill_Trans.Script_Code,Ms.Script_Name,TransType,BrokerBill_Trans.Consultant_code  
)

 --Select * from #Brought
 

CReate Table  #Sale
(
  Scriptcode Varchar(500),
  ScriptName Varchar(500),
  bought_sale Varchar(50),
  Qty Int,
  Consultantcode Varchar(500)
)

Insert Into #Sale (Scriptcode,ScriptName,bought_sale,Qty,Consultantcode)
(Select BrokerBill_Trans.Script_Code,Ms.Script_Name,TransType,
SUM(Qty),BrokerBill_Trans.Consultant_code from BrokerBill_Trans  
Inner Join  Mst_Script MS On MS.Script_Code=BrokerBill_Trans.Script_Code 
Where BrokerBill_Trans.Member_code=@Membercode and YearCode=@Yearcode and BrokerBill_Trans.Ac_Type='1100001' 
and TransType='Sold' and isFNOBill='0' and Trans_Dt>=@Fromdate and Trans_Dt<=@Todate
Group By BrokerBill_Trans.Script_Code,Ms.Script_Name,Qty,TransType,BrokerBill_Trans.Consultant_code  )

--Select * from #Sale

Select #Brought.Scriptcode,
#Brought.ScriptName, 
ISNULL(#Brought.Qty,0) as 'Brought',
ISNULL(#Sale.Qty,0)  as'Sale',
case when SUM(ISNULL(#Brought.Qty,0))=0 then  ISNULL(#Sale.Qty,0) 
 ELSE
case when SUM(ISNULL(#Sale.Qty,0))=0 then  ISNULL(#Brought.Qty,0)  
ELSE ISNULL((sUM(#Brought.Qty) - suM(#Sale.Qty )),0)  end end As 'Clsoing Qty',#Brought.bought_sale,
#Brought.Consultantcode
from  #Brought
Left Join #Sale  On #Sale.Scriptcode=#Brought.Scriptcode

--Where (#Brought.Qty - #Sale.Qty>0)
GROUP By #Brought.Consultantcode ,#Brought.Scriptcode,#Brought.ScriptName,#Brought.Qty,#Sale.Qty,#Brought.bought_sale


--GROUP By #Brought.Scriptcode,#Brought.ScriptName,#Brought.bought_sale



Drop Table #Brought
Drop Table #Sale
END



























GO
/****** Object:  StoredProcedure [dbo].[CheckIfAccounExists]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CheckIfAccounExists]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[CheckIfAccounExists] AS' 
END
GO

ALTER procedure [dbo].[CheckIfAccounExists]
(
 @MemberCode Varchar(Max),
 @YearCode Varchar(20),
 @AccountCode Varchar(Max)
)
As
  -- 0 not exists
  -- 1 Exist in Expense
  -- 2 Exists in transactions 
 DECLARE @ReturnValue int = 0

    IF( (select count(*) from BrokerBill_Format_Expense where Tax_Code  =@AccountCode and Member_code= @MemberCode and Year_code=@YearCode) > 0 )
		BEGIN 
		SET NOCOUNT ON;
			SET @ReturnValue = 1
		END
	ELSE IF( (select count(*) from AC_Trans where (Dr_Code  = @AccountCode OR Cr_Code = @AccountCode) and Member_code= @MemberCode and Year_code=@YearCode) > 0 ) 
		BEGIN 
			SET @ReturnValue = 2
		END
	ELSE IF( (select count(*) from BrokerBill  where Broker_Code  = @AccountCode and Member_code= @MemberCode and YearCode= @YearCode) > 0 ) 
		BEGIN 
			SET @ReturnValue = 2
		END
	ELSE IF( (select count(*) from IPO where Broker_Code  = @AccountCode and Member_code= @MemberCode and Year_code=@YearCode) > 0 ) 
		BEGIN 
			SET @ReturnValue = 2
		END

	Select @ReturnValue















GO
/****** Object:  StoredProcedure [dbo].[CreateUser]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CreateUser]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[CreateUser] AS' 
END
GO

-- Execute [dbo].[CreateUser]  'test1','test1','Admin'

ALTER PROCEDURE [dbo].[CreateUser] 
	@UserName varchar(max),
	@password varchar(max),
	@UserType varchar(max)
AS
BEGIN
SET NOCOUNT ON;
	IF((Select count(*) from Users Where [User_Name] = @UserName) = 0)
		BEGIN
			DECLARE @ID int = 1
			IF((Select count(*) from Users ) > 0)
				SET @ID  = (Select Max([User_Id] + 1) from Users)
			
			INSERT INTO [dbo].[Users]
				   ([User_Id]
				   ,[User_Name]
				   ,[User_Paswd]
				   ,[User_Type])
			 VALUES
			   (
					@ID,
					@UserName,
					@password,
					@UserType
    			)
    	END
	ELSE
		BEGIN
			Update Users
			SET User_Paswd = @password,
				User_Type = @UserType
			WHERE [User_Name] = @UserName
		END
END


--select * from Users

--Alter Table Users
--select * from Ent_EntryTypes

--Select * from 

	














GO
/****** Object:  StoredProcedure [dbo].[Dividend_Report]    Script Date: 21/04/2020 7:40:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Dividend_Report]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Dividend_Report] AS' 
END
GO


-- exec [Dividend_Report] '20190401','20200330','','T0134',1,'1120192020' --'M0001','K0001'    
ALTER PROCEDURE [dbo].[Dividend_Report] (@trans_dt_from DATETIME, 
                                         @trans_dt_to   DATETIME, 
                                         @membercode    NVARCHAR(MAx), 
                                         @scriptcode    NVARCHAR(MAx), 
                                         @sortby        NVARCHAR(250),
										 @yearcode      NVARCHAR(MAX)) 
AS 
  BEGIN 
  SET NOCOUNT ON;

      IF( @membercode != '' AND @scriptcode != '' ) 
        BEGIN 
            SELECT MS.script_name                            AS 'Name of Company', 
                   ( CONVERT(VARCHAR(10), ET.ex_date, 103) ) AS 'EX Date', 
                   MM.member_name                            AS 'Member Name', 
                   ET.percentage                             AS 'Rs', 
                   ET.qty                                    AS 'Closing Stock', 
              
                   ET.amount                                 AS 'Amount', 
                   ET.narration                              AS 'Narration', 
				   ET.Bank_Date                              As 'Reco Date'
		    FROM   eqdividend_trans ET 
                   INNER JOIN mst_script MS 
                           ON ET.script_code = MS.script_code AND ET.member_code IN (SELECT value FROM   Membercodestable(@membercode, ',' )) AND ET.Year_code=@yearcode 
                   INNER JOIN mst_member MM 
                           ON MM.member_code = ET.member_code AND ET.Year_code=@yearcode
                   INNER JOIN mst_family MF 
                           ON MF.family_code = MM.family_code 
            WHERE  
					ET.ex_date BETWEEN @trans_dt_from AND @trans_dt_to OR ET.Bank_Date BETWEEN @trans_dt_from AND @trans_dt_to
                    AND ET.script_code IN (SELECT value FROM   Membercodestable(@scriptcode,',')) 
                    AND ET.member_code IN (SELECT value FROM   Membercodestable(@membercode, ',')) 
					AND ET.Year_code=@yearcode
            ORDER  BY CASE 
                        WHEN @sortby = 1 THEN  ( CONVERT(VARCHAR(10), ET.ex_date, 103) )
                        WHEN @sortby = 2 THEN [script_name] 
                        WHEN @sortby = 3 THEN [member_name] 
                      END ASC 
        END 
     
      ELSE IF( @membercode != '' AND @scriptcode = '' ) 
        BEGIN 
            SELECT MS.script_name                            AS 'Name of Company', 
                   ( CONVERT(VARCHAR(10), ET.ex_date, 103) ) AS 'EX Date', 
                   MM.member_name                            AS 'Member Name', 
                   ET.percentage                             AS 'Rs', 
                   ET.qty                                    AS 'Closing Stock', 
                   ET.amount                                 AS 'Amount', 
                   ET.narration                              AS 'Narration', 
				   ET.Bank_Date                              As 'Reco Date'
            FROM   eqdividend_trans ET 
                   INNER JOIN mst_script MS 
                           ON ET.script_code = MS.script_code  AND ET.member_code IN (SELECT value FROM   Membercodestable(@membercode, ',' )) AND ET.Year_code=@yearcode 
                   INNER JOIN mst_member MM 
                           ON MM.member_code = ET.member_code AND ET.Year_code=@yearcode
                   INNER JOIN mst_family MF 
                           ON MF.family_code = MM.family_code 
            WHERE  ET.ex_date BETWEEN @trans_dt_from AND @trans_dt_to OR ET.Bank_Date BETWEEN @trans_dt_from AND @trans_dt_to
                   --and ET.Script_Code in (select value from membercodestable(@scriptcode,','))
                   AND ET.member_code IN (SELECT value FROM   Membercodestable(@membercode, ',' )) 
				   AND ET.Year_code=@yearcode
        order by  CASE 
          WHEN @sortby  = 1 THEN  ( CONVERT(VARCHAR(10), ET.ex_date, 103) )
          WHEN @sortby  = 2 THEN [Script_Name]  
          WHEN @sortby  = 3 THEN [Member_Name] 
          END ASC 
        END 
     
	  ELSE IF( @membercode = '' AND @scriptcode != '' ) 
        BEGIN 
            SELECT MS.script_name                            AS 'Name of Company', 
                   ( CONVERT(VARCHAR(10), ET.ex_date, 103) ) AS 'EX Date', 
                   MM.member_name                            AS 'Member Name', 
                   ET.percentage                             AS 'Rs', 
                   ET.qty                                    AS 'Closing Stock', 
                   ET.amount                                 AS 'Amount', 
                   ET.narration                              AS 'Narration',
				   ET.Bank_Date                              As 'Reco Date' 
            FROM   eqdividend_trans ET 
                   INNER JOIN mst_script MS 
                           ON ET.script_code = MS.script_code AND ET.Year_code=@yearcode  AND ET.Script_Code in (select value from membercodestable(@scriptcode,','))
                   INNER JOIN mst_member MM 
                           ON MM.member_code = ET.member_code AND ET.Year_code=@yearcode
                   INNER JOIN mst_family MF 
                           ON MF.family_code = MM.family_code 
            WHERE  ET.ex_date BETWEEN @trans_dt_from AND @trans_dt_to OR ET.Bank_Date BETWEEN @trans_dt_from AND @trans_dt_to
                   and ET.Script_Code in (select value from membercodestable(@scriptcode,','))
				   AND ET.Year_code=@yearcode
                   --AND ET.member_code IN (SELECT value FROM   Membercodestable(@membercode, ',' )) 
        order by  CASE 
          WHEN @sortby  = 1 THEN  ( CONVERT(VARCHAR(10), ET.ex_date, 103) )
          WHEN @sortby  = 2 THEN [Script_Name]  
          WHEN @sortby  = 3 THEN [Member_Name] 
          END ASC 
        END 


  --    ELSE IF( @membercode = '' AND @scriptcode != '' ) 
  --      BEGIN 
		--print @scriptcode
  --          SELECT MS.script_name                            AS 'Name of Company', 
  --                 ( CONVERT(VARCHAR(10), ET.ex_date, 103) ) AS 'EX Date', 
  --                 MM.member_name                            AS 'Member Name', 
  --                 ET.percentage                             AS 'Rs', 
  --                 ET.qty                                    AS 'Closing Stock', 
  --                 -- ET.Ex_date,  
  --                 ET.amount                                 AS 'Amount', 
  --                 ET.narration                              AS 'Narration' 
  --          FROM   EQDividend_Trans ET 
  --                 INNER JOIN mst_script MS 
  --            ON ET.script_code = MS.script_code 
  --                 INNER JOIN mst_member MM 
  --                         ON MM.member_code = ET.member_code 
  --                 INNER JOIN mst_family MF 
  --                         ON MF.family_code = MM.family_code 
  --          WHERE  ET.ex_date BETWEEN @trans_dt_from AND @trans_dt_to
  --                 AND ET.script_code IN (SELECT value FROM   Membercodestable(@scriptcode, ','))  
  --                 AND ET.member_code IN ( @membercode) 
  --          ORDER  BY CASE 
  --                      WHEN @sortby = 1 THEN   ( CONVERT(VARCHAR(10), ET.ex_date, 103) )
  --                      WHEN @sortby = 2 THEN [script_name] 
  --                      WHEN @sortby = 3 THEN [member_name] 
  --                    END ASC 
  --      END 
     
      ELSE IF ( @membercode = '' 
           AND @scriptcode = '' ) 
        BEGIN 
            SELECT MS.script_name                            AS 
                   'Name of Company', 
                   ( CONVERT(VARCHAR(10), ET.ex_date, 103) ) AS 'EX Date', 
                   MM.member_name                            AS 'Member Name', 
                   ET.percentage                             AS 'Rs', 
                   ET.qty                                    AS 'Closing Stock', 
                   -- ET.Ex_date, 
                   ET.amount                                 AS 'Amount', 
                   ET.narration                              AS 'Narration', 
				   ET.Bank_Date                              As 'Reco Date'
            FROM   eqdividend_trans ET 
                   INNER JOIN mst_script MS 
                           ON ET.script_code = MS.script_code  AND ET.Year_code=@yearcode 
                   INNER JOIN mst_member MM 
                           ON MM.member_code = ET.member_code AND ET.Year_code=@yearcode
                   INNER JOIN mst_family MF 
                           ON MF.family_code = MM.family_code 
            WHERE   ET.ex_date BETWEEN @trans_dt_from AND @trans_dt_to OR ET.Bank_Date BETWEEN @trans_dt_from AND @trans_dt_to
			AND ET.Year_code=@yearcode
                   -- and ET.Script_Code in (select value from membercodestable(@scriptcode,',')) 
                 --  AND ET.member_code IN ( @membercode ) 
            ORDER  BY CASE 
                        WHEN @sortby = 1 THEN  ( CONVERT(VARCHAR(10), ET.ex_date, 103) )
                        WHEN @sortby = 2 THEN [script_name] 
                        WHEN @sortby = 3 THEN [member_name] 
                      END ASC 
        END 
 
  END 





GO
/****** Object:  StoredProcedure [dbo].[eventpopup]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[eventpopup]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[eventpopup] AS' 
END
GO



ALTER proc [dbo].[eventpopup]
as
begin
declare
@event_count int,
@i int,
@re_cnt varchar(20)
create table #temp
(
SN int,
msg varchar(max),
r_type varchar(20),
date_show datetime
)

insert into #temp
select SrNo, event_msg,repeat_type,date_show from todolist where convert(varchar(10),popup_date,111)=convert(varchar(10),getdate(),111) and flag<>0 

select msg from #temp

set @event_count=(select count(r_type) from #temp)
if(@event_count>0)
begin
set @i=1
while(@i<@event_count)
begin

set @re_cnt=(select r_type from  #temp where SN=@i)
if(@re_cnt='Daily')
begin
update todolist set popup_date=(select dateadd(dd,1,popup_date)) where SrNo=@i
end

else if(@re_cnt='Weekly')
begin
update todolist set popup_date=(select dateadd(dd,7,popup_date)) where SrNo=@i
end

else if(@re_cnt='Monthly')
begin
update todolist set popup_date=(select dateadd(mm,1,popup_date)) where SrNo=@i
end

else if(@re_cnt='Yearly')
begin
update todolist set popup_date=(select dateadd(year,1,popup_date)) where SrNo=@i
end

set @i=@i+1
end
end
end



GO
/****** Object:  StoredProcedure [dbo].[FD_Interest_Calculation]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FD_Interest_Calculation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[FD_Interest_Calculation] AS' 
END
GO

--Select * from Other_Investments

-- Execute FD_Interest_Calculation 'M0002', '', '02/22/2018',''

ALTER PROCEDURE [dbo].[FD_Interest_Calculation]
	 @family varchar(Max),
	 @member varchar(Max),
	 @till_date datetime,
	 @Investment_code varchar(Max)
 
AS
BEGIN
SET NOCOUNT ON;

	DECLARE @TempMemberCode varchar(1000)
	IF(@member = '' AND @family != '')
		BEGIN 
			Select Member_Code 
			INTO #Members 
			FROM Mst_Member Where Family_Code IN (SELECT Value FROM membercodestable(@family,','))
			
			declare @tmp varchar(250)
			SET @tmp = ''
			select @tmp = @tmp + Member_Code + ',' from #Members
			SET @TempMemberCode = 	IsNULL((select SUBSTRING(@tmp, 0, LEN(@tmp))),'')
		END
	ELSE 
			SET @TempMemberCode = 	@member


			--Select @TempMemberCode
DECLARE @SQL  varchar(max) = ''

SET @SQL = 'Select MF.Family_Name as ''Family Name'', 
MM.Member_Name as ''Member Name'', 
MI.Investment_Name as ''Investment Name'',
OI.Trans_Dt as ''Transaction Date'',
OI.Year_Code,OI.Amount,
OI.Interest_Rate as ''Interest Rate'', 
OI.For_Years,OI.For_Days,
OI.For_Months,
OI.Maturity_Date as ''Maturity Date'',
OI.Maturity_Amount,
OI.Int_Receivable,
OI.Int_Recd,
OI.Int_Type ''Interest Type'',
OI.Int_Compound ''Rate Compounded'',
OI.Investment_Code,
OI.sr_no
FROM Other_Investments OI

Inner Join Mst_Member MM On
MM.Member_Code=OI.Member_Code

Inner Join Mst_Investment MI On
MI.Investment_Code=OI.Investment_Code

Inner Join Mst_Family MF On
MF.Family_Code=MM.Family_Code WHERE ' 

SET @SQL = @SQL + ' MM.Member_Code In(SELECT value FROM   Membercodestable('''+ @TempMemberCode +''', '','' ))'

IF(@family <> '')
	BEGIN
		SET @SQL = @SQL + ' AND MF.Family_Code In(SELECT value FROM   Membercodestable('''+ @family +''', '','' ))'
	END

IF(@Investment_code <> '')
	BEGIN
		SET @SQL = @SQL + 'AND OI.Ac_Code IN (SELECT value FROM   Membercodestable('''+ @Investment_code +''', '','' ))'
	END

SET @SQL  =  @SQL + 'Group By MM.Member_Name,OI.Year_Code,OI.Amount,OI.Interest_Rate,OI.For_Days,OI.For_Months,OI.Maturity_Date,OI.Maturity_Amount,
OI.Int_Receivable,OI.Int_Recd,OI.Int_Type,OI.Int_Compound,MI.Investment_Name,MF.Family_Name,OI.Trans_Dt,OI.Investment_Code,OI.sr_no,OI.For_Years'

SET @SQL  =  @SQL +' Order By OI.Trans_Dt '


Print @SQL

Execute (@SQL)
	


END
























GO
/****** Object:  StoredProcedure [dbo].[GetAccountCode]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetAccountCode]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[GetAccountCode] AS' 
END
GO

-- Execute [dbo].[GetAccountCode]  'A0002','1120182019','SAMEER','BROKER',2
ALTER PROCEDURE [dbo].[GetAccountCode] 
	@MemberCode varchar(50),
	@YearCode int,
	@AccountName varchar(max),
	@GroupName varchar(max),
	@GroupID int,
	@AccountCode varchar(50)
AS
BEGIN
SET NOCOUNT ON;
--DECLARE @Accountcode varchar(20)
DECLARE @Effect varchar(2) 
DECLARE @Effect1 varchar(2)
--DECLARE @AccountName varchar(20)

DECLARE @HName varchar(max)
SELECT @HName = hname FROM Mst_AcGroup WHERE GRP_NAME = @GroupName

SELECT @Effect = MAG.EFFECT, @Effect1 = MAG.EFFECT1
FROM Mst_AcGroup MAG
WHERE MAG.GRP_NAME = @HName

if((Select count(*) from MST_Account Where AC_Code = @AccountCode) = 0)
	BEGIN
		
		DECLARE @initial char(1) = ( Select SUBSTRING(@AccountName, 1,1))
		DECLARE @Query  Varchar(max)
		
		
		Create Table #Temp
		(
			MaxNumber int			
		)


		--SET @Query  ='insert into #Temp select max(CAST(substring(Script_Code,2,len(AC_Code)) as int))   FROM MST_Account' 
		SET @Query  ='insert into #Temp select max(CAST(substring(AC_Code,2,len(AC_Code)) as int))   FROM MST_Account' 
		SET @Query  = @Query + ' WHERE Member_Code='''+@MemberCode+''' and  AC_Code like '
		SET @Query  = @Query + ' ''' + @initial + '%'''
	
		Execute (@Query)

		DECLARE @Max int
		
		if((select Top(1) MaxNumber FROM #Temp) IS NULL)
			SET @Max = 1
		ELSE
			SET @Max =  (Select Top(1) ISNULL(MaxNumber,1) + 1 FROM #Temp)

		Set @Accountcode =UPPER(@initial +  Right('0000' + convert(varchar(4),@Max),4))
		
		Insert into  MST_Account(Member_Code,Year_Code,AC_Code,AC_Name,Grp_Name,Grp_id,InternalEntry,Effect, Effect1) 
		values(@MemberCode,@YearCode, @Accountcode,@AccountName,@GroupName,@GroupID,0,@Effect,@Effect1)	
		
		Drop Table #Temp

	END
ELSE
	BEGIN
	
		--SELECT TOP(1) @Accountcode = AC_Code FROM Mst_Account Where AC_Name = @AccountName --and Grp_id = @GroupID
		UPDATE MST_Account
		SET Effect = @Effect,
			Effect1 = @Effect1,
			AC_Name =  @AccountName
		WHERE AC_Code = @Accountcode and Member_Code=@MemberCode and Year_Code=@YearCode

	END


	Select @Accountcode

END


--select * from Mst_Account
--select * from Ent_EntryTypes

--Select * from 

	













GO
/****** Object:  StoredProcedure [dbo].[GetAutoIntraDayMarkingDetail]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetAutoIntraDayMarkingDetail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[GetAutoIntraDayMarkingDetail] AS' 
END
GO


-- Execute [dbo].[GetAutoIntraDayMarkingDetail]

ALTER PROCEDURE [dbo].[GetAutoIntraDayMarkingDetail] 
AS
BEGIN
SET NOCOUNT ON;

	Select * into #TempBuy 
	from TRF_body
	WHERE BS IS NOT NULL AND BS = 'B'
	
	Select * into #TempSELL	
	from TRF_body 
	WHERE BS IS NOT NULL AND BS = 'S'
	
	Select TB.S_Desc,Tb.Qnty into #TempIntraday	
	FROM #TempBuy TB JOIN #TempSELL TS 	ON TB.S_Desc = TS.S_Desc AND ABS(TB.Qnty) = ABS(TS.Qnty)
	
	--Select * from #TempBuy
	--Select * from #TempSell
	--Select * from #TempIntraday
	
	Select TRB.OrderNo as 'Order Number',TRB.TardeNo as 'Trade Number',TRB.S_Desc as 'Script Name', TRB.BS as 'BuySell', 
			TRB.Qnty as 'Qty',TRB.GrossRate as 'Gross Rate',TRB.BrokRate as 'Brok Rate',TRB.NetRate as 'Net Rate',TRB.NetTotal as 'Net Total'
	from TRF_body TRB JOIN  #TempIntraday TI	ON TRB.S_Desc = TI.S_Desc AND ABS(TRB.Qnty) = ABS(TI.Qnty)
	ORDER by TRB.S_Desc,TI.S_Desc, ABS(TRB.Qnty) desc,ABS(TI.Qnty) desc
	
	Drop Table #TempBuy
	Drop Table #TempSELL
	Drop Table #TempIntraday

	Truncate Table Auto_Expense

	Select * from  Auto_Expense

END






GO
/****** Object:  StoredProcedure [dbo].[GetBrokerage_Rate]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetBrokerage_Rate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[GetBrokerage_Rate] AS' 
END
GO


ALTER procedure [dbo].[GetBrokerage_Rate]
(
 @Membercode Varchar(20),
 @Yearcode Varchar(20),
 @Brokercode Varchar(20)
)
As
 BEGIN
 SET NOCOUNT ON;
	 --SELECT 
		-- ISNULL(EQB_Brokerage,0) as 'EQB_Brokerage', 
		-- ISNULL(EQS_Brokerage,0) as 'EQS_Brokerage', 
		-- ISNULL(eqintradaybuy,0) as 'eqintradaybuy', 
		-- ISNULL(eqintradaysell,0) as 'eqintradaysell', 
		-- ISNULL(FOB_Brokerage,0) as 'FOB_Brokerage', 
		-- ISNULL(FOS_Brokerage,0) as 'FOS_Brokerage', 
		-- ISNULL(MCXB,0) as 'MCXB', 
		-- ISNULL(MCXS,0) as 'MCXS', 
		-- ISNULL(MFB,0) as 'MFB', 
		-- ISNULL(MFS,0) as 'MFS', 
		-- ISNULL(CURB_Brokerage,0) as 'CURB_Brokerage', 
		-- ISNULL(CURS_Brokerage,0) as 'CURS_Brokerage', 
		-- ISNULL(NCDEXB_Brokerage,0) as 'NCDEXB_Brokerage',  
		-- ISNULL(NCDEXS_Brokerage,0)  as 'NCDEXS_Brokerage'
	SELECT	 [AC_code]
			,[Investment_Type]
			,ISNULL([Buy_Brokrage],0) as 'Buy_Brokrage'
			,ISNULL([Sell_Brokerage],0) as 'Sell_Brokerage'
			,[Per_Order]
			,ISNULL([Max_Brokrage],0) as 'Max_Brokrage'
			,ISNULL([Min_Brokrge],0) as 'Min_Brokrge'
			,[Member_Code]
			,[Year_Code]
	FROM [dbo].[Brokerage_Master]
 	WHERE Year_Code = @Yearcode and AC_Code = @Brokercode 
	
	--Member_Code=@Membercode and 

 ENd
  --Select * from Mst_Account
  --Select * from  Brokerage_Master
  --Select * from Ent_EntryTypes





















GO
/****** Object:  StoredProcedure [dbo].[GetExpense_Rate]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetExpense_Rate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[GetExpense_Rate] AS' 
END
GO

ALTER procedure [dbo].[GetExpense_Rate]
(
 @Brokercode Varchar(20)
)
As
 BEGIN	
 SET NOCOUNT ON;
	SELECT [id]
      ,[Expense_code] as 'Expense_code'
      ,[Broker_Code]as 'Broker_Code'
      ,IsNULL([Equity_D_buy],0) as 'Equity_D_buy' 
      ,IsNULL([Equity_D_Sale],0)as 'Equity_D_Sale'
      ,IsNULL([Equity_I_buy],0) as 'Equity_I_buy'
      ,IsNULL([Equity_I_Sale],0) as 'Equity_I_Sale'
      ,IsNULL([FO_FU_buy],0) as 'FO_FU_buy'
      ,IsNULL([FO_FU_Sale],0) as 'FO_FU_Sale'
      ,IsNULL([FO_OP_buy],0) as 'FO_OP_buy'
      ,IsNULL([FO_OP_Sale],0) as 'FO_OP_Sale'
      ,IsNULL([Mcx_FU_buy],0) as 'Mcx_FU_buy'
      ,IsNULL([Mcx_FU_Sale],0) as 'Mcx_FU_Sale'
      ,IsNULL([Mcx_OP_buy],0) as 'Mcx_OP_buy'
      ,IsNULL([Mcx_OP_Sale],0) as 'Mcx_OP_Sale'
      ,IsNULL([NCDEX_FU_buy],0) as 'NCDEX_FU_buy'
      ,IsNULL([NCDEX_FU_Sale],0) as 'NCDEX_FU_Sale'
      ,IsNULL([NCDEX_OP_buy],0) as 'NCDEX_OP_buy'
      ,IsNULL([NCDEX_OP_Sale],0) as 'NCDEX_OP_Sale'
      ,IsNULL([Curr_FU_buy],0) as 'Curr_FU_buy'
      ,IsNULL([Curr_FU_Sale],0) as 'Curr_FU_Sale'
      ,IsNULL([Curr_OP_buy],0) as 'Curr_OP_buy'
      ,IsNULL([Curr_OP_Sale],0) as 'Curr_OP_Sale'
  FROM [dbo].[Auto_Expense]
 	WHERE   Broker_code = @Brokercode 

 ENd
  --Select * from Mst_Account
  --Select * from  Brokerage_Master
  --Select * from Ent_EntryTypes





















GO
/****** Object:  StoredProcedure [dbo].[GetIndustryCode]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetIndustryCode]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[GetIndustryCode] AS' 
END
GO

-- Execute GetIndustryCode 'z00546'
-- Select * from mst_industry
ALTER PROCEDURE [dbo].[GetIndustryCode] 
	@Industry varchar(max)
AS
BEGIN
SET NOCOUNT ON;
if((Select count(*) from Mst_Industry Where Industry_Name = @Industry) = 0)
	BEGIN
		DECLARE @IndustryCode varchar(5)
		DECLARE @initial char(1) = ( Select SUBSTRING(@Industry, 1,1))
		DECLARE @Query  Varchar(500)
		
		Create Table #Temp
		(
			MaxNumber int			
		)


		SET @Query  = 	'insert into #Temp select max(CAST(substring(Industry_Code,2,len(Industry_code)) as int)) FROM Mst_Industry' 
		SET @Query  = @Query + ' WHERE Industry_code like '
		SET @Query  = @Query + ' ''' + @initial + '%'''
		
	
		Execute (@Query)
		
		DECLARE @Max int =  (Select Top(1) ISNULL(MaxNumber,1) + 1 FROM #Temp)

		
		Set @IndustryCode = Upper(@initial +  RIGHT('0000' + CONVERT(VARCHAR(4), @Max), 4))
		
	

		Insert into  Mst_Industry values(@IndustryCode,@Industry)
		Drop Table #Temp

	END
ELSE
	BEGIN
		SET @IndustryCode = (SELECT TOP(1) Industry_Code FROM Mst_Industry Where Industry_Name = @Industry) 
	END


	Select @IndustryCode

END
















GO
/****** Object:  StoredProcedure [dbo].[GetScriptCode]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetScriptCode]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[GetScriptCode] AS' 
END
GO
-- Execute GetScriptCode 'ABB INDIA LIMITED',0,'test'
-- Select * from mst_script
-- Delete from mst_script
ALTER PROCEDURE [dbo].[GetScriptCode] 
	@scriptname varchar(max),
	@investmentType int,
	@Industry varchar(max)
AS
BEGIN
SET NOCOUNT ON;

	--Create Table #TempIndustry
	--(
	--		Industry_code varchar(5)			
	--)

 --INSERT INTO #TempIndustry 
 --Execute GetIndustryCode @Industry


if((Select count(*) from Mst_Script Where Script_Name = @scriptname) = 0)
	BEGIN
		DECLARE @Scriptcode varchar(5)
		DECLARE @initial char(1) = ( Select SUBSTRING(@scriptname, 1,1))
		DECLARE @Query  Varchar(500)
		
		Create Table #Temp
		(
			MaxNumber int			
		)
		SET @Query  ='insert into #Temp select max(CAST(substring(Script_Code,2,len(Script_Code)) as int))   FROM Mst_Script' 
		SET @Query  = @Query + ' WHERE Script_Code like '
		SET @Query  = @Query + ' ''' + @initial + '%'''
	
		Execute (@Query)

		

		DECLARE @Max int
		
		if((select Top(1) MaxNumber FROM #Temp) IS NULL)
			SET @Max = 1
		ELSE
			SET @Max =  (Select Top(1) ISNULL(MaxNumber,1) + 1 FROM #Temp)

		Set @Scriptcode =UPPER(@initial +  Right('0000' + convert(varchar(4),@Max),4))

		Select @Max
		
		Insert into  Mst_Script (Script_Code,Script_Name,Short_Name,ismcx,iscurrency,InvestmentType,Industry_Code) 
		values(@Scriptcode,@scriptname,@scriptname, case When @investmentType = 3 Then 1 ELSE 0 END,case When @investmentType = 4 Then 1 ELSE 0 END, @investmentType, @Industry)	
		
		Drop Table #Temp

	END
ELSE
	BEGIN
		SET @Scriptcode = (SELECT TOP(1) Script_Code FROM Mst_Script Where Script_Name = @scriptname) 
		
		--IF((Select Count(*) from #TempIndustry) > 0)
		--	BEGIN
		--		UPDATE Mst_Script
		--		SET Industry_Code  = (Select Top 1 Industry_code from #TempIndustry)
		--		WHERE Script_Code = @Scriptcode
		--	END

		
	END


	Select @Scriptcode

END


--select * from Mst_Script
--select * from Ent_EntryTypes

--Select * from 

	















GO
/****** Object:  StoredProcedure [dbo].[GetTransactionNo]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetTransactionNo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[GetTransactionNo] AS' 
END
GO
ALTER PROCEDURE [dbo].[GetTransactionNo]
@MemberCode VARCHAR (20),
@YearCode VARCHAR (10) ,
@scriptcode VARCHAR (10) ,
@brokercode VARCHAR (10),
@IsFnoBill int 
AS
 BEGIN
 SET NOCOUNT ON;
	DECLARE @TransNumber int  = 0
	
	SELECT @TransNumber = BBT.Trans_No FROM BrokerBill_Trans BBT
	INNER JOIN BrokerBill BB ON BB.Trans_no = BBT.Trans_no 
	WHERE BBT.Member_code = @MemberCode 
		  AND BBT.YearCode = @YearCode 
		  AND BB.Broker_Code  = @brokercode 
		  AND BB.Bill_no   = 'Opening' 
		  AND BBT.isFNOBill = @IsFnoBill

	
	DELETE BBT FROM BrokerBill_Trans BBT
	WHERE BBT.Trans_No = @TransNumber AND BBT.Script_Code = @ScriptCode

	IF(@TransNumber = 0 OR @TransNumber  IS NULl)
		BEGIN
			SET @TransNumber = (SELECT MAX(Trans_No) + 1 FROM BrokerBill_Trans)
		END

	Select @TransNumber
 END











GO
/****** Object:  StoredProcedure [dbo].[GetUserMenu]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetUserMenu]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[GetUserMenu] AS' 
END
GO


--Execute [dbo].[GetUserMenu] 'sameer',1

ALTER Procedure [dbo].[GetUserMenu]
 @userName Varchar(Max),
 @IsAllData bit=0
AS
BEGIN
SET NOCOUNT ON;
 if(@IsAllData=0)
	BEGIN
		if(@userName = 'Admin')
		BEGIN
			 Select * from MenuMaster Where isActive = 1 Order By MenuOrder
			  SELECT * from User_Authorization 
		End
		ELSE
			BEGIN
				 Select M.* from MenuMaster M 
				 Inner Join User_Authorization UA On UA.Menuid = M.MenuID --and UA.ParentMenuID = M.MenuID
				 Where IsActive = 1  AND UA.UserName = @userName
				
				 UNION

				 Select * 
				 from MenuMaster 
				 Where IsActive = 1  AND MenuID IN (Select ParentMenuID from User_Authorization WHERE UserName = @userName)

				 UNION

				 Select * 
				 from MenuMaster 
				 Where IsActive = 1  AND MainMenuID IN (Select MenuID from User_Authorization WHERE ParentMenuID = 0 and UserName = @userName)
				 --UNION

				 --Select * 
				 --from MenuMaster 
				 --Where IsActive = 1  AND MenuID IN (Select ParentMenuID from User_Authorization WHERE UserName = @userName)
				 Order By MainMenuID

				 SELECT * from User_Authorization Where UserName = @userName

			END
	END
ELSE
	BEGIN
		
		SELECT *
		FROM   MenuMaster 
		WHERE  IsActive = 1
		ORDER BY MenuID

		 SELECT * from User_Authorization Where UserName = @userName
	END
END
























GO
/****** Object:  StoredProcedure [dbo].[Groupmaster_Insert]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Groupmaster_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Groupmaster_Insert] AS' 
END
GO
-- Execute MasterReport_Groupmaster_Insert 'Test 200', 'CAPITAL'

ALTER Procedure [dbo].[Groupmaster_Insert]
	@GroupName varchar(Max),
	@ParentGroupName varchar(Max),
	@GroupID varchar(50)
As
Begin
SET NOCOUNT ON;

Declare @ParentHname varchar(500)
Declare @effect varchar(2)
Declare @effect1 varchar(2)
Declare @order1 int 

Select  @ParentHname = hname From Mst_AcGroup Where GRP_NAME = @ParentGroupName
Select @effect = EFFECT, @effect1 = EFFECT1 from Hgroup Where HNAME = @ParentHname 

if((select count(*) from Mst_AcGroup Where Grp_Id = @GroupID) = 0)  
	BEGIN
		Select @order1 = Max(ORDER1) From Mst_AcGroup
		insert into Mst_AcGroup(Grp_Name, Hname, Effect, Effect1,ORDER1, Display_Under, IsSubEntry, isInternalEntry,SCH,Exported) 
		values(@GroupName,@ParentGroupName,@effect,@effect1, @order1,'0','1','0','','N')
	
	end
ELSE 
	BEGIN
		Update Mst_AcGroup
		SET Grp_Name = @GroupName,
			Effect = @effect,
			Effect1 = @effect1
		Where Grp_Id = @GroupID 
	END
END
















GO
/****** Object:  StoredProcedure [dbo].[Insert_UnMatchAccount_Master]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Insert_UnMatchAccount_Master]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Insert_UnMatchAccount_Master] AS' 
END
GO



--Execute ReTransfer_Account_Master '1220172018','1120182019','T0009','04/01/2017','03/31/2018'

ALTER  Procedure [dbo].[Insert_UnMatchAccount_Master]
(
	@PreviousYearcode varchar(10),
	@NextYearcode varchar(10),
	@Membercode varchar(10),
	@Account_Name varchar(max),
	@Group_Name varchar(max),
	@Amount float
)
AS
 BEGIN
	
		INSERT INTO [dbo].[Mst_Account]
           ([Member_Code],
           [Year_Code],
           [AC_Code],
           [AC_Name],
           [Grp_Name],
           [Grp_id],
           [Effect],
           [Effect1],
           [Op_Bal],
           [Op_Cal],
           [InternalEntry],
           [Contact_Person],
           [Add1],
           [Add2],
           [Add3],
           [Mobile_No],
           [Tel_No],
           [Fax_No],
           [email],
           [website],
           [Pan_No],
           [UCC_Code],
           [DecimalPlaces],
           [DefaultAcInBrokerBill],
           [IsBrokeragePerUnit],
           [EQB_Brokerage],
           [EQS_Brokerage],
           [FOB_Brokerage],
           [FOS_Brokerage],
           [IDB_Brokerage],
           [IDS_Brokerage],
           [Investment_Code],
           [CURB_Brokerage],
           [CURS_Brokerage],
           [MCXB],
           [MCXS],
           [MFB],
           [MFS],
           [eqintradaybuy],
           [eqintradaysell],
           [NCDEXB_Brokerage],
           [NCDEXS_Brokerage])
     
	 SELECT	  @Membercode,
		  @NextYearcode,
		  [AC_Code],
		  [AC_Name],
		  [Grp_Name],
		  [Grp_id],
		  [Effect],
		  [Effect1],
		  ABS(@Amount),
		  CASE
			WHEN @Amount > 0 THen 1 WHEN @Amount < 0 Then -1 Else 0
		  END,	  
		  [InternalEntry],
		  [Contact_Person],
		  [Add1],
		  [Add2],
		  [Add3],
		  [Mobile_No],
		  [Tel_No],
		  [Fax_No],
		  [email],
		  [website],
		  [Pan_No],
		  [UCC_Code],
		  [DecimalPlaces],
		  [DefaultAcInBrokerBill],
		  [IsBrokeragePerUnit],
		  [EQB_Brokerage],
		  [EQS_Brokerage],
		  [FOB_Brokerage],
		  [FOS_Brokerage],
		  [IDB_Brokerage],
		  [IDS_Brokerage],
		  [Investment_Code],
		  [CURB_Brokerage],
		  [CURS_Brokerage],
		  [MCXB],
		  [MCXS],
		  [MFB],
		  [MFS],
		  [eqintradaybuy],
		  [eqintradaysell],
		  [NCDEXB_Brokerage],
		  [NCDEXS_Brokerage]
  FROM [dbo].[Mst_Account]
  Where Member_Code = @Membercode and Year_Code = @PreviousYearcode and AC_Name = @Account_Name AND Grp_Name = @Group_Name
END


GO
/****** Object:  StoredProcedure [dbo].[IPO_Report]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[IPO_Report]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[IPO_Report] AS' 
END
GO



-- exec IPO_Report '','D0001','1120172018','04/01/2017','03/31/2018','','','Pending',''

ALTER PROCEDURE [dbo].[IPO_Report]                       
 (
@Familycode    VARCHAR(max), 
@Membercode     VARCHAR(max), 
@Yearcode       VARCHAR(500), 
@FromDate       VARCHAR(50), 
@ToDate         VARCHAR(50), 
@Consultantcode    VARCHAR(max), 
@Scriptcode     VARCHAR(max),
@DisplayAll     VARCHAR(max),
@WithAllotment    bit=1
)

AS
BEGIN
SET NOCOUNT ON;

 DECLARE @sqlstr AS NVARCHAR(max) 

 CREATE TABLE #temp
 (
    [Application_No] varchar(50),[Date] varchar(50),[Family_Code] varchar(50), [Family_Name] varchar(50),[Member_Code] varchar(50), 
	[Member_Name] varchar(50),[Consultant_Code] varchar(50),Consultant_name varchar(50),[Script_code]  varchar(50), [Application_Qty] Varchar(Max),
	[Application_Rate]  Varchar(100),[Applciation_Amount]  Varchar(100),[Alloted_Qty]  Varchar(100),[Alloted_Rate]  Varchar(100),[Alloted_Amount]  Varchar(Max),
	[Refund_Amount]  Varchar(100),[Script_Name]  Varchar(Max),[Refund_Qty]  Varchar(Max),[Refund_Rate]  Varchar(Max)
)

 SET @sqlstr='Select Ip.Application_no As Application_No '
 SET @sqlstr=@sqlstr +',Ip.Trans_Dt as Date'
 SET @sqlstr=@sqlstr +',MF.Family_Code as Family_Code'
 SET @sqlstr=@sqlstr +',Mf.Family_Name as Family_Name'
 SET @sqlstr=@sqlstr +',Ip.Member_Code as Member_Code'
 SET @sqlstr=@sqlstr +',MM.Member_Name as Member_Name'
 SET @sqlstr=@sqlstr +',Ip.Consultant_Code as Consultant_Code'
 SET @sqlstr=@sqlstr +',Mc.Consultant_name'
 SET @sqlstr=@sqlstr +',Ip.Script_code As Script_code'
 SET @sqlstr=@sqlstr +',Ip.Qty as Application_Qty'
 SET @sqlstr=@sqlstr +',IP.Rate As Application_Rate'
 SET @sqlstr=@sqlstr +',IP.Amount As Applciation_Amount'
 SET @sqlstr=@sqlstr +',Ip.Alloted_Qty as Alloted_Qty'
 SET @sqlstr=@sqlstr +',IP.Alloted_Rate As Alloted_Rate'
 SET @sqlstr=@sqlstr +',IP.Alloted_Amount As Alloted_Amount'
 SET @sqlstr=@sqlstr +',Ip.Refund_Amount As Refund_Amount'
 SET @sqlstr=@sqlstr +',Ms.Script_Name as Script_Name'
 SET @sqlstr=@sqlstr +',IP.Refund_Qty as Refund_Qty'
 SET @sqlstr=@sqlstr +',IP.Refund_Rate as Refund_Rate '

 SET @sqlstr = @sqlstr + ' into #temp from IPO Ip '

 SET @sqlstr = @sqlstr + ' Inner JOIN  Mst_Member MM On MM.Member_code=IP.Member_Code ' 
 SET @sqlstr = @sqlstr + ' Inner Join Mst_Family MF on MF.Family_Code=Mm.Family_Code ' 
 SET @sqlstr = @sqlstr + ' Inner join Mst_Consultant MC On Mc.Consultant_Code=Ip.Consultant_Code '
 SET @sqlstr = @sqlstr + ' Inner join Mst_Script MS On MS.Script_Code=Ip.Script_Code '
 SET @sqlstr = @sqlstr + ' where Ip.Member_Code in (SELECT Value FROM membercodestable(' + Char(39) + @Membercode + Char(39) + ',' + Char(39) + ',' + Char(39) + ')) ' 
 SET @sqlstr = @sqlstr + ' and Ip.Year_Code = ' + @Yearcode 

   IF (@Scriptcode <> '' ) 
				BEGIN 
				  SET @sqlstr = @sqlstr + ' and Ip.Script_code in (SELECT Value FROM membercodestable(' + Char(39) + @Scriptcode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
				END 
   IF (@Familycode <> '' ) 
				BEGIN
					SET @sqlstr = @sqlstr + ' and MF.Family_Code in (SELECT Value FROM membercodestable(' + Char(39) + @Familycode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
				END
   IF (@Consultantcode <> '')
				BEGIN
				   SET @sqlstr =@sqlstr + ' and Ip.Consultant_Code in(SELECT Value FROM membercodestable(' + Char(39) + @Consultantcode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  '
				END
   IF (@Membercode <> '')
				BEGIN
				   SET @sqlstr =@sqlstr + ' and Ip.Member_Code in(SELECT Value FROM membercodestable(' + Char(39) + @Membercode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  '
				END
	IF(@DisplayAll='Pending')	
	           BEGIN
			   SET @sqlstr=@sqlstr + ' and IP.Alloted_Qty = 0 '
			   END
       ELSE IF(@DisplayAll='Alloted')
	      BEGIN
		   SET @sqlstr=@sqlstr + ' and IP.Alloted_Qty != 0 '
		  END

 SET @sqlstr = @sqlstr + 'Select * from #temp' 

 SET @sqlstr = @sqlstr + ' Drop  Table #temp '  

 PRINT @sqlstr 
 EXECUTE (@sqlstr) 
 END


	--Select Ip.Application_no As 'Application No',Ip.Trans_Dt as'Date',MF.Family_Code as 'Family Code',
	--Mf.Family_Name as 'Family Name', Ip.Member_Code as'Member Code',
	--MM.Member_Name as'Member Name',Ip.Consultant_Code as 'Consultant Code', Mc.Consultant_name,
	--Ip.Script_code As'Script code', 
	--Ip.Qty as'Application Qty',IP.Rate As 'Application Rate',IP.Amount As'Applciation Amount',
	--Ip.Alloted_Qty as'Alloted Qty',IP.Alloted_Rate As 'Alloted Rate',IP.Alloted_Amount As'Alloted Amount',
	--Ip.Refund_Amount As'Refund Amount',
	--Ms.Script_Name as'Script Name',
	--IP.Refund_Qty as'Refund Qty',
	--IP.Refund_Rate as 'Refund_Rate'

	--from IPO Ip
	--Inner JOIN  Mst_Member MM On MM.Member_code=IP.Member_Code
	--Inner Join Mst_Family MF on MF.Family_Code=Mm.Family_Code
	--Inner join Mst_Consultant MC On Mc.Consultant_Code=Ip.Consultant_Code
	--Inner join Mst_Script MS On MS.Script_Code=Ip.Script_Code
	--where Ip.Member_Code IN (SELECT Value FROM membercodestable(@Membercode,','))  
	--and Ip.Year_Code=@Yearcode
	--END









GO
/****** Object:  StoredProcedure [dbo].[MasterReport]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[MasterReport] AS' 
END
GO
ALTER  Procedure [dbo].[MasterReport]
(
@Status Int,
@yearcode varchar(500)=Null
)
As
   --------for Family Master----------
Begin
SET NOCOUNT ON;
If(@Status=0)

Select Mst_Family.Family_Name As [Family Name],Mst_Family.Family_Code As [Family Code],
Mst_Member.Member_Name As[Member Name],Mst_Member.Member_Code As [Member Code] from Mst_Family

join Mst_Member
on
Mst_Family.Family_Code=Mst_Member.Family_Code;
End


--------for Member Master----------
 
 If(@Status=1)

Begin
Select Mst_Member.Member_Name As [Member Name],Mst_Member.Member_Code As [Member Code],
Mst_Member.PanNo As [Pan No],Mst_Member.ServTax_No As [Service Tax No],
Mst_Member.Gender As [Gender]
from Mst_Member;
End

--------for Consultant Master----------
Else if(@Status=2)

Begin

Select Mst_Consultant.Consultant_Name As [Consultant Name],
Mst_Consultant.Consultant_Code As [Consultant Code] from Mst_Consultant;

end

--------for Industry Master----------
 Else iF (@Status=3)

Begin

Select distinct (Mst_Industry.Industry_Name) As [Industry Name],
Mst_Industry.Industry_Code As [Industry Code],Mst_Script.Script_Name As [Script Name],
Mst_Script.Script_Code As [Script Code] from Mst_Industry

join Mst_Script
on
Mst_Industry.Industry_Code=Mst_Script.Industry_Code;
End

--------for Script Master----------

Else If(@Status=4)

Begin
Select Mst_Script.Script_Name As [Script Name],Mst_Script.Script_Code As [Script Code],
Mst_Script.BSE_Code As [BSE Code],Mst_Script.NSE_Code As [NSE Code],
Mst_Script.Script_Group AS [Group],Mst_Script.ISIN_No As [ISIN No],
Mst_Industry.Industry_Name As [Industry Name] from Mst_Script

Join Mst_Industry
on
Mst_Script.Industry_Code=Mst_Industry.Industry_Code;
End

--------for Narration Master----------

 Else if(@Status=5)

Begin
Select Mst_Narration.Narration_Name As [Narration Name],Mst_Narration.Narration_Code As [Narration Code] from Mst_Narration;

End

--------for Investment Master ----------

Else If(@Status=6)

Begin
Select Mst_Investment.Investment_Name As[Investment Name],Mst_Investment.Investment_Code AS [Investment Code],
Mst_Member.Member_Name As [Member Name],Mst_Investment.InternalEntry As [Entry Type] from Mst_Investment
Join Mst_Member
On
Mst_Investment.Member_Code=Mst_Member.Member_Code;
End


--------for Group Master----------

Else If(@Status=7)

Begin
Select Mst_AcGroup.GRP_NAME,Mst_AcGroup.hname,Mst_AcGroup.isInternalEntry from Mst_AcGroup;
End



--------for Demat Master----------

 Else If(@Status=8)

Begin
Select Mst_Demat.DP_Name,Mst_Demat.DP_Code from Mst_Demat
where  Year_Code=@yearcode;
End


--------for Mutul Fund Family Master----------

 Else If(@Status=9 and @yearcode='')

Begin 
Select Mst_MF_Family.MFF_Name,Mst_MF_Family.MFF_Code from Mst_MF_Family

End



































GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Consultantmaster]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Consultantmaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[MasterReport_Consultantmaster] AS' 
END
GO
ALTER  Procedure [dbo].[MasterReport_Consultantmaster]

As


Begin
SET NOCOUNT ON;
Select Mst_Consultant.Consultant_Name As [Consultant_Name],
Mst_Consultant.Consultant_Code As [Consultant_Code] from Mst_Consultant;

end



























GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Dematmaster]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Dematmaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[MasterReport_Dematmaster] AS' 
END
GO
ALTER  Procedure [dbo].[MasterReport_Dematmaster]
(
@yearcode varchar(10),
@memcode varchar(10)

)
As


Begin
SET NOCOUNT ON;
Select Mst_Demat.DP_Name,Mst_Demat.DP_Code from Mst_Demat
where (Member_Code='' or Member_Code=@memcode) and (Year_Code=@yearcode or Year_Code='') ;

end



























GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Familymaster]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Familymaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[MasterReport_Familymaster] AS' 
END
GO
ALTER  Procedure [dbo].[MasterReport_Familymaster]
(
@Status Int
)
As
   --------for Family Master----------
Begin
SET NOCOUNT ON;
If(@Status=0)

Select Mst_Family.Family_Name,Mst_Family.Family_Code As [Family_Code],
Mst_Member.Member_Name As[Member_Name],Mst_Member.Member_Code As [Member_Code] from Mst_Family

join Mst_Member
on
Mst_Family.Family_Code=Mst_Member.Family_Code;



else If(@Status=1)

Select Mst_Family.Family_Name As [Family_Name],Mst_Family.Family_Code As [Family_Code] from Mst_Family

join Mst_Member
on
Mst_Family.Family_Code=Mst_Member.Family_Code;
End



























GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Groupmaster]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Groupmaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[MasterReport_Groupmaster] AS' 
END
GO
ALTER  Procedure [dbo].[MasterReport_Groupmaster]

As


Begin
SET NOCOUNT ON;
Select Mst_AcGroup.GRP_NAME,Mst_AcGroup.hname from Mst_AcGroup;
end



























GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Groupmaster_Insert]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Groupmaster_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[MasterReport_Groupmaster_Insert] AS' 
END
GO
-- Execute MasterReport_Groupmaster_Insert 'Test 200', 'CAPITAL'

ALTER Procedure [dbo].[MasterReport_Groupmaster_Insert]
	@GroupName varchar(500),
	@ParentGroupName varchar(500)
As
Begin
SET NOCOUNT ON;
Declare @ParentHname varchar(500)
Declare @effect varchar(2)
Declare @effect1 varchar(2)
Declare @order1 int 

Select  @ParentHname = hname From Mst_AcGroup Where GRP_NAME = @ParentGroupName
Select @effect = EFFECT, @effect1 = EFFECT1 from Hgroup Where HNAME = @ParentHname 

if((select count(*) from Mst_AcGroup Where GRP_NAME = @GroupName) = 0)  
	BEGIN
		Select @order1 = Max(ORDER1) From Mst_AcGroup
		insert into Mst_AcGroup(Grp_Name, Hname, Effect, Effect1,ORDER1, Display_Under, IsSubEntry, isInternalEntry,SCH,Exported) 
		values(@GroupName,@ParentGroupName,@effect,@effect1, @order1,'0','1','0','','N')
	
	end
ELSE 
	BEGIN
		Update Mst_AcGroup
		SET hname = @ParentGroupName,
			Effect = @effect,
			Effect1 = @effect1
		Where GRP_NAME = @GroupName 
	END
END
















GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Industrymaster]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Industrymaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[MasterReport_Industrymaster] AS' 
END
GO
ALTER  Procedure [dbo].[MasterReport_Industrymaster]

As


Begin
SET NOCOUNT ON;
Select distinct (Mst_Industry.Industry_Name) As [Industry_Name],
Mst_Industry.Industry_Code As [Industry_Code],Mst_Script.Script_Name As [Script_Name],
Mst_Script.Script_Code As [Script_Code] from Mst_Industry

join Mst_Script
on
Mst_Industry.Industry_Code=Mst_Script.Industry_Code;

end



























GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Investmentnmaster]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Investmentnmaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[MasterReport_Investmentnmaster] AS' 
END
GO
ALTER  Procedure [dbo].[MasterReport_Investmentnmaster]

As


Begin
SET NOCOUNT ON;
Select Mst_Investment.Investment_Name As[Investment_Name],Mst_Investment.Investment_Code AS [Investment_Code],
Mst_Member.Member_Name As [Member_Name] from Mst_Investment
Join Mst_Member
On
Mst_Investment.Member_Code=Mst_Member.Member_Code;

end



























GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Mastersnew]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Mastersnew]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[MasterReport_Mastersnew] AS' 
END
GO
ALTER  Procedure [dbo].[MasterReport_Mastersnew]
(
@tablename varchar(100),
@stats int
)
As
   
Begin
SET NOCOUNT ON;
if(@stats=4)/*script master*/
	begin
	EXEC('SELECT Script_Name,Script_Code,BSE_Code,NSE_Code,Script_Group,ISIN_No,Industry_Name FROM ' + @tablename+' left join Mst_Industry on Mst_Script.Industry_Code=Mst_Industry.Industry_Code')
	end
else if(@stats=3)/*industry master*/
	begin
	EXEC('SELECT Industry_Name,Mst_Industry.Industry_Code,Script_Name,Script_Code FROM ' + @tablename+' left join Mst_Script on Mst_Script.Industry_Code=Mst_Industry.Industry_Code')
	end

else
	begin
	EXEC('SELECT * FROM ' + @tablename)
	end
End



























GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Membermaster]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Membermaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[MasterReport_Membermaster] AS' 
END
GO
ALTER  Procedure [dbo].[MasterReport_Membermaster]

As
Begin
SET NOCOUNT ON;

Select Mst_Member.Member_Code As [Member_Code],Mst_Member.Member_Name As [Member_Name],Mst_Member.Add1 As [Address],
Mst_Member.PanNo As [Pan_No],Mst_Member.ServTax_No As [Service_Tax_No],
Mst_Member.Gender As [Gender]
from Mst_Member;
End



























GO
/****** Object:  StoredProcedure [dbo].[MasterReport_MFFamilymaster]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_MFFamilymaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[MasterReport_MFFamilymaster] AS' 
END
GO
ALTER  Procedure [dbo].[MasterReport_MFFamilymaster]
As


Begin
SET NOCOUNT ON;
Select Mst_MF_Family.MFF_Name,Mst_MF_Family.MFF_Code from Mst_MF_Family

end



























GO
/****** Object:  StoredProcedure [dbo].[MasterReport_narrationmaster]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_narrationmaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[MasterReport_narrationmaster] AS' 
END
GO
ALTER  Procedure [dbo].[MasterReport_narrationmaster]

As


Begin
SET NOCOUNT ON;
Select Mst_Narration.Narration_Name As [Narration_Name],Mst_Narration.Narration_Code As [Narration_Code] from Mst_Narration;
end



























GO
/****** Object:  StoredProcedure [dbo].[MasterReport_Scriptmaster]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterReport_Scriptmaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[MasterReport_Scriptmaster] AS' 
END
GO
ALTER  Procedure [dbo].[MasterReport_Scriptmaster]

As


Begin
SET NOCOUNT ON;
Select Mst_Script.Script_Name As [Script_Name],Mst_Script.Script_Code As [Script_Code],
Mst_Script.BSE_Code As [BSE_Code],Mst_Script.NSE_Code As [NSE_Code],
Mst_Script.Script_Group AS [Group],Mst_Script.ISIN_No As [ISIN_No],
Mst_Industry.Industry_Name As [Industry_Name] from Mst_Script

Join Mst_Industry
on
Mst_Script.Industry_Code=Mst_Industry.Industry_Code;
end



























GO
/****** Object:  StoredProcedure [dbo].[Match_Bank_Statement]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Match_Bank_Statement]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Match_Bank_Statement] AS' 
END
GO
ALTER Procedure [dbo].[Match_Bank_Statement]
(
      @ID int,
	 @YearCode varchar(15),
	 @MemberCode varchar(50),
     @BankCode varchar(1000),	
	 @AccountName varchar(1000),
	 @AccountCode varchar(100)
)
As
BEGIN
SET NOCOUNT ON;
	IF(@ID != 0)
		BEGIN
			Update UploadBank_Account_Master
			SET Ac_code = @AccountCode,
				Bank_Ac_Name = @AccountName
			where ID = @ID
		END
	ELSE
		BEGIN
			Insert INTO UploadBank_Account_Master ([Member_code],Bank_code,[year_code],Ac_code,Bank_Ac_Name)
			Values(@MemberCode,@BankCode,@YearCode,@AccountCode,@AccountName)

			SET @ID  = scope_identity() 
		END

	Select @ID
End























GO
/****** Object:  StoredProcedure [dbo].[Merger_Openning_Report]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Merger_Openning_Report]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Merger_Openning_Report] AS' 
END
GO



-- Execute Merger_Openning_Report 'E0152',1100014,'04/01/2018','03/31/2019','R0001','1120182019',0

-- Select * from BrokerBill_Trans Where Script_Code = 'S0009' 
ALTER PROCEDURE [dbo].[Merger_Openning_Report] (@ScriptCode VARCHAR(Max), 
                                                @AcType     VARCHAR(500), 
                                                @FromDate   DATETIME, 
                                                @ToDate     DATETIME, 
                                                @MemCode    VARCHAR(Max), 
                                                @YearCode   VARCHAR(20),
												@Istransfer Varchar(10)) 
AS 

SET NOCOUNT ON;
CREATE TABLE #mainoutputtable_1_Final_merger
        ( 
           id INT,
		   Trans_no varchar(20),
		   Sr_no int,
		   flag_HT VARCHAR(200),
		   opening_bill_no varchar(500) ,
		   dupid INT,
		   prioritys INT,
		   Script_Code varchar(10),
		   AcountType varchar(20),
		   BrokerCode varchar(10),
		   Consultant_Code varchar(10),
		   Script_Name varchar(max),
		   Holding_Type varchar(max),
           opening_date VARCHAR(50),
		   opening_qty  Int ,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date VARCHAR(50),
		   purchase_bill_no VARCHAR(100),
		   purchase_qty int ,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date VARCHAR(50),
		   sold_bill_no VARCHAR(100),
		   sold_qty Int ,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain FLOAT DEFAULT 0,
		   loss FLOAT DEFAULT 0,
		   closing_qty Int, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   Consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   Other_amt FLOAT DEFAULT 0,
		   sort   VARCHAR(5),
		   type VARCHAR(50)
        ) 

		INSERT INTO #mainoutputtable_1_Final_merger
		EXECUTE proc_Stockholdingposition_Equity 0,0,@AcType,@MemCode,@YearCode,@FromDate,@ToDate,@ScriptCode,'','','', '0' ,'0','details','0'

		--proc_Stockholdingposition_Equity 0,0,'1100014','30001','1120182019','2018-04-01 12:00:00:00','2019-03-31 03:50:37:50','','','','', '0' ,'0','details'
	--	EXECUTE proc_Stockholdingposition_Equity 0,0,'1100014','R0001','1120182019','2018-04-01 12:00:00:00','2019-03-31 03:50:37:50','E0152','','','', '0' ,'0','details',0

		--Select * from #mainoutputtable_1_Final_merger

		SELECT	 qty ,rate ,transdt ,consultantcode , consultantname ,demateCode , transno ,srno,dematname 
	    from 
		(SELECT	closing_qty		as 'qty',
				closing_rate	as 'rate',
				CASE 
					WHEN opening_date IS NOT NULL 
					THEN opening_date 
					ELSE purchase_date 
				END as 'transdt',
				temp.Consultant_Code as 'consultantcode', 
				cons.Consultant_Name as 'consultantname',
				BBD.dp_code          as 'demateCode',
				temp.Trans_no        as 'transno',
				temp.Sr_no           as 'srno',
				MD.DP_Name          as  'dematname'
		FROM    #mainoutputtable_1_Final_merger temp
		LEFT JOIN Mst_Consultant cons 
			ON temp.Consultant_Code = cons.Consultant_Code
        Inner Join BrokerBill_DmatInfo BBD 
		    ON temp.Trans_no=BBD.Trans_No and temp.Script_Code=BBD.Script_Code  and BBD.Member_code=@MemCode and BBD.YearCode=@YearCode and temp.Sr_no = BBD.Sr_No 
        Inner Join Mst_Demat MD
		    ON MD.DP_Code=BBD.dp_code and MD.Member_code=@MemCode and MD.Year_Code=@YearCode
		   
		WHERE  closing_qty > 0
		  
		Group By closing_qty,closing_rate,opening_date,purchase_date,MD.DP_Name,
		temp.Consultant_Code,cons.Consultant_Name,BBD.dp_code,temp.Trans_no,temp.Sr_no ) as a
		WHERE a.transdt = ( SELECT CASE WHEN @Istransfer = 1 THEN (SELECT a.transdt WHERE a.transdt <= @ToDate) ELSE a.transdt  END)
		  AND a.transdt = ( SELECT CASE WHEN @Istransfer = 1 THEN (SELECT a.transdt WHERE a.transdt >= @FromDate) ELSE a.transdt  END)
		 
		ORDER  BY transdt, transno, srno



















GO
/****** Object:  StoredProcedure [dbo].[Multipal_BrokerBill_Entry_Delete]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Multipal_BrokerBill_Entry_Delete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Multipal_BrokerBill_Entry_Delete] AS' 
END
GO
ALTER Procedure [dbo].[Multipal_BrokerBill_Entry_Delete]
( 
  @yearcode varchar(100),
  @membercode varchar(Max),
  @TransNo varchar(1000),
  @InvestmentType varchaR(Max),
  @VoucharNo Varchar(Max),
  @Book_Type1 Varchar(Max),
  @OtherInvestment Varchar(Max)
)
As
BEGIN
BEGIN TRANSACTION;
SAVE TRANSACTION MySavePoint;
SET NOCOUNT ON;
IF(@TransNo!='' AND @OtherInvestment='123')
        BEGIN TRY
                Delete from AC_Trans where  AC_Trans.Member_Code=@membercode AND AC_Trans.Year_Code=@yearcode   
                            AND AC_Trans.Trans_No IN(SELECT Value FROM membercodestable(@TransNo,','))

                Delete from Other_Investments where Other_Investments.Member_Code=@membercode and Other_Investments.Year_Code=@yearcode 
                            And Other_Investments.Sr_No IN(SELECT Value FROM membercodestable(@TransNo,',') )

                Delete from Certificate_Details Where Certificate_Details.SR_NO IN(SELECT Value FROM membercodestable(@TransNo,','))
				COMMIT TRANSACTION 
        END TRY
		BEGIN CATCH
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION MySavePoint; -- rollback to MySavePoint
        END
    END CATCH

ELSE IF(@TransNo!='' AND @OtherInvestment='Insurance')
       BEGIN TRY
                Delete from Insurance where Insurance.Member_Code=@membercode AND Insurance.Year_Code=@yearcode 
                            AND Insurance.Trans_no IN(SELECT Value FROM membercodestable(@TransNo,','))

                Delete From  AC_Trans Where AC_Trans.Member_Code=@membercode AND AC_Trans.Year_Code=@yearcode 
				AND AC_Trans.Trans_No IN(SELECT Value FROM membercodestable(@TransNo,','))

				COMMIT TRANSACTION 
       END TRY
	   BEGIN CATCH
             IF @@TRANCOUNT > 0
                BEGIN
                    ROLLBACK TRANSACTION MySavePoint; -- rollback to MySavePoint
                END
    END CATCH

ELSE if(@TransNo !='' AND @Book_Type1!='JV' AND @Book_Type1!='BK')
        BEGIN TRY
                Delete from  BrokerBill  where Member_Code=@membercode and YearCode=@yearcode
                             AND isFNOBill=@InvestmentType and Trans_no in (SELECT Value FROM membercodestable(@TransNo,','))

                Delete from BrokerBill_Trans where BrokerBill_Trans.Member_code=@membercode and BrokerBill_Trans.YearCode=@yearcode 
                            AND BrokerBill_Trans.isFNOBill=@InvestmentType and BrokerBill_Trans.Trans_No in(SELECT Value FROM membercodestable(@TransNo,','))

                Delete from BrokerBill_DmatInfo where BrokerBill_DmatInfo.Member_code=@membercode and BrokerBill_DmatInfo.YearCode=@yearcode  
                            And BrokerBill_DmatInfo.Trans_No In(SELECT Value FROM membercodestable(@TransNo,','))

                Delete from AC_Trans where  AC_Trans.Member_Code=@membercode AND AC_Trans.Year_Code=@yearcode 
                            AND AC_Trans.InvestmentType=@InvestmentType AND AC_Trans.Trans_No IN(SELECT Value FROM membercodestable(@TransNo,','))
			    COMMIT TRANSACTION 
         END TRY
		 BEGIN CATCH
             IF @@TRANCOUNT > 0
                BEGIN
                    ROLLBACK TRANSACTION MySavePoint; -- rollback to MySavePoint
                END
        END CATCH
ELSE IF(@TransNo !='' AND @Book_Type1='JV')
        BEGIN TRY
                Delete from AC_Trans where  AC_Trans.Member_Code=@membercode AND AC_Trans.Year_Code=@yearcode  and Book_Type1=@Book_Type1
                            AND AC_Trans.Vouch_No IN(SELECT Value FROM membercodestable(@VoucharNo,',')) AND AC_Trans.Trans_No in(SELECT Value FROM membercodestable(@TransNo,','))
       
	    COMMIT TRANSACTION 
	    END TRY	
		BEGIN CATCH
             IF @@TRANCOUNT > 0
                BEGIN
                    ROLLBACK TRANSACTION MySavePoint; -- rollback to MySavePoint
                END
        END CATCH
ELSE IF(@VoucharNo!='' AND @Book_Type1='BK')
       BEGIN TRY
                Delete from AC_Trans where  AC_Trans.Member_Code=@membercode AND AC_Trans.Year_Code=@yearcode  and Book_Type1=@Book_Type1
                            AND AC_Trans.Vouch_No IN(SELECT Value FROM membercodestable(@VoucharNo,',')) AND AC_Trans.Trans_No in(SELECT Value FROM membercodestable(@TransNo,','))
       COMMIT TRANSACTION 
	   END TRY
	   BEGIN CATCH
             IF @@TRANCOUNT > 0
       BEGIN
             ROLLBACK TRANSACTION MySavePoint; -- rollback to MySavePoint
       END
    END CATCH
END




























GO
/****** Object:  StoredProcedure [dbo].[Postal_Otherinvestment_Report]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Postal_Otherinvestment_Report]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Postal_Otherinvestment_Report] AS' 
END
GO
-- exec [Postal_Otherinvestment_Report] '20180103','20180106','A0001','110002','M0002'    ,'0'      '1','1'
-- exec [Postal_Otherinvestment_Report] '20180104','20190331','30001','','','1'

-- exec [Postal_Otherinvestment_Report] '20110103','20180106','','110002','','0'

ALTER Procedure [dbo].[Postal_Otherinvestment_Report]
(
 @trans_dt_from datetime,
 @trans_dt_to datetime,
 @membercode nvarchar(Max),
 @investmentcode nvarchar(MAx),
 @familycode nvarchar(Max),
 @remark nvarchar(10)

)
--..........Account Master ....
As
begin
SET NOCOUNT ON;
             -- if(@remarks='1')
			 if(@membercode='' and @investmentcode='' and @familycode='' and @remark='1')
			 begin
              select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      OI.Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code  AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			  and OI.Member_Code in (@membercode)			 
			  order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end
			  else if(@membercode!='' and @investmentcode='' and @familycode='' and @remark='1')
		      begin
              select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      OI.Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			  and OI.Member_Code in (SELECT Value FROM membercodestable(@membercode,','))
			  
			  Group By Sr_No,MM.Member_Name,Post_Office,OI.Agent,Trans_Dt,For_Years,For_Months,For_Days,Maturity_Date,Maturity_Amount,OI.Remark1,OI.Remark2,
			  chq_no,MF.Family_Name,MA.Grp_Name,MA.AC_Name,Amount,MF.Family_Code,MA.AC_Code,MM.Member_Code,OI.Member_Code,MM.Family_Code
			  order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			  else if(@membercode='' and @investmentcode='' and @familycode='' and @remark='0')
			 begin
              select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			  and OI.Member_Code in (@membercode)
			 
			  Group By Sr_No,MM.Member_Name,Post_Office,OI.Agent,Trans_Dt,For_Years,For_Months,For_Days,Maturity_Date,Maturity_Amount,OI.Remark1,OI.Remark2,
			  chq_no,MF.Family_Name,MA.Grp_Name,MA.AC_Name,Amount,MF.Family_Code,MA.AC_Code,MM.Member_Code,OI.Member_Code,MM.Family_Code
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			  else if (@membercode!='' and @investmentcode='' and @familycode='' and @remark='0')
			  begin
			  select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			  and OI.Member_Code in (SELECT Value FROM membercodestable(@membercode,','))
			 
			  Group By Sr_No,MM.Member_Name,Post_Office,OI.Agent,Trans_Dt,For_Years,For_Months,For_Days,Maturity_Date,Maturity_Amount,OI.Remark1,OI.Remark2,
			  chq_no,MF.Family_Name,MA.Grp_Name,MA.AC_Name,Amount,MF.Family_Code,MA.AC_Code,MM.Member_Code,OI.Member_Code,MM.Family_Code
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			  else if (@membercode='' and @investmentcode='' and @familycode!='' and @remark='0')
			  begin
			  select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			 
			  and MF.Family_Code in (select value from membercodestable(@familycode,','))
			  Group By Sr_No,MM.Member_Name,Post_Office,OI.Agent,Trans_Dt,For_Years,For_Months,For_Days,Maturity_Date,Maturity_Amount,OI.Remark1,OI.Remark2,
			  chq_no,MF.Family_Name,MA.Grp_Name,MA.AC_Name,Amount,MF.Family_Code,MA.AC_Code,MM.Member_Code,OI.Member_Code,MM.Family_Code
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			  else if (@membercode='' and @investmentcode!='' and @familycode!='' and @remark='0')
			  begin
			  select MM.Member_Name,MF.Family_Code,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			
			  and OI.Investment_Code in (SELECT Value FROM membercodestable(@investmentcode,','))
			  and MF.Family_Code in (select value from membercodestable(@familycode,','))
			  Group By Sr_No,MM.Member_Name,Post_Office,OI.Agent,Trans_Dt,For_Years,For_Months,For_Days,Maturity_Date,Maturity_Amount,OI.Remark1,OI.Remark2,
			  chq_no,MF.Family_Name,MA.Grp_Name,MA.AC_Name,Amount,MF.Family_Code,MA.AC_Code,MM.Member_Code,OI.Member_Code,MM.Family_Code
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			  else if (@membercode='' and @investmentcode!='' and @familycode!='' and @remark='1')
			  begin
			  select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			
			  and OI.Investment_Code in (SELECT Value FROM membercodestable(@investmentcode,','))
			  and MF.Family_Code in (select value from membercodestable(@familycode,','))
			  Group By Sr_No,MM.Member_Name,Post_Office,OI.Agent,Trans_Dt,For_Years,For_Months,For_Days,Maturity_Date,Maturity_Amount,OI.Remark1,OI.Remark2,
			  chq_no,MF.Family_Name,MA.Grp_Name,MA.AC_Name,Amount,MF.Family_Code,MA.AC_Code,MM.Member_Code,OI.Member_Code,MM.Family_Code
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			  else if (@membercode!='' and @investmentcode='' and @familycode!='' and @remark='1')
			  begin
			  select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			  and OI.Member_Code in (SELECT Value FROM membercodestable(@membercode,','))
			
			  and MF.Family_Code in (select value from membercodestable(@familycode,','))
			  Group By Sr_No,MM.Member_Name,Post_Office,OI.Agent,Trans_Dt,For_Years,For_Months,For_Days,Maturity_Date,Maturity_Amount,OI.Remark1,OI.Remark2,
			  chq_no,MF.Family_Name,MA.Grp_Name,MA.AC_Name,Amount,MF.Family_Code,MA.AC_Code,MM.Member_Code,OI.Member_Code,MM.Family_Code
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			   else if (@membercode!='' and @investmentcode='' and @familycode!='' and @remark='0')
			  begin
			  select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			  and OI.Member_Code in (SELECT Value FROM membercodestable(@membercode,','))
			
			  and MF.Family_Code in (select value from membercodestable(@familycode,','))
			  Group By Sr_No,MM.Member_Name,Post_Office,OI.Agent,Trans_Dt,For_Years,For_Months,For_Days,Maturity_Date,Maturity_Amount,OI.Remark1,OI.Remark2,
			  chq_no,MF.Family_Name,MA.Grp_Name,MA.AC_Name,Amount,MF.Family_Code,MA.AC_Code,MM.Member_Code,OI.Member_Code,MM.Family_Code
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			  else if (@membercode!='' and @investmentcode!='' and @familycode!='' and @remark='1')
			  begin
			  select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			  and OI.Member_Code in (SELECT Value FROM membercodestable(@membercode,','))
			  and OI.Investment_Code in (SELECT Value FROM membercodestable(@investmentcode,','))
			  and MF.Family_Code in (select value from membercodestable(@familycode,','))

			  Group By Sr_No,MM.Member_Name,Post_Office,OI.Agent,Trans_Dt,For_Years,For_Months,For_Days,Maturity_Date,Maturity_Amount,OI.Remark1,OI.Remark2,
			  chq_no,MF.Family_Name,MA.Grp_Name,MA.AC_Name,Amount,MF.Family_Code,MA.AC_Code,MM.Member_Code,OI.Member_Code,MM.Family_Code
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			  else if (@membercode='' and @investmentcode!='' and @familycode='' and @remark='0')
			  begin
			  select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			
			  and OI.Investment_Code in (SELECT Value FROM membercodestable(@investmentcode,','))
			  
			  Group By Sr_No,MM.Member_Name,Post_Office,OI.Agent,Trans_Dt,For_Years,For_Months,For_Days,Maturity_Date,Maturity_Amount,OI.Remark1,OI.Remark2,
			  chq_no,MF.Family_Name,MA.Grp_Name,MA.AC_Name,Amount,MF.Family_Code,MA.AC_Code,MM.Member_Code,OI.Member_Code,MM.Family_Code
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			  else if (@membercode='' and @investmentcode!='' and @familycode='' and @remark='1')
			  begin
			  select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			
			  and OI.Investment_Code in (SELECT Value FROM membercodestable(@investmentcode,','))
			 
			  Group By Sr_No,MM.Member_Name,Post_Office,OI.Agent,Trans_Dt,For_Years,For_Months,For_Days,Maturity_Date,Maturity_Amount,OI.Remark1,OI.Remark2,
			  chq_no,MF.Family_Name,MA.Grp_Name,MA.AC_Name,Amount,MF.Family_Code,MA.AC_Code,MM.Member_Code,OI.Member_Code,MM.Family_Code
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			  else if (@membercode!='' and @investmentcode!='' and @familycode='' and @remark='0')
			  begin
			  select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			  and OI.Member_Code in (SELECT Value FROM membercodestable(@membercode,','))
			  and OI.Investment_Code in (SELECT Value FROM membercodestable(@investmentcode,','))
			
			  Group By Sr_No,MM.Member_Name,Post_Office,OI.Agent,Trans_Dt,For_Years,For_Months,For_Days,Maturity_Date,Maturity_Amount,OI.Remark1,OI.Remark2,
			  chq_no,MF.Family_Name,MA.Grp_Name,MA.AC_Name,Amount,MF.Family_Code,MA.AC_Code,MM.Member_Code,OI.Member_Code,MM.Family_Code
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			  else if (@membercode!='' and @investmentcode!='' and @familycode='' and @remark='1')
			  begin
			  select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			  and OI.Member_Code in (SELECT Value FROM membercodestable(@membercode,','))
			  and OI.Investment_Code in (SELECT Value FROM membercodestable(@investmentcode,','))
			
			  Group By Sr_No,MM.Member_Name,Post_Office,OI.Agent,Trans_Dt,For_Years,For_Months,For_Days,Maturity_Date,Maturity_Amount,OI.Remark1,OI.Remark2,
			  chq_no,MF.Family_Name,MA.Grp_Name,MA.AC_Name,Amount,MF.Family_Code,MA.AC_Code,MM.Member_Code,OI.Member_Code,MM.Family_Code
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			  else if (@membercode='' and @investmentcode='' and @familycode!='' and @remark='1')
			  begin
			  select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			 
			  and MF.Family_Code in (select value from membercodestable(@familycode,','))
			  Group By Sr_No,MM.Member_Name,Post_Office,OI.Agent,Trans_Dt,For_Years,For_Months,For_Days,Maturity_Date,Maturity_Amount,OI.Remark1,OI.Remark2,
			  chq_no,MF.Family_Name,MA.Grp_Name,MA.AC_Name,Amount,MF.Family_Code,MA.AC_Code,MM.Member_Code,OI.Member_Code,MM.Family_Code
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			  else if (@membercode!='' and @investmentcode!='' and @familycode!='' and @remark='0')
			  begin
			  select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			  and OI.Member_Code in (SELECT Value FROM membercodestable(@membercode,','))
			  and OI.Investment_Code in (SELECT Value FROM membercodestable(@investmentcode,','))
			  and MF.Family_Code in (select value from membercodestable(@familycode,','))
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  
			  end

			  else --if (@membercode!='' and @investmentcode!='' and @familycode!='')
			  begin
			  select MM.Member_Name,
			  Post_Office  as 'Investment With',
		      Agent,
			  (convert(varchar(10),Trans_Dt,103)) as 'Date',
			  (CONCAT(For_Years,'/',For_Months,'/',For_Days)) as 'Investment Duration',
			  Amount,-- Maturity_Date,
			  (convert(varchar(10),Maturity_Date,103)) as 'Maturity Date',
			  Maturity_Amount, --'' as 'Cash/Bank',
			  (concat(OI.Remark1,',',OI.Remark2)) as 'Remarks',
			  chq_no as 'Cheque No.',
		      MF.Family_Name as 'Family Name' ,
		      (concat(MA.Grp_Name,' : ',MA.AC_Name)) as 'Cash/Bank'
			  from Other_Investments OI 
			  inner join Mst_Member MM on MM.Member_Code=OI.Member_Code
			  inner join Mst_Family MF on MF.Family_Code=MM.Family_Code
			  inner join Mst_Account MA on MA.AC_Code=OI.Cr_Code AND MA.Member_Code IN (SELECT Value FROM membercodestable(@membercode,','))
			  where Trans_Dt>=@trans_dt_from and Trans_Dt<=@trans_dt_to 
			  and OI.Member_Code in (SELECT Value FROM membercodestable(@membercode,','))
			  and OI.Investment_Code in (SELECT Value FROM membercodestable(@investmentcode,','))
			  and MF.Family_Code in (select value from membercodestable(@familycode,','))
			   order by MM.Family_Code, OI.Member_Code, Trans_Dt		  	  
			  end

			  --else
			  --begin

			  --end
			  
			

end






























GO
/****** Object:  StoredProcedure [dbo].[proc_Advisory_BrokerWise_Equity_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Advisory_BrokerWise_Equity_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Advisory_BrokerWise_Equity_Summary] AS' 
END
GO

--Execute  proc_Advisory_BrokerWise_Equity_Summary    0,0,'0','Y0001,D0001','1120172018','2015-02-01 12:00:00:00','2018-03-28 03:50:37:50','','','0','', '0' ,'0',1,0 
--Execute  proc_Stockholdingposition_Equity_Summary    0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0',1,1,1 
ALTER PROCEDURE [dbo].[proc_Advisory_BrokerWise_Equity_Summary] --'' 
(@status            INT, 
 @Investmenttype    INT, 
 @Ac_Type           NVARCHAR(100), 
 @memcode           VARCHAR(100), 
 @yearcode          VARCHAR(100), 
 @Fromdate          VARCHAR(30), 
 @Todate            VARCHAR(30), 
 @ScriptCode        VARCHAR(max), 
 @BrokerCode        VARCHAR(max), 
 @BSE_NSE_Code      VARCHAR(max), 
 @Is_BFCF           VARCHAR(max), 
 @short_Long_Term   INT, 
 @IsWithTax         BIT = 0, 
 @IsAdvisory        BIT=0, 
 @IsAllDataRequired BIT = 1) 
AS 
  BEGIN 
  SET NOCOUNT ON;
      DECLARE @Invested_Amount FLOAT 

      SELECT MA.ac_code, 
             MA.ac_name, 
             Sum(At.amount) AS 'Amount',
			 AT.member_code 
      INTO   #brokertotal 
      FROM   ac_trans AT 
             INNER JOIN mst_account MA 
                     ON AT.dr_code = MA.ac_code 
                        AND MA.member_code = At.member_code 
                        AND Ma.year_code = At.year_code 
                        AND Ma.grp_name = 'BROKER' 
      WHERE  At.member_code IN (SELECT value 
                                FROM   Membercodestable(@memcode, ',')) 
             AND AT.year_code = @yearcode 
             AND At.book_type1 = 'BK' 
             AND At.sub_type2 = 'P' 
             AND At.dr_code = MA.ac_code 
      GROUP  BY At.dr_code, 
                MA.ac_code, 
                MA.ac_name ,
				 AT.member_code 

      SELECT @Invested_Amount = Sum(amount) 
      FROM   #brokertotal 

      CREATE TABLE #meberwisebankpaymenttotal 
        ( 
           membercode VARCHAR(100), 
           amount     FLOAT 
        ) 

      INSERT INTO #meberwisebankpaymenttotal 
      SELECT MA.member_code, 
             Sum(At.amount) AS 'Amount' 
      FROM   ac_trans AT 
             INNER JOIN mst_account MA 
                     ON AT.dr_code = MA.ac_code 
                        AND MA.member_code = At.member_code 
                        AND Ma.year_code = At.year_code 
                        AND Ma.grp_name = 'BROKER' 
      WHERE  At.member_code IN (SELECT value 
                                FROM   Membercodestable(@memcode, ',')) 
             AND AT.year_code = @yearcode 
             AND At.book_type1 = 'BK' 
             AND At.sub_type2 = 'P' 
             AND At.dr_code = MA.ac_code 
      GROUP  BY MA.member_code 

      SELECT * 
      FROM   #meberwisebankpaymenttotal 

      CREATE TABLE #mainoutputtable_1_final_summary 
        ( 
           prioritys         INT, 
           trans_no          VARCHAR(50), 
           scriptcode        VARCHAR(50), 
           id                INT, 
           membercode        VARCHAR(20), 
           yearcode          VARCHAR(50), 
           script_name       VARCHAR(500), 
           holding_type      VARCHAR(200), 
           flag_script_name  VARCHAR(500), 
           flag_holding_type VARCHAR(200), 
           opening_date      VARCHAR(50), 
           opening_qty       FLOAT DEFAULT 0, 
           opening_rate      FLOAT DEFAULT 0, 
           opening_amount    FLOAT DEFAULT 0, 
           purchase_date     VARCHAR(50), 
           purchase_bill_no  VARCHAR(100), 
           purchase_qty      FLOAT DEFAULT 0, 
           purchase_rate     FLOAT DEFAULT 0, 
           purchase_amount   FLOAT DEFAULT 0, 
           sold_date         VARCHAR(50), 
           sold_bill_no      VARCHAR(100), 
           sold_qty          FLOAT DEFAULT 0, 
           sold_rate         FLOAT DEFAULT 0, 
           sold_amount       FLOAT DEFAULT 0, 
           gain_loss         FLOAT DEFAULT 0, 
           gain              FLOAT DEFAULT 0, 
           loss              FLOAT DEFAULT 0, 
           closing_qty       FLOAT DEFAULT 0, 
           closing_rate      FLOAT DEFAULT 0, 
           closing_value     FLOAT DEFAULT 0, 
           short_term        FLOAT DEFAULT 0, 
           long_term         FLOAT DEFAULT 0, 
           speculation       FLOAT DEFAULT 0, 
           gain_speculation  FLOAT DEFAULT 0, 
           loss_speculation  FLOAT DEFAULT 0, 
           broker_name       VARCHAR(500), 
           nse_rate          FLOAT DEFAULT 0, 
           bse_rate          FLOAT DEFAULT 0, 
           other_amt         FLOAT DEFAULT 0, 
           servtax_amt       FLOAT DEFAULT 0, 
           stt_amt           FLOAT DEFAULT 0, 
           sort              VARCHAR(5), 
           isintradaycol     INT 
        ) 

      INSERT INTO #mainoutputtable_1_final_summary 
      EXEC Proc_stockholdingposition_brokerwise_equity 
        @status, 
        @Investmenttype, 
        @Ac_Type, 
        @memcode, 
        @yearcode, 
        @Fromdate, 
        @Todate, 
        @ScriptCode, 
        @BrokerCode, 
        @BSE_NSE_Code, 
        @Is_BFCF, 
        0, 
        @short_Long_Term, 
        'ALLData', 
        @IsWithTax 

      SELECT T1.id, 
             T1.trans_no, 
             T1.prioritys, 
             T1.script_name, 
             T1.holding_type, 
             T1.flag_script_name, 
             T1.flag_holding_type, 
             T1.opening_date, 
             T1.opening_qty, 
             T1.opening_rate, 
             T1.opening_amount, 
             T1.purchase_date, 
             T1.purchase_bill_no, 
             T1.purchase_qty, 
             T1.purchase_rate, 
             T1.purchase_amount, 
             T1.sold_date, 
             T1.sold_bill_no, 
             T1.sold_qty, 
             T1.sold_rate, 
             T1.sold_amount, 
             T1.gain_loss, 
             T1.gain, 
             T1.loss, 
             T1.closing_qty, 
             T1.closing_rate, 
             T1.closing_value, 
             T1.short_term, 
             T1.long_term, 
             T1.speculation, 
             T1.gain_speculation, 
             T1.loss_speculation, 
             T1.broker_name, 
             T1.sort, 
             T1.isintradaycol, 
             T2.other_amt, 
             T2.servtax_amt, 
             T2.stt_amt, 
             membercode, 
             Isnull(Dr.bse_rate, 0) AS 'bse_rate',/**/ 
             Isnull(Dr.bse_rate, 0) AS 'nse_rate' /**/ 
      INTO   #alldata_summary 
      FROM   #mainoutputtable_1_final_summary T1 
             LEFT JOIN brokerbill T2 
                    ON T2.trans_no = T1.trans_no 
                       AND T2.member_code = T1.membercode 
                       AND T2.yearcode = T1.membercode 
             LEFT JOIN dailyrate DR 
                    ON DR.script_code = T1.scriptcode 
                       AND Dr.trans_dt = @Todate /**/ 
      ORDER  BY broker_name 

      --Select * from #alldata_Summary 
      TRUNCATE TABLE #mainoutputtable_1_final_summary 

      INSERT INTO #mainoutputtable_1_final_summary 
                  (id, 
                   trans_no, 
                   prioritys, 
                   script_name, 
                   holding_type, 
                   flag_script_name, 
                   flag_holding_type, 
                   opening_date, 
                   opening_qty, 
                   opening_rate, 
                   opening_amount, 
                   purchase_date, 
                   purchase_bill_no, 
                   purchase_qty, 
                   purchase_rate, 
                   purchase_amount, 
                   sold_date, 
                   sold_bill_no, 
                   sold_qty, 
                   sold_rate, 
                   sold_amount, 
                   gain_loss, 
                   gain, 
                   loss, 
                   closing_qty, 
                   closing_rate, 
                   closing_value, 
                   short_term, 
                   long_term, 
                   speculation, 
                   gain_speculation, 
                   loss_speculation, 
                   broker_name, 
                   nse_rate, 
                   bse_rate, 
                   sort, 
                   isintradaycol, 
                   t2.other_amt, 
                   t2.servtax_amt, 
                   t2.stt_amt, 
                   membercode) 
      SELECT id, 
             trans_no, 
             prioritys, 
             script_name, 
             holding_type, 
             flag_script_name, 
             flag_holding_type, 
             opening_date, 
             Isnull(opening_qty, 0), 
             Isnull(opening_rate, 0), 
             Isnull(opening_amount, 0), 
             purchase_date, 
             purchase_bill_no, 
             Isnull(purchase_qty, 0), 
             Isnull(purchase_rate, 0), 
             Isnull(purchase_amount, 0), 
             sold_date, 
             sold_bill_no, 
             Isnull(sold_qty, 0), 
             Isnull(sold_rate, 0), 
             Isnull(sold_amount, 0), 
             Isnull(gain_loss, 0), 
             Isnull(gain, 0), 
             Isnull(loss, 0), 
             Isnull(closing_qty, 0), 
             Isnull(closing_rate, 0), 
             Isnull(closing_value, 0), 
             Isnull(short_term, 0), 
             Isnull(long_term, 0), 
             Isnull(speculation, 0), 
             Isnull(gain_speculation, 0), 
             Isnull(loss_speculation, 0), 
             broker_name, 
             Max(Isnull(nse_rate, 0)), 
             Max(Isnull(bse_rate, 0)), 
             sort, 
             isintradaycol, 
             Isnull(other_amt, 0), 
             Isnull(servtax_amt, 0), 
             Isnull(stt_amt, 0), 
             membercode 
      FROM   #alldata_summary 
      GROUP  BY broker_name, 
                id, 
                trans_no, 
                prioritys, 
                script_name, 
                holding_type, 
                flag_script_name, 
                flag_holding_type, 
                opening_date, 
                opening_qty, 
                opening_rate, 
                opening_amount, 
                purchase_date, 
                purchase_bill_no, 
                purchase_qty, 
                purchase_rate, 
                purchase_amount, 
                sold_date, 
                sold_bill_no, 
                sold_qty, 
                sold_rate, 
                sold_amount, 
                gain_loss, 
                gain, 
                loss, 
                closing_qty, 
                closing_rate, 
                closing_value, 
                short_term, 
                long_term, 
                speculation, 
                gain_speculation, 
                loss_speculation, 
                sort, 
                isintradaycol, 
                other_amt, 
                servtax_amt, 
                stt_amt, 
                membercode 
      ORDER  BY broker_name 

      DECLARE @Market_Amount FLOAT 

      SELECT @Market_Amount = Round(bse_rate * Sum(closing_qty) - Sum( 
                                           Isnull(closing_value, 0)), 2) 
      FROM   #mainoutputtable_1_final_summary 
      GROUP  BY bse_rate 

      IF( @Market_Amount = 0 ) 
        SET @Market_Amount = 1 

      --Select @Market_Amount 
      IF( @IsAdvisory = 1 ) 
        BEGIN 
            DECLARE @DynamicPivotQuery AS NVARCHAR(max) 
            DECLARE @ColumnName AS NVARCHAR(max) 


                  SELECT MM.member_name 
                         AS 
                         'Member Name', 
                         holding_type 
                         AS 'Holding Type', 
                         script_name 
                         'Script Name', 
                         Isnull (Sum(closing_qty), 0) 
                         AS 'Closing Qty', 
                         Isnull(Round(Abs(Sum(Isnull(closing_value, 0)) / Sum( 
                                          NULLIF(closing_qty, 0))), 4 
                                ), 0) 
                         AS 'Closing Rate', 
                         Round(Sum(closing_value), 4) 
                         AS 'Total Cast of Holding', 
                         --ROUND((ROUND(SUM(closing_value),4)/ (select  TOP 1 ISNULL(MBT.Amount,1) from #MeberwiseBankPaymentTotal MBT Where MBT.MemberCode= Membercode )) * 100,4)  AS '% Of AUA',  
                         Round(( Round(Sum(closing_value), 4) / 
                                 Isnull(Sum(MBT.amount), 1) ) 
                               * 
                               100 
                         , 4) AS 
                         '% Of AUA', 
                         Isnull(bse_rate, 0) 
                         AS 'CMP', 
                         bse_rate * Sum(closing_qty) 
                         AS 'MARKET VALUES', 
                         Round(bse_rate * Sum(closing_qty) - Sum( 
                               Isnull(closing_value, 0)), 
                         4) 
                         AS 'GAIN', 
                         Round(Isnull(bse_rate * Sum(closing_qty), 1) / ( 
                               Isnull (@Market_Amount, 1) ) * 
                               100, 4) 
                         AS '%  of Total Portfolio', 
                         ( Round(( ( Isnull (bse_rate, 0) / Isnull( 
                                     Round(Abs(Sum( 
                                     Isnull( 
                                               closing_value, 0) 
                                               ) 
                                                 / 
                                     Sum( 
                                           NULLIF(closing_qty 
                                           , 
                                           1))), 
                                             4 
                                     ), 
                                                            1) 
                                     ) - 1 
                                 ) * 100, 4) ) 
                         AS 'Gain(%)', 
                         '' 
                         AS'Broker Name', 
                         FS.membercode 
                  INTO   #tempmemberwise 
                  FROM   #mainoutputtable_1_final_summary FS 
                         JOIN #meberwisebankpaymenttotal MBT 
                           ON MBT.membercode = FS.membercode 
                         LEFT JOIN mst_member MM 
                                ON MM.member_code = FS.membercode 
                  WHERE  FS.membercode IN (SELECT value 
                                           FROM   Membercodestable(@memcode, ',' 
                                                  )) 
                  GROUP  BY FS.membercode, 
                            MM.member_code, 
                            MM.member_name, 
                            holding_type, 
                            script_name, 
                            bse_rate, 
                            nse_rate, 
                            MBT.membercode 
                  HAVING Sum(closing_qty) != 0 

                  IF( @IsAllDataRequired = 1 ) 
                    BEGIN 
                        SELECT * 
                        FROM   #tempmemberwise 
                        ORDER  BY membercode, 
                                  [script name] 
                    END 
                  ELSE 
                    BEGIN 
                        --Get distinct values of the PIVOT Column  
                        SELECT @ColumnName = Isnull(@ColumnName + ',', '') 
                                             + Quotename([member name]) 
                        FROM   (SELECT DISTINCT [member name] 
                                FROM   #tempmemberwise) AS [Member_Name] 

                        PRINT @ColumnName 

                        --Prepare the PIVOT query using the dynamic  
                        SET @DynamicPivotQuery = 
                        N'	sELECT * into #temp1 from ( select [Script Name], [Member Name], [MARKET VALUES]  FROM #Tempmemberwise )SRC PIVOT( SUM([MARKET VALUES])  FOR [Member Name] IN (' 
                        + @ColumnName + ')   ) PIV Select * from #temp1' 

                        EXEC Sp_executesql 
                          @DynamicPivotQuery 
                    END 
            
        
            /*AUA Amount*/ 
            SELECT Isnull(Sum(amount), 1) AS 'AUA',mm.Member_Name 
            FROM   #brokertotal BT
			 JOIN mst_member mm 
                     ON BT.Member_code = mm.member_code 
					 Group By mm.Member_Name,BT.Member_code,mm.member_code  

			 /*END*/ 
            /*Purchase-SaleAmount*/ 
            SELECT Round(Sum(amount) - ( b2.b2amount ), 2) AS 
                   'Purchase_Sale_Amount', 
                   mm.member_name 
            FROM   brokerbill_trans B1 
                   JOIN (SELECT Sum(amount) AS'B2Amount', 
                                member_code AS'B2Membercode' 
                         FROM   brokerbill_trans 
                         WHERE  isfnobill = '0' 
                                AND member_code IN (SELECT value 
                                                    FROM 
                                    Membercodestable(@memcode, 
                                    ',')) 
                                AND yearcode = @yearcode 
                                AND transtype = 'Sold' 
                         GROUP  BY member_code)b2 
                     ON B1.member_code = b2.b2membercode 
                   JOIN mst_member mm 
                     ON B1.member_code = mm.member_code 
            WHERE  isfnobill = '0' 
                   AND B1.member_code IN (SELECT value 
                                          FROM   Membercodestable(@memcode, ',') 
                                         ) 
                   AND yearcode = @yearcode 
                   AND transtype = 'Bought' 
            GROUP  BY B1.member_code, 
                      b2.b2amount, 
                      mm.member_code, 
                      mm.member_name 
            ORDER  BY B1.member_code 

        /*END*/ 
            /*Unallocated*/ 
            SELECT 
			Round(Sum(amount) - ( b2.b2amount ), 2) + ( d1.divideamount ) + ( MT.bankpaymentamount ) AS'UnallocatedAmount',
			mm.member_name 
			FROM   brokerbill_trans B1 
		   JOIN (SELECT Sum(amount) AS'B2Amount', 
						member_code AS'B2Membercode' 
				 FROM   brokerbill_trans 
				 WHERE  isfnobill = '0' 
						AND member_code IN (SELECT value 
											FROM   Membercodestable(@memcode, ',')) 
						AND yearcode = @yearcode 
						AND transtype = 'Sold' 
				 GROUP  BY member_code)b2 
			 ON B1.member_code = b2.b2membercode 
		   JOIN (SELECT Isnull(Sum(amount), 0)AS'DivideAmount', 
						member_code           AS'DMembercode' 
				 FROM   eqdividend_trans 
				 WHERE  year_code = @yearcode 
						AND member_code IN (SELECT value 
											FROM   Membercodestable(@memcode, ',')) 
				 GROUP  BY member_code)d1 
			 ON B1.member_code = d1.dmembercode 
		   JOIN (SELECT Sum(amount) AS'BankPaymentAmount', 
						membercode  AS'MTMemberCode' 
				 FROM   #meberwisebankpaymenttotal 
				 WHERE  #meberwisebankpaymenttotal.membercode IN 
								(SELECT value 
																  FROM 
								Membercodestable(@memcode, ',')) 
				 GROUP  BY membercode)MT 
			 ON B1.member_code = MT.mtmembercode 
		   JOIN mst_member mm 
			 ON B1.member_code = mm.member_code 
			WHERE  isfnobill = '0' 
				   AND b1.member_code IN (SELECT value 
										  FROM   Membercodestable(@memcode, ',')) 
				   AND yearcode = @yearcode 
				   AND transtype = 'Bought' 
			GROUP  BY B1.member_code, 
					  mm.member_code, 
					  b2.b2amount, 
					  d1.divideamount, 
					  MT.bankpaymentamount, 
					  mm.member_name 
		ORDER  BY mm.member_name 

/*END*/ 
    /*DividendAmount*/ 
    SELECT Isnull(Sum(amount), 0) AS 'Dividend_Amount', 
           mm.member_name 
    FROM   eqdividend_trans ED 
           JOIN mst_member mm 
             ON ED.member_code = mm.member_code 
    WHERE  year_code = '1120172018' 
           AND ED.member_code IN (SELECT value 
                                  FROM   Membercodestable(@memcode, ',')) 
    GROUP  BY ED.member_code, 
              mm.member_name 
    ORDER  BY mm.member_name 

/*End*/ 
    /*T. Port. Value*/ 
    SELECT Sum(bse_rate * (closing_qty))  + E.unallocatedamount AS'TotalPortFolioValues', 
           MM.Member_Name 
    into #TempPF
    FROM   #mainoutputtable_1_final_summary MS 
           JOIN(	SELECT 
					Round(Sum(amount) - ( b2.b2amount ), 2) + ( d1.divideamount ) AS 'UnallocatedAmount', 
					B1.member_code 
					FROM   brokerbill_trans B1 
                    JOIN (SELECT	Sum(amount) AS'B2Amount', 
									member_code AS'B2Membercode' 
                            FROM   brokerbill_trans 
                            WHERE  isfnobill = '0' 
                                AND member_code IN (SELECT value 
                                                    FROM Membercodestable(@memcode, ',')) 
                                AND yearcode = @yearcode 
                                AND transtype = 'Sold' 
                            GROUP  BY member_code) b2 
                    ON B1.member_code = b2.b2membercode 
                    JOIN (SELECT Isnull(Sum(amount), 0) AS 'DivideAmount',  
                                member_code             AS 'DMembercode' 
                            FROM   eqdividend_trans 
                            WHERE  year_code = @yearcode 
                                AND Member_Code IN (SELECT value FROM Membercodestable(@memcode, ',')) 
                            GROUP  BY member_code)d1 
                         ON B1.member_code = d1.DMembercode 
					WHERE  isfnobill = '0' 
						   AND member_code IN (SELECT value FROM   Membercodestable(@memcode, ',' )) 
						   AND yearcode = @yearcode 
						   AND transtype = 'Bought' 
					GROUP  BY member_code, 
							  b2.b2amount, 
                              d1.divideamount) E 
             ON E.member_code = MS.membercode 
           JOIN mst_member mm 
             ON MS.membercode = mm.member_code 
    WHERE  MS.membercode IN (SELECT value FROM   Membercodestable(@memcode, ',')) 
    GROUP  BY MS.membercode, 
              E.unallocatedamount, 
              mm.member_code, 
              mm.Member_Name 
    ORDER  BY mm.Member_Name 
	Select * from #TempPF 

	

	SELECT t1.[Script Name], t1.[Member Name], Round(SUM((t1.[MARKET VALUES]/T2.TotalPortFolioValues))* 100,4) as'Percetage_Values'
	into #Weights_Stock
	FROM #tempmemberwise t1
	JOIN #TempPF T2
	ON t1.[member name] = T2.Member_Name
	GROUP BY t1.[Member Name],t1.[Script Name]

	
		SEt @ColumnName = Null
	     SELECT @ColumnName = Isnull(@ColumnName + ',', '') 
                                             + Quotename([member name]) 
                        FROM   (SELECT DISTINCT [member name] 
                                FROM   #Weights_Stock) AS [Member_Name] 

                        select @ColumnName 

                        --Prepare the PIVOT query using the dynamic  
                        SET @DynamicPivotQuery = 
                        N'	sELECT * into #temp1 from ( select [Script Name], [Member Name], [Percetage_Values]  FROM #Weights_Stock )SRC PIVOT( SUM([Percetage_Values])  FOR [Member Name] IN (' 
                        + @ColumnName + ')   ) PIV Select * from #temp1' 

                        EXEC Sp_executesql 
                          @DynamicPivotQuery 


						

	 
/*END */ 
--Where      
END 
--Select Broker_Name,Sum(ISNULL (gain_loss,0)) from #mainoutputtable_1_Final_Summary 
--Group By Broker_Name 
--Having Sum(ISNULL (gain_loss,0))!=0 
--Order by 1 
--  Select  Round(sum(Other_amt),4) from BrokerBill where Member_code=@memcode and Yearcode=@yearcode and isfnoBill=@Investmenttype and Trans_Dt<=@Todate
END 





GO
/****** Object:  StoredProcedure [dbo].[proc_Advisory_Equity_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Advisory_Equity_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Advisory_Equity_Summary] AS' 
END
GO





--Execute  proc_Advisory_Equity_Summary   0,0,'0','Y0001','1120172018','2015-02-01 12:00:00:00','2018-03-28 03:50:37:50','','','0','', '0' ,'0',0,0,0
--Execute  proc_Stockholdingposition_Equity_Summary    0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0',1,1,1
ALTER PROCEDURE [dbo].[proc_Advisory_Equity_Summary]  --''
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(MAX),@BrokerCode  VARCHAR(MAX),@BSE_NSE_Code VARCHAR(MAX),@Is_BFCF VARCHAR(MAX),@IsIntraDay VARCHAR(MAX),@short_Long_Term INT,
@RecordOnlyhavingClosingbalanceZero AS BIT,@WithActualAvgRate AS BIT, @DateWiseClosinStock AS BIT,@IsWithTax bit = 0)
AS
BEGIN
SET NOCOUNT ON;
		CREATE TABLE #Summary_Result
        (          
		   holding_type VARCHAR(200),
		   Script_Name  VARCHAR(500),
		   closing_value FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0,
		   closing_rate FLOAT DEFAULT 0,
		   closing_date Varchar(100),
		   gain_loss FLOAT DEFAULT 0,
           bse_rate FLOAT DEFAULT 0,
		   BSE_Valuation FLOAT DEFAULT 0,
		   BSE_UnREalizedGainLoss FLOAT DEFAULT 0,
		   nse_rate FLOAT DEFAULT 0,
		   NSe_Valuation FLOAT DEFAULT 0,
		   NSE_UnREalizedGainLoss FLOAT DEFAULT 0,
		   Profit_Loss FLOAT DEFAULT 0,
		   Avg_Rate FLOAT DEFAULT 0,
		   value_After_profit_Loss  FLOAT DEFAULT 0,
		   Other_amount FLOAT DEFAULT 0,
		   Broker_Name Varchar(Max)

		   

		  
        ) 

		INSERT INTO #Summary_Result
		
		Execute  proc_Advisory_Equity_Summary   0,0,'0','Y0001','1120172018','2015-02-01 12:00:00:00','2018-03-28 03:50:37:50','','','0','', '0' ,'0',0,0,0

		Select * from #Summary_Result
		
END

































GO
/****** Object:  StoredProcedure [dbo].[proc_Brokeragestatement_OtherCharges]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Brokeragestatement_OtherCharges]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Brokeragestatement_OtherCharges] AS' 
END
GO


ALTER PROCEDURE [dbo].[proc_Brokeragestatement_OtherCharges]  
--Execute proc_Brokeragestatement_OtherCharges 'Y0001','1120172018','','','04/01/2017','03/31/2018','0'
--select * from mst_Account
(
	@Membercode VARCHAR(Max),
	@Yearcode VARCHAR(1000),
	@BrokerCode VARCHAR(Max),
	@ExpenseType VARCHAR(max),
	@FromDate VARCHAR(50),
	@ToDate VARCHAR(50) ,
	@Investmenttype VARCHAR(50)
)
AS
	BEGIN
	SET NOCOUNT ON;	
		DECLARE @Pivot_Column [nvarchar](max);  
		DECLARE @Query [nvarchar](max);  
			
		IF(@ExpenseType = '')
			BEGIN
				SET @ExpenseType =  (SELECT  STUFF((SELECT ',' + CAST(AC_Code AS VARCHAR(500)) [text()] 
													FROM Mst_Account MA 
													JOIN AC_Trans AT 
														ON MA.AC_Code = AT.Dr_Code OR MA.AC_Code = AT.cr_Code    
													WHERE AT.EntryType = 10
													AND MA.Year_Code = @Yearcode AND MA.Member_Code = @Membercode
													AND AT.Year_Code = @Yearcode AND AT.Member_Code = @Membercode
													--AND AC_Code NOT IN ('(0001','(0002','(0003')
													GROUP BY AC_Code 
													FOR XML PATH(''), TYPE).value('.','VARCHAR(MAX)'),1,1,''))
			END
		--Select @ExpenseType

			DECLARE @TempBrokerCode varchar(max)
			IF(@BrokerCode = '')
				BEGIN 
					Select distinct(Broker_Code) as 'Broker_Code' 
					INTO #Brokers 
					FROM BrokerBill Where YearCode = @Yearcode AND Member_Code = @Membercode and isFNOBill = @Investmenttype
			
					declare @tmp varchar(max)
					SET @tmp = ''
					select @tmp = @tmp + Broker_Code + ',' 
					from #Brokers
					SET @TempBrokerCode = IsNULL((select SUBSTRING(@tmp, 0, LEN(@tmp))),'')
				END
			ELSE 
				BEGIN
					SET @TempBrokerCode = 	@BrokerCode
				END
		 
		SELECT distinct(MA.AC_Name) as 'Exp_Code' 
		into #tempPivotColumn 
		FROM  AC_Trans AT 
			JOIN Mst_Account MA ON MA.AC_Code = (CASE WHEN AT.ExpenseType = 'A' THEN AT.Dr_Code WHEN AT.ExpenseType = 'L' THEN At.Cr_Code END)
			JOIN BrokerBill_Trans BT on At.Trans_No = Bt.Trans_No
		WHERE 
			AT.Member_Code = @Membercode AND AT.Year_Code = @Yearcode AND Bt.isFNOBill = @Investmenttype 
			AND MA.Member_Code = @Membercode AND MA.Year_Code = @Yearcode
			AND bt.TransType != 'Opening' 
			AND MA.AC_Code IN (SELECT Value FROM membercodestable(@ExpenseType,','))  
			AND AT.Amount<>0  

		SELECT @Pivot_Column =  (SELECT  STUFF((SELECT '],[' + CAST(Exp_Code AS VARCHAR(Max)) [text()] FROM #tempPivotColumn FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,2,' '))
		Select @Pivot_Column = @Pivot_Column + ']'

		SELECT @Query='	SELECT	Trans_No,
								ExpenseType, 
								' + @Pivot_Column + '
						into #TempExpense
						FROM (
								Select  At.Trans_No,
										MA.AC_Name,	
										AT.ExpenseType, 
										Cast (At.Amount AS DECIMAL(16,4)) as ''Amount'' 
										--CASE WHEN AT.ExpenseType = ''A'' THEN AT.Dr_Code WHEN AT.ExpenseType = ''L'' THEN At.Cr_Code END as ''Exp_Code''
								FROM  AC_Trans AT
								JOIN Mst_Account MA ON Ma.AC_Code = (CASE WHEN AT.ExpenseType = ''A'' THEN AT.Dr_Code WHEN AT.ExpenseType = ''L'' THEN At.Cr_Code END)
								Where AT.InvestmentType = '''+@Investmenttype+''' and AT.ExpenseType IN (''A'',''L'') AND AT.EntryType=''10'' AND AT.Member_Code IN ('''+@Membercode+''') AND AT.Year_Code = '''+@Yearcode+'''  
								AND MA.Member_Code IN ('''+@Membercode+''') AND MA.Year_Code = '''+@Yearcode+'''  
								Group by   At.Dr_Code,At.Cr_Code,   At.Trans_No,AT.ExpenseType,At.Amount ,MA.AC_Name
							 )
						Tab1
		  
						PIVOT  
						(  
							SUM(Amount) FOR [AC_Name] IN ('+ @Pivot_Column + ')
						) 
						AS Tab2 '  
  
		--/*Execute Query*/  
		--print @Query
		--EXEC  sp_executesql  @Query  


	SELECT @Query = @Query + '
		SELECT  
				BB.Broker_Code,
				MA.AC_Name  AS ''Broker Name'',
				BBT.Bill_no as ''Invoice No'', 
				CONVERT(VARCHAR,BBT.Trans_Dt,103) AS ''Transaction Date'',
				CASE WHEN Cast(SUM(BBT.Brok_Amt) AS DECIMAL(16,4)) = 0.0000 THEN NULL ELSE Cast(SUM(BBT.Brok_Amt) AS DECIMAL(16,4)) END AS ''Brokerage Amount'',
				TE.*
		INTO #TempFinal		
		FROM BrokerBill_Trans BBT
		JOIN #TempExpense TE ON TE.Trans_No = BBT.Trans_No
		LEFT JOIN BrokerBill BB ON BB.Trans_no = BBT.Trans_No AND BB.Member_Code=BBT.Member_code AND BB.YearCode = BBT.YearCode
		LEFT JOIN Mst_Account MA ON MA.AC_Code = BB.Broker_Code  AND MA.Member_Code=BB.Member_Code AND MA.Year_Code=BB.YearCode
		WHERE  
		(BBT.Trans_Dt BETWEEN '''+ @FromDate +''' AND '''+ @ToDate +''') 
		AND BBT.YearCode = '''+@Yearcode+''' AND BBT.Member_code = '''+@Membercode+''' AND BBT.isFNOBill = '''+@Investmenttype + '''
		AND BB.Broker_Code IN (SELECT Value FROM membercodestable(' + Char(39) + @TempBrokerCode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))
		GROUP BY BB.Broker_Code,MA.AC_Name,BBT.Bill_no,BBT.Trans_Dt,TE.Trans_No,TE.ExpenseType,'+ @Pivot_Column+ ''


		
		SELECT @Query = @Query + ' Select * from #TempFinal'

		SELECT @Pivot_Column = 'SUM(' + Replace(@Pivot_Column,',','), SUM(') + ')'

	
		SELECT @Query = @Query + ' Select Broker_Code,[Broker Name], sum([Brokerage Amount]), '+ @Pivot_Column + 'from #TempFinal Group By Broker_Code,[Broker Name]'
		
		print @Query
		EXEC  sp_executesql  @Query  

		

		
	END

	


























GO
/****** Object:  StoredProcedure [dbo].[Proc_ClosingBalanceTransferTo_Mst_Account]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_ClosingBalanceTransferTo_Mst_Account]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_ClosingBalanceTransferTo_Mst_Account] AS' 
END
GO
ALTER procedure [dbo].[Proc_ClosingBalanceTransferTo_Mst_Account]
(
	@InvestmentType int,@Ac_Type_Code varchar(20),@MemberCode varchar(20),@YearCode varchar(20),@Mode varchar(20),@ClosingAmount float 
 )
 AS
	BEGIN
	SET NOCOUNT ON;
	IF(@InvestmentType=0)
		BEGIN
			UPDATE Mst_Account SET Op_Bal=@ClosingAmount WHERE Member_Code=@MemberCode AND Year_Code=@YearCode and AC_Code= @Ac_Type_Code
		END
	ELSE IF(@InvestmentType=1)
		BEGIN
			set @Ac_Type_Code =(SELECT   distinct(Ac_Code) AS 'Account Code'   FROM Mst_Account  where Ac_name='F & O SHARE TRADING A/C')

			UPDATE Mst_Account SET Op_Bal=@ClosingAmount 
			WHERE Member_Code=@MemberCode AND Year_Code=@YearCode and AC_Code= @Ac_Type_Code
		END
	ELSE IF(@InvestmentType=2)
		BEGIN
			set @Ac_Type_Code =(SELECT   distinct(Ac_Code) AS 'Account Code'   FROM Mst_Account  where Ac_name='MUTUAL FUND INVESTMENT A/C')
			UPDATE Mst_Account SET Op_Bal=@ClosingAmount WHERE Member_Code=@MemberCode AND Year_Code=@YearCode and AC_Code= @Ac_Type_Code
		END
	ELSE IF(@InvestmentType=3)
		BEGIN
			set @Ac_Type_Code =(SELECT   distinct(Ac_Code) AS 'Account Code'   FROM Mst_Account  where Ac_name='COMMODITY SHARE TRADING A/C')
			UPDATE Mst_Account SET Op_Bal=@ClosingAmount WHERE Member_Code=@MemberCode AND Year_Code=@YearCode and AC_Code= @Ac_Type_Code
		END
	ELSE IF(@InvestmentType=4)
		BEGIN
			set @Ac_Type_Code =(SELECT   distinct(Ac_Code) AS 'Account Code'   FROM Mst_Account  where Ac_name='CURRENCY SHARE TRADING A/C')
			UPDATE Mst_Account SET Op_Bal=@ClosingAmount WHERE Member_Code=@MemberCode AND Year_Code=@YearCode and AC_Code= @Ac_Type_Code
		END
	ELSE IF(@InvestmentType=5)
		BEGIN
			set @Ac_Type_Code =(SELECT   distinct(Ac_Code) AS 'Account Code'   FROM Mst_Account  where Ac_name='NCDEX SHARE TRADING A/C')
			UPDATE Mst_Account SET Op_Bal=@ClosingAmount WHERE Member_Code=@MemberCode AND Year_Code=@YearCode and AC_Code= @Ac_Type_Code
		END
	END
	-- select * from Mst_Account	 where AC_Name like 'cu%'
	--select * from Ent_EntryTypes



















GO
/****** Object:  StoredProcedure [dbo].[proc_FamilyWiseAccountLedger]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_FamilyWiseAccountLedger]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_FamilyWiseAccountLedger] AS' 
END
GO
ALTER PROCEDURE [dbo].[proc_FamilyWiseAccountLedger]
@Fromdate VARCHAR(20),
@Todate VARCHAR(20),
@Membercode VARCHAR(Max),
@Yearcode VARCHAR(20),
@Familycode VARCHAR(Max),
@Accountcode VARCHAR(Max),
@Mode VARCHAR(50)	
AS
BEGIN
	IF(@Mode='MemberAndFamily')
		BEGIN
		SET NOCOUNT ON;
			SELECT M.Member_Name, FM.Family_Name FROM AC_Trans AT 
			LEFT JOIN Mst_Member M ON M.Member_Code=AT.Member_Code
			LEFT JOIN Mst_Family FM ON FM.Family_Code=M.Family_Code
			WHERE AT.Member_Code=@Membercode and AT.Year_Code=@Yearcode
			GROUP BY M.Member_Name, FM.Family_Name
		END
	ELSE IF(@Mode='All')
		BEGIN
			SELECT BrokerBill_Trans.ID,Script_Name,
			(CASE WHEN Bill_no='Opening' and FrmNm!='BB' AND BrokerBill_Trans.Trans_Dt<@Fromdate and YearCode=@yearcode 
			THEN CONVERT(VARCHAR(20), BrokerBill_Trans.Trans_Dt, 103) ELSE '' END) AS [Opening Date],Ac_Type,
			SUM(CASE WHEN Bill_no = 'Opening'  AND FrmNm != 'BB' AND BrokerBill_Trans.Trans_Dt < @Fromdate  THEN Qty ELSE 0 END) AS [Opening Qty],
			SUM(CASE WHEN Bill_no = 'Opening'  AND FrmNm != 'BB' AND BrokerBill_Trans.Trans_Dt < @Fromdate  THEN Rate ELSE 0 END) AS [Opening Rate],
			SUM(CASE WHEN Bill_no = 'Opening'  AND Frmnm != 'BB' AND BrokerBill_Trans.Trans_Dt < @Fromdate  THEN Amount ELSE 0 END) AS [Opening Amount],

			(CASE WHEN TransType='Bought' AND Frmnm != 'op' AND Frmnm != 'IPO' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN  CONVERT(varchar(20), BrokerBill_Trans.Trans_Dt, 103) ELSE '' END) AS [Purhase Date], 
			(CASE WHEN TransType='Bought' AND Frmnm != 'op' AND Frmnm != 'IPO' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Bill_no ELSE '' END) AS [Purchase_Bill_No],
			(CASE WHEN TransType='Bought' AND Frmnm != 'op' AND Frmnm != 'IPO' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Qty ELSE 0 END) AS [Purchase Qty],
			(CASE WHEN TransType='Bought' AND Frmnm != 'op' AND Frmnm != 'IPO' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Rate ELSE 0 END) AS [Purchase Rate],
			(CASE WHEN TransType='Bought' AND Frmnm != 'op' AND Frmnm != 'IPO' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Amount ELSE 0 END) AS [Purchase Amount],

			(CASE WHEN TransType='Bought' AND Bill_no = 'Bonus' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN  CONVERT(varchar(20), BrokerBill_Trans.Trans_Dt, 103) ELSE '' END) AS [Bonus Date], 
			(CASE WHEN TransType='Bought' AND Bill_no = 'Bonus' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Bill_no ELSE '' END) AS [Bonus_Bill_No],
			(CASE WHEN TransType='Bought' AND Bill_no = 'Bonus' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Qty ELSE 0 END) AS [Bonus Qty],
			(CASE WHEN TransType='Bought' AND Bill_no = 'Bonus' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Rate ELSE 0 END) AS [Bonus Rate],
			(CASE WHEN TransType='Bought' AND Bill_no = 'Bonus' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Amount ELSE 0 END) AS [Bonus Amount],
						
			(CASE WHEN TransType='Bought' AND Bill_no = 'Rights' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN  CONVERT(varchar(20), BrokerBill_Trans.Trans_Dt, 103) ELSE '' END) AS [Rights Date], 
			(CASE WHEN TransType='Bought' AND Bill_no = 'Rights' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Bill_no ELSE '' END) AS [Rights_Bill_No],
			(CASE WHEN TransType='Bought' AND Bill_no = 'Rights' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Qty ELSE 0 END) AS [Rights Qty],
			(CASE WHEN TransType='Bought' AND Bill_no = 'Rights' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Rate ELSE 0 END) AS [Rights Rate],
			(CASE WHEN TransType='Bought' AND Bill_no = 'Rights' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Amount ELSE 0 END) AS [Rights Amount],
					   
			(CASE WHEN TransType='Bought' AND Frmnm = 'IPO' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN  CONVERT(varchar(20), BrokerBill_Trans.Trans_Dt, 103) ELSE '' END) AS [IPO Date], 
			(CASE WHEN TransType='Bought' AND Frmnm = 'IPO' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Bill_no ELSE '' END) AS [IPO_No],
			(CASE WHEN TransType='Bought' AND Frmnm = 'IPO' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Qty ELSE 0 END) AS [IPO Qty],
			(CASE WHEN TransType='Bought' AND Frmnm = 'IPO' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Rate ELSE 0 END) AS [IPO Rate],
			(CASE WHEN TransType='Bought' AND Frmnm = 'IPO' AND BrokerBill_Trans.Trans_Dt >= @Fromdate AND BrokerBill_Trans.Trans_Dt <= @Todate THEN Amount ELSE 0 END) AS [IPO Amount],
			'' 'BSE_OR_NSE_Code', Mst_Consultant.Consultant_Name,''BSE_Rate,''NSE_Rate
			FROM BrokerBill_Trans 
			JOIN Mst_Script ON Mst_Script.Script_Code=BrokerBill_Trans.Script_Code 
			JOIN Mst_Consultant ON Mst_Consultant.Consultant_Code =BrokerBill_Trans.Consultant_code
			--JOIN DailyRate D ON D.Script_Code= BrokerBill_Trans.Script_Code 
			WHERE  TransType='Bought' 
			and BrokerBill_Trans.Member_code=@Membercode and YearCode=@yearcode  
			GROUP BY BrokerBill_Trans.ID,Bill_no,Script_Name,BrokerBill_Trans.Trans_Dt,TransType,FrmNm,YearCode,BrokerBill_Trans.Qty,BrokerBill_Trans.Rate,BrokerBill_Trans.Amount,Ac_Type
			,Mst_Script.BSE_Code,Mst_Script.NSE_Code,Mst_Consultant.Consultant_Name 
			ORDER BY BrokerBill_Trans.Trans_Dt 
		END
END
























GO
/****** Object:  StoredProcedure [dbo].[proc_Get_AllCodes]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Get_AllCodes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Get_AllCodes] AS' 
END
GO




ALTER procedure [dbo].[proc_Get_AllCodes]
@Param1 VARCHAR(20),
@Param2 VARCHAR(20),
@mode VARCHAR(100) 
AS
BEGIN
	/*For SHARE INVESTMENT (EQUITY) A/C Code*/
	IF(@mode='Share_Inv_EQ_AC')
		BEGIN
		SET NOCOUNT ON;
			SELECT Ac_Code AS 'Account Code',Ac_Name as 'Account Name'     FROM InternalAccountMaster  WHERE Ac_Name='SHARE INVESTMENT (EQUITY) A/C' AND isactive=1 
		END


/*For SHARE INVESTMENT (EQUITY) A/C and TRADING A/C Names*/
	ELSE IF(@mode='Share_Inv_Trad_AC_Name')
		BEGIN
			SELECT 'All' Ac_Name,0 AS 'Account Code'    
			
			UNION
			
			SELECT  Ac_Name,Ac_Code AS 'Account Code'   FROM InternalAccountMaster  
			WHERE Ac_Name in('SHARE INVESTMENT (EQUITY) A/C','SHARE TRADING A/C') AND isactive=1 
			
		END
/*For SHARE INVESTMENT (EQUITY) A/C and TRADING A/C Names For Insert into Account Settings Table While Financial Year Add*/
	ELSE IF(@mode='Share_Inv_Trad_AC_Name_AcSettings')
		BEGIN			 		
			SELECT  Member_Code,Year_Code,Ac_Name,Ac_Code AS 'Account Code',1   FROM InternalAccountMaster  
			WHERE Ac_Name in('SHARE INVESTMENT (EQUITY) A/C','SHARE TRADING A/C') AND isactive=1 
			
		END
		/*For SHARE TRADING A/C Open Position*/
		ELSE IF(@mode='Share_Trad_AC_Open_Position')
		BEGIN
			SELECT Ac_Code AS 'Account Code',Ac_Name as 'Account Name'    FROM InternalAccountMaster  WHERE Ac_Name='F&O SHARE TRADING OPEN POSITION' AND isactive=1  
		END
	
	/*For SHARE TRADING A/C*/
	ELSE IF(@mode='Share_Trad_AC')
		BEGIN
			SELECT Ac_Code AS 'Account Code',Ac_Name as 'Account Name'    FROM InternalAccountMaster  WHERE Ac_Name='SHARE TRADING A/C' AND isactive=1  
		END
	
	ELSE IF(@mode='Share_Purchase_Trading_A/c' )
	     BEGIN
		       SELECT Ac_Code AS 'Account Code',Ac_Name as 'Account Name'    FROM InternalAccountMaster  WHERE Ac_Name='SHARE PURCHASE TRADING A/C' AND isactive=1  
		 END

    ELSE IF(@mode='Share_Sale_Trading_A/c')
	     BEGIN
		       SELECT Ac_Code AS 'Account Code',Ac_Name as 'Account Name'    FROM InternalAccountMaster  WHERE Ac_Name='SHARE SALE TRADING A/C' AND isactive=1  
		 END
     
    ELSE IF(@mode='STOCK_IN_TRADE_EQUITY_A/C')
	     BEGIN
		       SELECT Ac_Code AS 'Account Code',Ac_Name as 'Account Name'    FROM InternalAccountMaster  WHERE Ac_Name='STOCK IN TRADE (EQUITY) A/C' AND isactive=1  
		 END
	/*For F & O SHARE TRADING A/C Code*/
	ELSE IF(@mode='FandO_SHARE_Trad_AC')
		BEGIN
			SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='F & O SHARE TRADING A/C' AND isactive=1  
		END

    ELSE IF(@mode='InvestmentType')
	     BEGIN
		        SELECT Sr_No AS 'Account Code',Entry_Type as 'Account Name' from Ent_EntryTypes where Sr_no='0'
		 END
	ELSE IF(@mode='Opening_Stock_Equity' )
	     BEGIN
		       SELECT Ac_Code AS 'Account Code',Ac_Name as 'Account Name'    FROM InternalAccountMaster  WHERE Ac_Name='OPENING STOCK (EQUITY)' AND isactive=1  
		 END
    ELSE IF(@mode='SECURITY_TRANSACTION_TAX_Ac')
	    BEGIN
		     SELECT Ac_Code AS 'Account Code',Ac_Name as 'Account Name'    FROM InternalAccountMaster  WHERE Ac_Name='SECURITY TRANSACTION TAX' AND isactive=1  
	    END
     ELSE IF(@mode='PNL_Ac')
	    BEGIN
		     SELECT Ac_Code AS 'Account Code',Ac_Name as 'Account Name'    FROM InternalAccountMaster  WHERE Ac_Name='PROFIT/LOSS A/C' AND isactive=1  
	    END
	ELSE IF(@mode='Currency_FD')
		BEGIN
			SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='CURRENCY FIXED.DEPOSIT A/C.' AND isactive=1  
		END
	
	ELSE IF(@mode='Roundoff_AC')
		BEGIN
			SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='ROUND OFF A/C' AND isactive=1  
		END	
		
	ELSE IF(@mode='Stock_In_Trade')
		BEGIN
			SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='STOCK IN TRADE (EQUITY) A/C' AND isactive=1  
		END	

	ELSE IF(@mode='CAPITAL_GAIN_LOSS')
		BEGIN
			SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='CAPITAL GAIN/LOSS(P&L)' AND isactive=1  
		END	
		
	ELSE IF(@mode='PROFIT_LOSS_AC')
		BEGIN
			SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='PROFIT/LOSS A/C' AND isactive=1  
		END	
		
	ELSE IF(@mode='FO_SHARE_LOSS')
	    BEGIN
	        SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='F&O EQ DERIVATIVE(LOSS)' AND isactive=1  
	    END	
	
	ELSE IF(@mode='MCX_SHARE_LOSS')
	    BEGIN
	        SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='F&O COMMODITY DERIVATIVE(LOSS)' AND isactive=1  
	    END	

	ELSE IF(@mode='FO_SHARE_PROFIT')
	    BEGIN
	        SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='F&O EQ DERIVATIVE(PROFIT)' AND isactive=1  
	    END	

	ELSE IF(@mode='MCX_SHARE_PROFIT')
	    BEGIN
	        SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='F&O COMMODITY DERIVATIVE(PROFIT)' AND isactive=1  
	    END	
	/*For COMMODITY SHARE TRADING A/C Code*/
	ELSE IF(@mode='Comm_Share_Trad_AC')
		BEGIN
			SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='COMMODITY SHARE TRADING A/C' AND isactive=1  
		END
		/*  CURRENCY SHARE LOSS*/
    ELSE IF(@mode='Currency_Share_Loss')
	    BEGIN
	        SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='F&O CURRENCY DERIVATIVE (LOSS)' AND isactive=1  
	    END	
		/*  CURRENCY SHARE PROFIT*/
	 ELSE IF(@mode='Currency_Share_Profit')
	    BEGIN
	        SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='F&O CURRENCY DERIVATIVE(PROFIT)' AND isactive=1  
	    END	
		/*  NCDEX SHARE LOSS*/
	 ELSE IF(@mode='NCDEX_Share_Loss')
	    BEGIN
	        SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='NCDEX (LOSS)' AND isactive=1  
	    END	
		/*  NCDEX SHARE PROFIT*/
	 ELSE IF(@mode='NCDEX_Share_Profit')
	    BEGIN
	        SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='NCDEX (PROFIT)' AND isactive=1  
	    END	
  /* NCDEX SHARE TRADING A/C Code*/

  ELSE IF(@mode='GL_Ncdex_Share_Trad_AC')
		BEGIN
			SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='NCDEX SHARE TRADING A/C' AND isactive=1  
		END
	
	/*For CURRENCY SHARE TRADING A/C Code*/
	ELSE IF(@mode='Curr_Share_Trad_AC')
		BEGIN
			SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='CURRENCY SHARE TRADING A/C' AND isactive=1
		END

	/*For AUTO BROKEGE A/C Code*/
	ELSE IF(@mode='DEF_DEMAT_AC')
		BEGIN
			SELECT DP_Code AS 'Demat Code'  FROM InternalDematMaster  WHERE DP_Name='DEFAULT DEMAT A/C' --AND isactive=1
		END
	ELSE IF(@mode='DEF_DEMAT_AC_All')
		BEGIN
			SELECT DP_Code  AS 'Demat Code',DP_Name AS 'Demat Name'  FROM InternalDematMaster  WHERE DP_Name='DEFAULT DEMAT A/C' --AND isactive=1
		END
	/*For SELF CONSULTANT Code*/
	ELSE IF(@mode='SelfConsultant')
		BEGIN
			SELECT Consultant_Code AS 'Consultant Code'  FROM InternalConsultantMaster WHERE Consultant_Name='SELF CONSULTANT'
		END
	ELSE IF(@mode='SelfConsultant_All')
		BEGIN
			SELECT  Consultant_Code AS 'Consultant Code',Consultant_Name AS 'Consultant Name'  FROM InternalConsultantMaster WHERE Consultant_Name='SELF CONSULTANT'
		END	
	/*For MUTUAL FUND INVESTMENT A/C Code*/
	ELSE IF(@mode='Mutual_Fund_Inv_AC')
		BEGIN
			SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='MUTUAL FUND INVESTMENT A/C' AND isactive=1
		END
	
	/*For SELF-BROKER A/C Code*/
	ELSE IF(@mode='SelfBroker_AC')
		BEGIN
			SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='SELF-BROKER A/C' AND isactive=1
		END

	ELSE IF(@mode='stock_in_trade')
		BEGIN
			SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='STOCK IN TRADE (EQUITY) A/C' AND isactive=1
		END
   ELSE IF(@mode='Closing_Stock_In_Trade')
   BEGIN
         SELECT Ac_Code AS 'Account Code'  FROM InternalAccountMaster  WHERE Ac_Name='CLOSING (STOCK IN TRADE)' AND isactive=1
   END
	ELSE IF(@mode='Investment_Types')
		BEGIN
			SELECT * from Ent_EntryTypes
		END
	ELSE IF(@mode='AutoJVCode')
		BEGIN
			SELECT Ac_code,AC_Name from InternalAccountMaster where ac_code in('1100035','1100036','1100017','1100015','1100101','1100100','1100102','1100014','1100010','1100024','1100050','1100051')
			Order by Ac_code

			--SELECT Ac_code,AC_Name from InternalAccountMaster 
		END
	ELSE IF(@mode='ROUNDOFFACC')
		BEGIN
			SELECT Ac_code AS 'Account Code',AC_Name from InternalAccountMaster where Ac_Name ='ROUND OFF A/C'
			--SELECT Ac_code,AC_Name from InternalAccountMaster 
		END

	ELSE IF(@mode='Acc_CodesOn_BrokerEntryFrm')
		BEGIN
			SELECT  AC_Code,Ac_Name FROM InternalAccountMaster 
			WHERE ac_name in('Share Investment (equity) A/c','STOCK IN TRADE (EQUITY) A/C','F & O SHARE TRADING A/C','Commodity Share Trading A/c','Round OFF A/c','NCDEX Share Trading A/c')
		END

	ELSE IF(@mode='SHARE APPLICATION A/C')
		BEGIN
			SELECT  distinct AC_Code,Ac_Name FROM MSt_Account
			WHERE ac_name = 'SHARE APPLICATION A/C'
		END
   ELSE IF(@mode='BUYBACK ENTRY')
   BEGIN
   SELECT  Ac_Name,Ac_Code AS 'Account Code'   FROM InternalAccountMaster  
			WHERE Ac_Name in('SHARE INVESTMENT (EQUITY) A/C','SHARE TRADING A/C') AND isactive=1 
			
   END
	--select * from InternalAccountMaster where AC_Code='110026' 
END		























GO
/****** Object:  StoredProcedure [dbo].[proc_getInternalData]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_getInternalData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_getInternalData] AS' 
END
GO
--[proc_getInternalData] 'A0001','1120182019','','getexternalConsultant'
ALTER PROCEDURE [dbo].[proc_getInternalData] --'A0001','1120182019','','proc_getInternalData'
@memcode VARCHAR(Max),
@yearcode VARCHAR(20),
@parem1 VARCHAR(20),
@mode VARCHAR(100)
AS
BEGIN
SET NOCOUNT ON;
	DECLARE @val1 VARCHAR(20)
	DECLARE @val2 VARCHAR(20)
	DECLARE @val3 VARCHAR(100)
	SET @val1 = SUBSTRING(@yearcode, 3, 4); 
	SET @val2 = SUBSTRING(@yearcode, 7, 4); 
	SET @val1 = CONVERT(INT,@val1)-1
	SET @val2 = CONVERT(INT,@val2)-1
	SET @val3='11'+ CONVERT(VARCHAR(100),@val1+@val2)

	IF(@mode='getInternalInvestment')
		BEGIN
			SELECT Member_Code,Year_Code,Investment_Code,Investment_Name,InternalEntry FROM InternalInvestmentMaster WHERE isactive=1
		END
	ElSE IF(@mode='getInternalDemat')
		BEGIN
			SELECT Member_Code,Year_Code,DP_Code,DP_Name,InternalEntry FROM  InternalDematMaster WHERE isactive=1
		END
	ElSE IF(@mode='getInternalConsultant')
		BEGIN
			SELECT '' 'member_code','' 'year_code',Consultant_Code,Consultant_Name,InternalEntry  FROM  InternalConsultantMaster WHERE isactive=1
		END

	ELSE IF(@mode='getexternalConsultant')
		BEGIN
			--SET @val1 = SUBSTRING(@yearcode, 3, 4); 
			--SET @val2 = SUBSTRING(@yearcode, 7, 4); 
			--SET @val1 = CONVERT(INT,@val1)-1
			--SET @val2 = CONVERT(INT,@val2)-1
			--SET @val3='11'+ CONVERT(VARCHAR(100),@val1+@val2)
			--6select @val3
			SELECT member_code,year_code,Consultant_Code,Consultant_Name,InternalEntry FROM  Mst_Consultant --WHERE member_code=@memcode and year_code=@val3
		END

	ELSE IF(@mode='getexternalinvestment')
		BEGIN
			--SET @val1 = SUBSTRING(@yearcode, 3, 4); 
			--SET @val2 = SUBSTRING(@yearcode, 7, 4); 
			--SET @val1 = CONVERT(INT,@val1)-1
			--SET @val2 = CONVERT(INT,@val2)-1
			--SET @val3='11'+ CONVERT(VARCHAR(100),@val1+@val2)
			SELECT * FROM Mst_Investment WHERE Member_Code=@memcode AND  year_code=@val3
		END

	ELSE if (@mode='GetExternalDemat')
		BEGIN
			--SET @val1 = SUBSTRING(@yearcode, 3, 4); 
			--SET @val2 = SUBSTRING(@yearcode, 7, 4); 
			--SET @val1 = CONVERT(INT,@val1)-1
			--SET @val2 = CONVERT(INT,@val2)-1
			--SET @val3='11'+ CONVERT(VARCHAR(100) , @val1 + @val2)
			SELECT * FROM Mst_Demat WHERE Member_Code=@memcode AND  year_code=@val3
		END
		
	ElSE IF(@mode='getInternal_Ac_Settings')
		BEGIN
			--EXEC [proc_Get_AllCodes] ''  ,'' ,'Share_Inv_Trad_AC_Name_AcSettings' 
			SELECT  '' Member_Code,Year_code,AC_Name 'Description',AC_Code,InternalEntry   from InternalAccountMaster
			WHERE Ac_Name in('SHARE INVESTMENT (EQUITY) A/C','SHARE TRADING A/C') AND isactive=1 
		END

	ELSE IF(@mode='GetExternal_Ac_Settings')
		BEGIN
			SELECT  *  FROM AC_Settings WHERE Member_Code = @memcode AND year_code=@val3
		END
    ELSE IF(@mode='Get_Brokerage_Master')
	     BEGIN
		     SELECT  *  FROM Brokerage_Master WHERE Member_Code = @memcode AND year_code=@val3
		 END
    ELSE IF(@mode='Get_Expense_Mapping')
	     BEGIN
	         SELECT  *  FROM BrokerBill_Format_Expense WHERE Member_code = @memcode AND year_code=@val3
	     END
END























GO
/****** Object:  StoredProcedure [dbo].[proc_getInvestmentType]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_getInvestmentType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_getInvestmentType] AS' 
END
GO
ALTER PROCEDURE [dbo].[proc_getInvestmentType] 
AS
BEGIN
SET NOCOUNT ON;
	SELECT * FROM Ent_EntryTypes
END























GO
/****** Object:  StoredProcedure [dbo].[Proc_GetShortCutKeysData]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_GetShortCutKeysData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_GetShortCutKeysData] AS' 
END
GO
ALTER PROCEDURE [dbo].[Proc_GetShortCutKeysData]
as
BEGIN
SET NOCOUNT ON;
	select KeyName,Description from [dbo].[Shortkeys]
END












GO
/****** Object:  StoredProcedure [dbo].[proc_InsertBrokerageMaster]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_InsertBrokerageMaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_InsertBrokerageMaster] AS' 
END
GO


ALTER PROCEDURE [dbo].[proc_InsertBrokerageMaster]
  @dt AS dbo.BrokerageDataTable READONLY,
  @memcode varchar(Max),
  @yearcode varchar(100),
  @accode varchar(Max),
  @mode varchar(100)
AS
BEGIN
SET NOCOUNT ON;	
	 	
if(@mode='current')
  BEGIN
	 
		IF EXISTS(SELECT 1 FROM Brokerage_Master WHERE Member_Code= @memcode and Year_Code=@yearcode)
			BEGIN
				DELETE FROM Brokerage_Master  WHERE Member_Code= @memcode and Year_Code=@yearcode
			END
		  --ALTER TABLE Mst_Demat REBUILD WITH (IGNORE_DUP_KEY = ON);
		  --alter table Mst_Demat drop CONSTRAINT [IX_DP_Master]
			INSERT into  Brokerage_Master  SELECT *   FROM @dt;
			--alter table Mst_Demat add CONSTRAINT [IX_DP_Master]
			--PRIMARY KEY CLUSTERED ([DP_Code]);
			select '1' as 'success'
	END
	ELSE IF(@mode='previous')
	BEGIN
		 
	 IF EXISTS(SELECT 1 FROM Brokerage_Master WHERE Member_Code= @memcode and Year_Code=@yearcode)
		BEGIN
			DELETE FROM Brokerage_Master  WHERE Member_Code= @memcode and Year_Code=@yearcode
		END

		INSERT  INTO  Brokerage_Master  SELECT *  FROM @dt;
		 
		SELECT '1' AS 'success'
	 	
	END
END

 




























GO
/****** Object:  StoredProcedure [dbo].[proc_InsertExpenseMapping]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_InsertExpenseMapping]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_InsertExpenseMapping] AS' 
END
GO


ALTER PROCEDURE [dbo].[proc_InsertExpenseMapping]
  @dt AS dbo.BrokerBill_Format_Expense READONLY,
  @memcode varchar(Max),
  @yearcode varchar(100),
  @accode varchar(Max),
  @mode varchar(100)
AS
BEGIN
SET NOCOUNT ON;	
	 	
if(@mode='current')
  BEGIN
	 
		IF EXISTS(SELECT 1 FROM BrokerBill_Format_Expense WHERE Member_Code= @memcode and Year_Code=@yearcode)
			BEGIN
				DELETE FROM BrokerBill_Format_Expense  WHERE Member_Code= @memcode and Year_Code=@yearcode
			END
		  --ALTER TABLE Mst_Demat REBUILD WITH (IGNORE_DUP_KEY = ON);
		  --alter table Mst_Demat drop CONSTRAINT [IX_DP_Master]
			INSERT into  BrokerBill_Format_Expense  SELECT *   FROM @dt;
			--alter table Mst_Demat add CONSTRAINT [IX_DP_Master]
			--PRIMARY KEY CLUSTERED ([DP_Code]);
			select '1' as 'success'
	END
	ELSE IF(@mode='previous')
	BEGIN
		 
	 IF EXISTS(SELECT 1 FROM BrokerBill_Format_Expense WHERE Member_Code= @memcode and Year_Code=@yearcode)
		BEGIN
			DELETE FROM BrokerBill_Format_Expense  WHERE Member_Code= @memcode and Year_Code=@yearcode
		END

		INSERT  INTO  BrokerBill_Format_Expense  SELECT *  FROM @dt;
		 
		SELECT '1' AS 'success'
	 	
	END
END


GO
/****** Object:  StoredProcedure [dbo].[Proc_InsertFinancialYearEntries]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_InsertFinancialYearEntries]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_InsertFinancialYearEntries] AS' 
END
GO
 
ALTER PROCEDURE [dbo].[Proc_InsertFinancialYearEntries] 
@memcode VARCHAR(Max),
@yearcode VARCHAR(50),
@mode VARCHAR(200)
AS
BEGIN
SET NOCOUNT ON;
	
		DECLARE @val1 VARCHAR(20)--,@yearcode VARCHAR(50)
		--SET @yearcode='1120182019'
			DECLARE @val2 VARCHAR(20)
			DECLARE @val3 VARCHAR(100)
			SET @val1 = SUBSTRING(@yearcode, 3, 4); 
			SET @val2 = SUBSTRING(@yearcode, 7, 4); 
			--SET @val1=CONVERT(INT,@val1)-1
			--SET @val2=CONVERT(INT,@val2)-1
			--set @val1=@val1+1
			SET @val3='11'+ CONVERT(VARCHAR(100),@val1+@val2)
			SET @val3='11'+ CONVERT(VARCHAR(100),@val1+@val2)
			SET @val1= @val1 +  '-04-01'  
			SET @val2=  @val2 +'-03-31'  

			select @val1,@val2
			--select * from mst_year
	IF(@mode='save')
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM [Mst_Year] WHERE Member_Code = @memcode AND [Year_Code] = @yearcode AND [Period_FromDate] = @val1 AND [Period_ToDate] = @val1 )
			INSERT INTO[dbo].[Mst_Year]([Member_Code],[Year_Code],[Period_FromDate],[Period_ToDate])
			VALUES
			(
				@memcode,@yearcode,@val1,@val1
			)
		END
	 
END
























GO
/****** Object:  StoredProcedure [dbo].[proc_InsertInternal_External_Ac_Settings]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_InsertInternal_External_Ac_Settings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_InsertInternal_External_Ac_Settings] AS' 
END
GO
ALTER PROCEDURE [dbo].[proc_InsertInternal_External_Ac_Settings]
  @dt AS dbo.AccountDataTable READONLY,
  @memcode varchar(Max),
  @yearcode varchar(100),
  @accode  varchar(Max),
  @mode varchar(100)
AS
BEGIN
	
	SET NOCOUNT ON; 
	
if(@mode='current')
  BEGIN
	 
		IF EXISTS(SELECT 1 FROM AC_Settings WHERE Member_Code= @memcode and Year_Code=@yearcode)
			BEGIN
				DELETE FROM AC_Settings  WHERE Member_Code= @memcode and Year_Code=@yearcode
			END
			INSERT into  AC_Settings  SELECT *   FROM @dt;
			select '1' as 'success'
	END
	ELSE IF(@mode='previous')
		BEGIN
			 IF EXISTS(SELECT 1 FROM AC_Settings WHERE Member_Code= @memcode and Year_Code=@yearcode)
				BEGIN
					DELETE FROM AC_Settings  WHERE Member_Code= @memcode and Year_Code=@yearcode
				END
					INSERT  INTO  AC_Settings  SELECT *  FROM @dt;
					SELECT '1' AS 'success'
	END
END

 



























GO
/****** Object:  StoredProcedure [dbo].[proc_InsertInternalConsultant]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_InsertInternalConsultant]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_InsertInternalConsultant] AS' 
END
GO
ALTER PROCEDURE [dbo].[proc_InsertInternalConsultant]
  @dt AS dbo.DematDataTable READONLY,
  @memcode varchar(Max),
  @yearcode varchar(100),
  @accode varchar(Max),
  @mode varchar(100)
AS
BEGIN
	SET NOCOUNT ON;
	 
	
if(@mode='current')
  BEGIN
		IF EXISTS(SELECT 1 FROM Mst_Consultant WHERE year_code=@yearcode AND member_code=@memcode)
			BEGIN
				DELETE FROM Mst_Consultant WHERE  year_code=@yearcode AND member_code=@memcode
			END
			INSERT into  Mst_Consultant  SELECT *   FROM @dt;
			SELECT '1' AS 'success'
	END
	ELSE IF(@mode='previous')
	BEGIN
		IF EXISTS(SELECT 1 FROM Mst_Consultant WHERE year_code=@yearcode AND member_code=@memcode)
			BEGIN
				DELETE FROM Mst_Consultant WHERE  year_code=@yearcode AND member_code=@memcode
			END
		INSERT  into  Mst_Consultant  SELECT *   FROM @dt;
		SELECT '1' AS 'success'
	END
END

 



























GO
/****** Object:  StoredProcedure [dbo].[proc_InsertInternalDemat]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_InsertInternalDemat]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_InsertInternalDemat] AS' 
END
GO
ALTER PROCEDURE [dbo].[proc_InsertInternalDemat]
  @dt AS dbo.DematDataTable READONLY,
  @memcode varchar(Max),
  @yearcode varchar(100),
  @accode varchar(Max),
  @mode varchar(100)
AS
BEGIN
SET NOCOUNT ON;	
	 
	
if(@mode='current')
  BEGIN
	 
		IF EXISTS(SELECT 1 FROM Mst_Demat WHERE Member_Code= @memcode and Year_Code=@yearcode)
			BEGIN
				DELETE FROM Mst_Demat  WHERE Member_Code= @memcode and Year_Code=@yearcode
			END
		  --ALTER TABLE Mst_Demat REBUILD WITH (IGNORE_DUP_KEY = ON);
		  --alter table Mst_Demat drop CONSTRAINT [IX_DP_Master]
			INSERT into  Mst_Demat  SELECT *   FROM @dt;
			--alter table Mst_Demat add CONSTRAINT [IX_DP_Master]
			--PRIMARY KEY CLUSTERED ([DP_Code]);
			select '1' as 'success'
	END
	ELSE IF(@mode='previous')
	BEGIN
		 
	 IF EXISTS(SELECT 1 FROM Mst_Demat WHERE Member_Code= @memcode and Year_Code=@yearcode)
		BEGIN
			DELETE FROM Mst_Demat  WHERE Member_Code= @memcode and Year_Code=@yearcode
		END

		INSERT  INTO  Mst_Demat  SELECT *  FROM @dt;
		 
		SELECT '1' AS 'success'
	 	
	END
END

 



























GO
/****** Object:  StoredProcedure [dbo].[Proc_InsertInternalExternalEntries]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_InsertInternalExternalEntries]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_InsertInternalExternalEntries] AS' 
END
GO
ALTER PROCEDURE [dbo].[Proc_InsertInternalExternalEntries]
@memcode VARCHAR(Max),
@yearcode VARCHAR(50),
@mode VARCHAR(200)
AS
BEGIN
SET NOCOUNT ON;
	DECLARE @val1 VARCHAR(20)
			DECLARE @val2 VARCHAR(20)
			DECLARE @val3 VARCHAR(100)
			SET @val1 = SUBSTRING(@yearcode, 3, 4); 
			SET @val2 = SUBSTRING(@yearcode, 7, 4); 
			SET @val1 = CONVERT(INT,@val1)-1
			SET @val2 = CONVERT(INT,@val2)-1
			SET @val3 = '11'+ CONVERT(VARCHAR(100),@val1+@val2)
	IF(@mode='consultant_internal')
		BEGIN
			
			IF((SELECT Count(*) From Mst_Consultant Where InternalEntry = 1) = 0)
				BEGIN 
					INSERT INTO Mst_Consultant(Consultant_Code,Consultant_Name,InternalEntry) 
					SELECT Consultant_Code,Consultant_Name,1 FROM InternalConsultantMaster
				END
		END
	--ELSE IF(@mode='consultant_External')
	--	BEGIN
	--			IF((SELECT Count(*) From Mst_Consultant Where InternalEntry = 0) = 0)
	--				BEGIN 
	--					INSERT INTO Mst_Consultant(Consultant_Code,Consultant_Name,InternalEntry)  
	--					(SELECT Consultant_Code,Consultant_Name,0 FROM Mst_Consultant)
	--				END
	--	END
	ELSE IF(@mode='Account_Opening_External')
		BEGIN
			IF   EXISTS(SELECT 1 FROM [Mst_Account_Opening] WHERE member_code=@memcode AND  year_code=@yearcode)
				BEGIN
					delete FROM [Mst_Account_Opening] WHERE member_code=@memcode AND  year_code=@yearcode
				END
					INSERT INTO[dbo].[Mst_Account_Opening] 
					([Member_Code], [Year_Code], [AC_Code], [Op_Bal], [Op_Cal], [cl_bl], [cl_calc], [InternalEntry]) 
					SELECT @memcode,@yearcode,[AC_Code],[Op_Bal],[Op_Cal],0,0,[InternalEntry]
					FROM [Mst_Account]  WHERE Member_Code=@memcode and year_code=@val3
		END
	ELSE IF(@mode='Account_Opening_Internal')
		BEGIN
			IF   EXISTS(SELECT 1 FROM [Mst_Account_Opening] WHERE member_code=@memcode AND  year_code=@yearcode)
				BEGIN
					delete FROM [Mst_Account_Opening] WHERE member_code=@memcode AND  year_code=@yearcode
				END

					INSERT INTO[dbo].[Mst_Account_Opening] 
					([Member_Code], [Year_Code], [AC_Code], [Op_Bal], [Op_Cal], [cl_bl], [cl_calc], [InternalEntry]) 
					SELECT @memcode,@yearcode,[AC_Code],[Op_Bal],[Op_Cal],0,0,InternalEntry
					FROM [dbo].[InternalAccountMaster]  where InternalEntry=1
	
		END
END
























GO
/****** Object:  StoredProcedure [dbo].[proc_InsertInternalInvestment]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_InsertInternalInvestment]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_InsertInternalInvestment] AS' 
END
GO
ALTER PROCEDURE [dbo].[proc_InsertInternalInvestment]
  @dt AS dbo.InvestMentDataTable READONLY,
  @memcode varchar(Max),
  @yearcode varchar(100),
  @accode varchar(Max),

  @mode varchar(100)
AS
BEGIN
SET NOCOUNT ON;
	DECLARE @val1 varchar(20)
	DECLARE @val2 varchar(20)
	DECLARE @val3 varchar(100)

if(@mode='current')
  BEGIN
		if exists(select 1 from Mst_Investment where Member_Code=@memcode and Year_Code=@yearcode)
			BEGIN
				 delete from Mst_Investment where Member_Code=@memcode and Year_Code=@yearcode
			END
	  --ALTER TABLE Mst_Investment REBUILD WITH (IGNORE_DUP_KEY = ON);
	  -- alter table Mst_Investment drop CONSTRAINT PK_Investment_Master
		INSERT Mst_Investment  SELECT *   FROM @dt;
		--alter table Mst_Investment add CONSTRAINT PK_Investment_Master
		--PRIMARY KEY CLUSTERED ([Investment_Code]);
				select '1' as 'success'

	END
	ELSE IF(@mode='previous')
	BEGIN
		if exists(select 1 from Mst_Investment where Member_Code=@memcode and Year_Code=@yearcode)
			BEGIN
				 delete from Mst_Investment where Member_Code=@memcode and Year_Code=@yearcode
			END
		--alter table Mst_Investment drop CONSTRAINT [PK_Investment_Master]
		--ALTER TABLE [Mst_Investment] REBUILD WITH (IGNORE_DUP_KEY = ON);
		INSERT Mst_Investment  SELECT *   FROM @dt;
		select '1' as 'success'

	END

	 
END

 



























GO
/****** Object:  StoredProcedure [dbo].[proc_InsertMyDataTable]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_InsertMyDataTable]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_InsertMyDataTable] AS' 
END
GO

ALTER PROCEDURE [dbo].[proc_InsertMyDataTable]
  @dt AS dbo.MyDataTable READONLY,
  @memcode varchar(Max),
  @yearcode varchar(100),
  @accode varchar(Max),
  @mode varchar(100)

AS
BEGIN
SET NOCOUNT ON;
if(@mode='current')
  begin
  SET NOCOUNT ON;
		 ALTER TABLE [mst_account] REBUILD WITH (IGNORE_DUP_KEY = ON);
		 --alter table mst_account drop CONSTRAINT [PK_AC_Master]
		INSERT mst_account  SELECT *   FROM @dt;
		select '1' as 'success' 
		--------ALTER table mst_account
		--------ADD CONSTRAINT [PK_Mst_Account] PRIMARY KEY CLUSTERED (Member_Code, Year_Code, AC_Code)

END
	else if(@mode='previous')
	begin
		SET NOCOUNT ON;
		ALTER TABLE [mst_account] REBUILD WITH (IGNORE_DUP_KEY = ON);
		INSERT mst_account  SELECT *  FROM @dt;
		select '1' as 'success'
	END
	ELSE IF(@mode='checkpreviousentry')
		BEGIN
			DECLARE @val1 VARCHAR(20)
			DECLARE @val2 VARCHAR(20)
			DECLARE @val3 VARCHAR(100)
			SET @val1 = SUBSTRING(@yearcode, 3, 4); 
			SET @val2 = SUBSTRING(@yearcode, 7, 4); 
			SET @val1=CONVERT(INT,@val1)-1
			SET @val2=CONVERT(INT,@val2)-1
			SET @val3='11'+ CONVERT(VARCHAR(100),@val1+@val2)
			SELECT  count(*) as 'count',@val3 as 'val'  FROM mst_account WHERE Member_Code=@memcode and Year_Code=@val3
		END
END

 















GO
/****** Object:  StoredProcedure [dbo].[proc_MonthWise_StockholdingPosition_BrokerWise_Equity]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_MonthWise_StockholdingPosition_BrokerWise_Equity]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_MonthWise_StockholdingPosition_BrokerWise_Equity] AS' 
END
GO



--proc_StockholdingPosition_BrokerWise_Equity 0,0,'0','Y0001','1120172018','2017-04-01','2017-04-30','','','','0', '0' ,'0','Details'	

--proc_MonthWise_StockholdingPosition_BrokerWise_Equity 0,0,'0','Y0001','1120172018','2017-04-01','2018-03-28','','','0','0', '0' ,'0','Summary','0','0','0','1'	

--proc_MonthWise_StockholdingPosition_BrokerWise_Equity 0,0,'0','S0001','1120172018','2017-04-01','2018-03-28','','','','', '0' ,'2','details'	
			    
ALTER PROCEDURE [dbo].[proc_MonthWise_StockholdingPosition_BrokerWise_Equity] --0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','ScriptWiseTotal'
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@BrokerCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX),
@IsWithTax bit = 0,@RecordOnlyhavingClosingbalanceZero AS BIT = 0,@WithActualAvgRate AS BIT = 0, @DateWiseClosinStock AS BIT = 0,@IsBSEISIN bit=0)

AS 
  BEGIN 
  SET NOCOUNT ON;
		DECLARE @StartYearDate varchar(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101)

		CREATE TABLE #mainoutputtable_1_MonthWise_BrokerWise
        ( 
			pkid INT identity(1,1), 
			Dup_pkid int, 
			Broker_name VARCHAR(MAX),
			Trans_No VARCHAR(20),
			id INT,
			prioritys INT,
			Trans_Type  VARCHAR(50), 
			Split_Type VARCHAR(500), 
			Flag_Type VARCHAR(100),
			Flag_Type_Sold VARCHAR(100),
			flag_script_name  VARCHAR(Max),
			flag_holding_type VARCHAR(MAx), 
			script_name  VARCHAR(Max),
			holding_type VARCHAR(MAx), 
		    opening_bill_no VARCHAR(100),		    
			opening_date DATETIME,
			opening_qty  FLOAT DEFAULT 0,
			opening_rate  FLOAT DEFAULT 0,
			opening_amount AS( [opening_qty] * [opening_rate] ), 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount AS( purchase_qty * purchase_rate ), 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount AS ( sold_qty * sold_rate ), 
			gain_loss float,
			closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 
			closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
			closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
			short_term FLOAT DEFAULT 0,
			long_term  FLOAT DEFAULT 0,
			speculation  FLOAT DEFAULT 0,
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			dayscount FLOAT DEFAULT 0,
			isintradaycol INT,[type] VARCHAR(50),
			ScriptCode VARCHAR(50),
			MemberCode VARCHAR(50),
			MemberName VARCHAR(max)
        )  

		CREATE TABLE #mainoutputtable_Final_MonthWise_BrokerWise_ISINNO
		(
		   pkid int,
		   Dup_pkid int, 		 
           Broker_name VARCHAR(MAX),
		   Trans_No VARCHAR(20),
		   id INT,		   
		   prioritys INT,
		   Trans_Type  VARCHAR(50), 
		   Split_Type VARCHAR(500), 
		   Flag_Type VARCHAR(100),
		   Flag_Type_Sold VARCHAR(100),
		   flag_script_name  VARCHAR(Max),
		   flag_holding_type VARCHAR(MAx), 
		   script_name  VARCHAR(Max),
		   holding_type VARCHAR(MAx), 
		   opening_bill_no VARCHAR(100),		    
		   opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
		   purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
	   	   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
		   sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0,         
           gain_loss FLOAT DEFAULT 0,	  
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,[type] VARCHAR(50),	  
		   ScriptCode VARCHAR(50),
		   MemberCode VARCHAR(50),
		   MemberName VARCHAR(max)    
		)

		CREATE TABLE #mainoutputtable_1_Final__MonthWise_BrokerWise
        ( 
		   Dup_pkid int, 
		   OrderBy varchar(100),
           Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT   ,
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(100),
		   Flag_Type_Sold VARCHAR(100),
		   flag_script_name  VARCHAR(Max),
		   flag_holding_type VARCHAR(Max), 
		   script_name  VARCHAR(Max),
		   holding_type VARCHAR(Max), 
		   opening_bill_no VARCHAR(100),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   Broker_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(50),
		   sort   VARCHAR(5),
		   ScriptCode VARCHAR(50),
		   MemberCode VARCHAR(50),
		   MemberName VARCHAR(max)
        )

		CREATE TABLE #mainoutputtable_1_Final_Summary_Monthwise 
        ( 
           prioritys INT,Trans_No VARCHAR(50),ScriptCode  VARCHAR(50),id INT,MemberCode varchar(20),yearcode varchar(50), script_name  VARCHAR(500),holding_type VARCHAR(200),flag_script_name  VARCHAR(500),flag_holding_type VARCHAR(200),
           opening_date VARCHAR(50),opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
           purchase_date VARCHAR(50),purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
           sold_date VARCHAR(50),sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   Broker_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   Other_amt FLOAT DEFAULT 0,
		   ServTax_Amt FLOAT DEFAULT 0,
		   Stt_amt FLOAT DEFAULT 0,
		   sort   VARCHAR(5),
		   isintradaycol  INT 
        ) 

		CREATE TABLE #Openings
        (
		   id INT, 
		   Trans_No VARCHAR(20),
		   script_name  VARCHAR(Max),
		   script_Code  VARCHAR(50),
		   holding_type VARCHAR(Max),
		   bill_no VARCHAR(100),		     
           trans_dt Datetime,
		   qty  FLOAT DEFAULT 0,
		   rate  FLOAT DEFAULT 0,
		   amount FLOAT DEFAULT 0, 
           isintraday bit DEFAULT 0, 
		   Broker_Name  VARCHAR(100),
		   Member_Code varchar(20),
		   Member_Name varchar(100),
		   BillType varchar(20)
	   ) 

		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates DATETIME,@qty FLOAT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT  
		DECLARE @tablerowscount INT
		IF(@status = 0) 
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
				@openingDate DATETIME,@openingRate FLOAT,@openingQty FLOAT,@openingAmount FLOAT,
				@purchaseDate DATETIME,@PurchaseBillNo  VARCHAR(50),@purchaseRate FLOAT,@purchaseQty FLOAT,@purchaseAmount FLOAT,
				@soldDate DATETIME,@soldBillNo  VARCHAR(50),@soldRate FLOAT,@soldQty FLOAT,@soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50),@Broker_name  VARCHAR(100), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(10),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,@PurchaseIntraFlag VARCHAR(100),@SaleIntraFlag VARCHAR(10),@BillType varchar(20) 
				DECLARE @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@ScriptId VARCHAR(50),@Dup_pkid int, @Pkid varchar(200),@idcount int ,@Member_Code varchar(100), @Member_Name varchar(max)  

				CREATE TABLE #SCriptCodes_Monthwise_brokerwise
				(
					ScriptCode varchar(MAX)
				)

				IF(@ScriptCode != '')
					INSERT INTO #SCriptCodes_Monthwise_brokerwise 
					SELECT value FROM Fn_split(@ScriptCode, ',') 
				ELSE 
					INSERT INTO #SCriptCodes_Monthwise_brokerwise 
					SELECT MS.Script_Code 
					FROM mst_script MS join Brokerbill_trans bbt on bbt.Script_Code=MS.Script_code 
					group by MS.Script_Code

				CREATE TABLE #BrokerCodes_MonthWise
				(
					BrokerCodes varchar(MAX)
				)
				 
				IF(@BrokerCode != '')
					INSERT INTO #BrokerCodes_MonthWise SELECT value FROM Fn_split(@BrokerCode, ',') 
				ELSE 
					INSERT INTO #BrokerCodes_MonthWise SELECT BB .Broker_Code FROM brokerbill BB left join BrokerBill_Trans BBT 
					ON BBT.Trans_No=BBT.Trans_No AND BBT.Member_code=bb.Member_Code and bbt.YearCode=bb.YearCode
					 WHERE BBT.Member_Code=@memcode AND BBT.YearCode=@yearcode
					 group by  BB .Broker_Code
				
				SELECT	 ROW_NUMBER ( ) OVER (ORDER BY  t.script_code,t.Ac_Type,t.trans_dt ) AS NameId,
						t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,ma1.AC_Name,t.TransType,t.Ac_Type,t.Script_Code,t.Last_Date,t.Qty,
						Case When @IsWithTax = 0 Then t.Rate Else t.Exp_Rate END As 'Rate',--t.Rate,`
						t.YearCode, t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,t.Exp_Rate,t.FrmNm,t.ID,
						Ms.bse_code,Ms.nse_code,Ms.script_name,ma.ac_name  AS 'Holding Type',
						CASE	WHEN TransType='Sold' THEN 'Sold' 
						        WHEN (((t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101))AND t.TransType='Bought') THEN 'Opening'
								WHEN TransType='Bought' AND t.Bill_no = 'Bonus' THEN 'Bonus' 
								WHEN TransType='Bought' AND t.Bill_no ='Rights'THEN 'Rights' 
								WHEN TransType='Bought' AND  t.Bill_no ='Split' THEN 'Split' 
								WHEN TransType='Bought' AND  t.Bill_no ='Transfer' THEN 'Transfer' 
								WHEN TransType='Bought' AND Frmnm = 'IPO' THEN 'IPO'  
								WHEN TransType='Bought' AND Frmnm='MFDRI' THEN 'Devidend Re-Investment'
								WHEN t.TransType='Bought' AND  t.Bill_no <> 'Opening'  THEN 'Bought'
							
								END AS 'Flag_Type',
						ma1.AC_Name as 'Broker_Name',
						mm.Member_Code,
						mm.Member_Name--,t.isstock
						INTO #alldata 
				FROM brokerbill_trans t 
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN mst_account ma ON t.ac_type = ma.ac_code AND ma.member_code = t.Member_code and ma.Year_Code=t.YearCode
				LEFT JOIN BrokerBill BB ON BB.Member_Code = t.Member_code AND BB.Trans_no=t.Trans_No AND BB.YearCode = t.yearcode
				LEFT JOIN mst_account ma1 on ma1.AC_Code = BB.Broker_Code AND ma1.Member_Code = BB.Member_code and ma1.Year_Code = BB.YearCode  and bb.Trans_no=t.Trans_No
				LEFT JOIN Mst_Member mm		ON t.member_code = mm.Member_code 
				WHERE  ISNULL(t.isfnobill,0) = @Investmenttype 
				AND t.trans_dt >=  @Fromdate AND t.trans_dt <= @Todate 
				AND t.member_code = @memcode AND  t.yearcode = @yearcode  
				AND  t.Ac_Type =(CASE WHEN  @Ac_Type='0' THEN  t.Ac_Type  ELSE  @Ac_Type END)
				AND  t.script_code IN (SELECT * FROM #SCriptCodes_Monthwise_brokerwise)
				AND	 BB.Broker_code IN (SELECT * FROM #BrokerCodes_MonthWise)
				AND  ISNULL(t.isIntraDay,0) = (CASE WHEN @IsIntraDay=0 THEN  ISNULL(isIntraDay,0) ELSE ISNULL(@IsIntraDay,0) END) 
				AND t.MergedEntry = 0  AND ISNULL( t.Ref_SrNo,0) != 1
				AND (IsSLBS=0 OR IsSLBS IS NUll) 
				GROUP BY mm.Member_Code,mm.Member_Name,t.Trans_Dt,t.Trans_No,t.Sr_No,t.Bill_no,t.ID,ma1.AC_Code,ma1.AC_Name ,ma.ac_name,t.Ac_Type,Ms.script_name,t.TransType,t.Ac_Type,
				t.Script_Code,t.Last_Date,t.Qty,t.Rate,t.Member_code,t.YearCode, t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,
				t.Exp_Rate,t.FrmNm,Ms.bse_code,Ms.nse_code,Frmnm --,t.isstock
				 
				-- Select * from #alldata
				 
				DECLARE @isIntradayCol INT , 
				@COUNT INT = 0	 
				 
			    DECLARE @ToDATEfORcLOSIng VARCHAR(15) =  CONVERT(Varchar,CONVERT(DATETime,@Fromdate,101) - 1,101)
				
				INSERT INTO #Openings
				EXECUTE proc_StockholdingPosition_BrokerWise_Equity 0,@Investmenttype,@Ac_Type,@memcode,@Yearcode,@FromDate,@ToDATEfORcLOSIng,@ScriptCode,'',@BSE_NSE_Code,@Is_BFCF, '0','','ClosingStocks',@IsWithTax,1

			--	Select * from #Openings
				
				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT	id,Trans_No,script_name,script_Code,holding_type,bill_no,CONVERT(VARCHAR(10), trans_dt,101),qty,rate,amount,ISNULL(isintraday, 0)isIntraDay,Broker_name,Member_Code,Member_Name
				FROM #Openings 
				WHERE BillType = 'Opening'
			    UNION ALL 
				SELECT  id,Trans_No,script_name,Script_Code,[holding type] , Bill_no,CONVERT(VARCHAR(10), trans_dt,101),qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Broker_Name,Member_Code,Member_Name
				FROM #alldata WHERE  
				Flag_Type = 'Opening'
			
				OPEN alldatacursor 
				FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type, @billno, @dates, @qty, @rate, @amount, @isIntradayCol ,@Broker_name,@Member_Code,@Member_Name
				WHILE(@@FETCH_STATUS = 0)
					BEGIN

						IF(@Investmenttype=2)
							SET @holding_type='Mutual Fund'
					
						-- Insert All Openings
						SET @Pkid = (SELECT (MAX(ISNULL(pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE ScriptCode = @ScriptId)--and MemberCode = @Member_Code and  Broker_Name = @Broker_Name)
						SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Pkid = @Pkid)
						SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise) else @Dup_pkid end)
						SET @Dup_pkid = ISNULL(@Dup_pkid,0)
						SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Dup_pkid > @Dup_pkid)
						SET @Dup_pkid = @Dup_pkid + 1
	
						DECLARE @IDs INT=0
						
						INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise  
						(Dup_pkid, opening_bill_no ,id, Trans_No,ScriptCode, Trans_Type, Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,Broker_name,MemberCode,MemberName) 
						SELECT 
						@Dup_pkid,@billno,@ID, @Trans_No,@ScriptId,'Opening', 'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Broker_name,@Member_Code,@Member_Name
						
						SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),0) FROM #mainoutputtable_1_MonthWise_BrokerWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) END)  
						IF(@idcount>0)
							BEGIN
								UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
								SET Dup_pkid = Dup_pkid + 1 
								WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
							END
			 			FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type, @billno,      @dates, @qty, @rate, @amount, @isIntradayCol ,@Broker_name,@Member_Code,@Member_Name
					END 
				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 
			 
				DECLARE @salecount INT=0,@Boughtcount INT=0,@Flag_Type VARCHAR(50)

				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
				Select id,bill_no,BillType,BillType,script_Code,script_name,holding_type,Trans_No,CONVERT(VARCHAR(10), trans_dt,101),qty,rate,amount,ISNULL(isintraday, 0)isIntraDay,Broker_name,Member_Code,Member_Name
				from #Openings
				WHERE BillType != 'Opening'			
				UNION ALL 			
				SELECT id,Bill_no,Flag_Type,TransType,Script_Code, script_name,[holding type],Trans_No,CONVERT(DATETIME, trans_dt,103), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Broker_name, Member_Code,Member_Name
				FROM #alldata  	WHERE  
				(TransType in('Bought','Sold')  AND CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
				
				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Broker_name,@Member_Code,@Member_Name
				WHILE (@@FETCH_STATUS = 0) 
					BEGIN
						SET @COUNT = 0
						DECLARE @IsOpening INT							=	0,
						@prioritysId INT								=	0,
						@str VARCHAR(MAX)								=	'',	
						@purchase_Op_Qty FLOAT							=	0,
						@purchase_Op_Bill VARCHAR(20)					=	'',
						@purchase_Op_Date VARCHAR(20)					=	'',
						@purchase_Op_Rate FLOAT							=	0,
						@PurQTY FLOAT									=	0,
						@BalPurQTY FLOAT								=	0,
						@BalSoldQTY FLOAT								=	0,
						@Balpurchase_Op_Qty FLOAT						=	0,
						@BalOpeningQTY FLOAT							=	0,
						@Sold_Qty FLOAT									=	0,
						@tempID int										=	0
						

					IF(@isIntradayCol=0)
						BEGIN
							IF(@Investmenttype = 2)
								SET @holding_type='Mutual Fund'

							IF(@TransType LIKE '%Bought%')
								BEGIN
								
									/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
									SET @COUNT = (	SELECT Count(*) 
													FROM #mainoutputtable_1_MonthWise_BrokerWise 
													WHERE holding_type=@holding_type AND script_name=@scriptname AND isintradaycol=0 
													AND Flag_Type_Sold IN('Sold')  and  Flag_Type='Sold'
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) 												
													AND Broker_name = @Broker_name AND MemberName = @Member_Name)
									IF (@COUNT > 0)
										BEGIN
											SELECT  ROW_NUMBER ( ) OVER (ORDER BY MemberName,Broker_name,scriptcode, holding_type,CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,
											* INTO #tempSoldValExists 
											FROM #mainoutputtable_1_MonthWise_BrokerWise 											  
											WHERE script_name=@scriptname AND holding_type=@holding_type  
											AND Broker_name = @Broker_name
											AND MemberName = @Member_Name
											AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
											AND Flag_Type_Sold ='Sold'  and  Flag_Type = 'Sold' AND isintradaycol=0
											ORDER BY NameId								
											
											DECLARE @R_Sold_COUNT FLOAT=(SELECT COUNT(*) FROM #tempSoldValExists )
											DECLARE @Temppurchase_Op_Qty FLOAT 
										
											WHILE(@R_Sold_COUNT  > 0)
												BEGIN 
													DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists ORDER BY Dup_pkid,NameId)
													SET @str = @TransType

													SELECT TOP 1	@Sold_Qty		= sold_qty,
																	@soldDate		= sold_date,
																	@soldRate		= sold_Rate,
																	@soldBillNo		= sold_bill_no,
																	@Pkid			= Pkid
													FROM #tempSoldValExists
													WHERE id  = @tempSaleID 

													SET @purchase_Op_Qty = @qty
													
													IF(@TransType='Opening')
														BEGIN
															UPDATE #mainoutputtable_1_MonthWise_BrokerWise  
															SET	opening_date=@dates,
																opening_rate=@rate,
																opening_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
															Flag_Type = 'Bought'
															WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid
														END
													ELSE IF(@TransType='Bought')
														BEGIN
															UPDATE #mainoutputtable_1_MonthWise_BrokerWise  
															SET	purchase_date=@dates,
																purchase_bill_no=@billno,
																purchase_rate=@rate,
																purchase_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																Flag_Type = 'Bought'
															WHERE  id = @tempSaleID  AND ISNULL(purchase_qty,0)=0 AND pkid = @pkid
														END
													if(@Sold_Qty > @purchase_Op_Qty )
														BEGIN
															UPDATE #mainoutputtable_1_MonthWise_BrokerWise  
															SET	sold_qty = @purchase_Op_Qty 
															WHERE  id  = @tempSaleID AND Flag_Type_Sold='Sold' AND pkid = @pkid
														END
														
													DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND pkid = @pkid
													DECLARE @Balancedval   FLOAT = Round((ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)),6)
													SET @tablerowscount = (SELECT COUNT(*) FROM  #tempSoldValExists )
															
													IF(@Balancedval  < 0)
														BEGIN
															--SET @Pkid = (SELECT (MAX(ISNULL(pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE ScriptCode = @ScriptId AND Broker_name = @Broker_name AND MemberName = @Member_Name)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															SET @soldQty=ABS(@Balancedval) 
															SET @prioritysId = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise_BrokerWise) 
															SET @prioritysId = ISNULL(@prioritysId,0) + 1
																	
															INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise(Dup_pkid, ID,Trans_No,ScriptCode, Flag_Type,Flag_Type_Sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,Broker_name,MemberCode,MemberName,Trans_Type)
															VALUES(@Dup_pkid, @tempSaleID ,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Broker_name,@Member_Code,@Member_Name,'Sold')
																	
															UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
															SET prioritys=@prioritysId+1  
															WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
															
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) END)  
																	
															IF(@idcount>0)
															BEGIN
																UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
																SET Dup_pkid = Dup_pkid + 1 
																WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																FROM Fn_split(@Pkid, ',') ) 
															END
															SET @Balancedval = 0

														BREAK;
														END
													ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
															BEGIN
															  
																SET @Pkid = (SELECT (MAX(ISNULL(pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE ScriptCode = @ScriptId AND Broker_name = @Broker_name AND MemberName = @Member_Name)
																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Pkid = @Pkid)
																SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1
																SET @prioritysId = (SELECT MAX(prioritys+1) FROM #mainoutputtable_1_MonthWise_BrokerWise)
															
																IF(@TransType='Opening')
																	BEGIN
																		INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise(Dup_pkid, ID,Trans_No,ScriptCode, Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,Broker_name,MemberCode,MemberName,Trans_Type)
																		VALUES(@Dup_pkid, @ID,@Trans_No,@ScriptId, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Broker_name,@Member_Code,@Member_Name,@Flag_Type)

																		UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
																		SET prioritys=@prioritysId+1  
																		WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	END
																ELSE IF(@TransType='Bought')
																	BEGIN
																		INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise(Dup_pkid, ID,Trans_No, ScriptCode, Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,Broker_name,MemberCode,MemberName,Trans_Type)
																		VALUES(@Dup_pkid, @ID,@Trans_No,@ScriptId, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Broker_name,@Member_Code,@Member_Name,@Flag_Type)

																		UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
																		SET prioritys=@prioritysId+1  
																		WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	END
																		
																SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) END)  
																IF(@idcount>0)
																	BEGIN
																		UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
																		SET Dup_pkid = Dup_pkid + 1 
																		WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																		FROM Fn_split(@Pkid, ',') ) 
																	END
																	ENd
														ELSE IF(@Balancedval=0)
															BEGIN
																break;
															END
													SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
													SET @qty = @Balancedval
												END
													

											DROP TABLE #tempSoldValExists
										END
									/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
									ELSE
										BEGIN
										
										  
											SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise_BrokerWise)
											SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0)+1 from #mainoutputtable_1_MonthWise_BrokerWise)
											--SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1_MonthWise_BrokerWise)

											INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise (Dup_pkid,id,Trans_No,ScriptCode, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,Broker_name,MemberCode,MemberName,Trans_Type)
											VALUES ( ISNULL(@Dup_pkid,0),@ID,@Trans_No,@ScriptId, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Broker_name,@Member_Code,@Member_Name,@Flag_Type) 
										END
								END	
							ELSE IF(@TransType LIKE '%Sold%')
								BEGIN
								  
									/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
									SET @COUNT = (SELECT Count(*) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Other') AND ISNULL(sold_qty,0)=0  AND isintradaycol=0  AND Broker_name=@Broker_name AND MemberName = @Member_Name)
									IF (@COUNT > 0)
									 	BEGIN
											DECLARE @Balanceval FLOAT
											SELECT  ROW_NUMBER ( ) OVER (ORDER BY  MemberName,Broker_name,scriptcode, holding_type,CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,
											* INTO #tempValExists 
											FROM
											#mainoutputtable_1_MonthWise_BrokerWise WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Other') 
											AND Broker_name= @Broker_name  
											AND MemberName = @Member_Name
											AND ISNULL(sold_qty,0)=0  AND isintradaycol=0 
											ORDER BY NameId
													
													
											DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
											DECLARE @TempSoldQty FLOAT 
											DECLARE @brokerName varchar(200)
										
											WHILE(@RCOUNT > 0 )
												BEGIN
													SET @Sold_Qty = @qty

													SET @tempID = (SELECT TOP(1) id FROM #tempValExists   ORDER BY Dup_pkid)
													SET @str = (SELECT TOP(1) Flag_Type FROM #tempValExists WHERE id  = @tempID)  
 													IF(@str='Opening')
														BEGIN
															SELECT	TOP(1)	@TempSoldQty	= opening_qty,
																			@openingDate	= opening_date,
																			@openingrate	= opening_rate,
																			@Pkid			= Pkid
															FROM #tempValExists 
															WHERE id  = @tempID
														END
													ELSE IF(@str='Bought')
														BEGIN
															SELECT	TOP(1)	@TempSoldQty	= purchase_qty,
																			@PurchaseDate	= purchase_date,
																			@Purchaserate	= purchase_rate,
																			@PurchaseBillNo = purchase_bill_no,
																			@Pkid			= Pkid
															FROM #tempValExists 
															WHERE id  = @tempID
														END

													IF(@Sold_Qty > 0)
														BEGIN
															SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise_BrokerWise)-- WHERE id=@tempID)
															SET @prioritysId = ISNULL(@prioritysId,0)+1
															UPDATE #mainoutputtable_1_MonthWise_BrokerWise  
																SET	
																	opening_qty     = CASE WHEN @str ='Opening'
																						THEN 
																							CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																						ELSE 0
																						END,
																	purchase_qty    = CASE WHEN @str ='Bought'
																						THEN 
																							CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																						END,
																	sold_date       = @dates,
																	sold_bill_no    = @billno,
																	sold_rate       = @rate,
																	sold_qty        = CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																	Flag_Type_Sold  = 'Sold',
																	prioritys       = @prioritysId
															WHERE  id = @tempID AND ISNULL(sold_qty,0)=0 AND pkid = @Pkid
															SET @Balanceval = Round((ABS(@Sold_Qty) - ABS(@TempSoldQty)),6)
														END
														
												DELETE FROM #tempValExists WHERE id = @tempID AND Pkid=@Pkid
												SET @tablerowscount = (SELECT COUNT(*) FROM  #tempValExists )
												SET @RCOUNT = @RCOUNT - 1
															
												IF(@Balanceval  < 0)
													BEGIN
														--SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Pkid = @Pkid)
														SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Pkid = @Pkid)
														SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise) else @Dup_pkid end)
														SET @Dup_pkid = ISNULL(@Dup_pkid,0)
														SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Dup_pkid > @Dup_pkid)
														SET @Dup_pkid = @Dup_pkid + 1
																	 
																
														IF(@str='Opening')
															BEGIN
																SET @openingQty = ABS(@Balanceval) 
																SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise_BrokerWise)-- WHERE id=@tempID)
																SET @prioritysId = ISNULL(@prioritysId,0)+1
																
																INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise(Dup_pkid,opening_bill_no, ID,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,Broker_name,MemberName,MemberCode,Trans_Type)
																VALUES(@Dup_pkid,'Opening',@tempID,@Trans_No,@ScriptId, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Broker_name,@Member_Name,@Member_Code,@Flag_Type)

																SET @prioritysId = ISNULL(@prioritysId,0)+1
														
																UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
																SET prioritys=@prioritysId   
																WHERE prioritys >= @prioritysId AND ID <> @tempID
															END
														ELSE 
															BEGIN
																SET @PurchaseQty = ABS(@Sold_Qty) 
																SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise_BrokerWise)-- WHERE id=@tempID)
																SET @prioritysId = ISNULL(@prioritysId,0)+1


																INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,Broker_name,MemberName,MemberCode,Trans_Type)
																VALUES(@Dup_pkid,@tempID,@Trans_No,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Broker_name,@Member_Name,@Member_Code,@Flag_Type)
																
																SET @prioritysId = ISNULL(@prioritysId,0)+1
																			
																UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
																SET prioritys=@prioritysId    
																WHERE prioritys >= @prioritysId AND ID <> @tempID
															END
																	
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) ELSE CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),1) FROM #mainoutputtable_1_MonthWise_BrokerWise)) END)  
															IF(@idcount>0)
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise_BrokerWise SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
																SET @Balanceval = 0
														BREAK;
													END
												ELSE  IF(ISNULL(@Balanceval,0) > 0 and @tablerowscount=0)
													BEGIN	
														SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Pkid = @Pkid)
														SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise) else @Dup_pkid end)
														SET @Dup_pkid = ISNULL(@Dup_pkid,0)
														SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Dup_pkid > @Dup_pkid)
														SET @Dup_pkid = @Dup_pkid + 1
														SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #mainoutputtable_1_MonthWise_BrokerWise)

														INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,Broker_name,MemberName,MemberCode,Trans_Type)
														VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Broker_name,@Member_Name,@Member_Code,@Flag_Type)
																
														UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
														SET prioritys=@prioritysId+1  
														WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
														SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) END)  
																	
														IF(@idcount>0)
															BEGIN
																UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
																SET Dup_pkid = Dup_pkid + 1 
																WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																FROM Fn_split(@Pkid, ',') ) 
															END
													END
													ELSE IF(ISNULL(@Balanceval,0) =0)
														BEGIN
															SET @Balanceval=0
															BREAK;
														END
													SET @qty = @Balanceval
							 				END
											DROP TABLE #tempValExists
										END
											
									/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
									ELSE
										BEGIN
											--SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #mainoutputtable_1_MonthWise_BrokerWise)
											--SET @prioritysId = ISNULL(@prioritysId,0)+1
											SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise_BrokerWise)
											SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0)+1 from #mainoutputtable_1_MonthWise_BrokerWise)

											INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,Broker_name,MemberName,MemberCode,Trans_Type)
											VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId,  'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Broker_name,@Member_Name,@Member_Code,@Flag_Type)
										END
									SET @purchase_Op_Date  = ''
									SET @purchase_Op_Rate  = ''
									SET @purchase_Op_Qty   = ''
									SET @purchase_Op_Bill  = ''
								END
						END
					IF(@isIntradayCol=1)
						BEGIN
							IF(@TransType LIKE '%Bought%')
								BEGIN
									/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
									--SELECT * FROM #mainoutputtable_1_MonthWise_BrokerWise --WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and ISNULL(Flag_Type,'')='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=1  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
										SET @COUNT = (	SELECT Count(*) 
													FROM #mainoutputtable_1_MonthWise_BrokerWise 
													WHERE holding_type=@holding_type AND script_name=@scriptname 
													AND Flag_Type_Sold IN('Sold')  and  Flag_Type='Sold'
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) 
													AND isintradaycol=1 
													AND Broker_name = @Broker_name AND MemberName = @Member_Name)
									IF (@COUNT > 0)
										BEGIN
											SELECT  ROW_NUMBER ( ) OVER (ORDER BY MemberName,Broker_name,scriptcode, holding_type,CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,
											* INTO #tempBought 
											FROM
											#mainoutputtable_1_MonthWise_BrokerWise 
											WHERE script_name=@scriptname AND holding_type=@holding_type  
											AND Broker_name = @Broker_name
											AND MemberName = @Member_Name
											AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
											AND Flag_Type_Sold ='Sold'  and  Flag_Type = 'Sold' AND isintradaycol=1
											ORDER BY NameId	
													 
											DECLARE @Bought_COUNT INT = ( SELECT COUNT(*) FROM #tempBought )
											DECLARE @Temppurchase_Qty FLOAT 
											SET @purchase_Op_Qty = @qty
											DECLARE @Balance_val FLOAT
											WHILE(@Bought_COUNT  > 0)
												BEGIN 
													DECLARE @tempSale_ID INT = (SELECT TOP(1) id FROM #tempBought ORDER BY Dup_pkid)
													SET @str=@TransType

													SELECT	@Temppurchase_Qty		= sold_qty,
															@soldDate				= sold_date,
															@soldRate				= sold_rate,
															@soldBillNo				= sold_bill_no,
															@pkid					= pkid
													FROM #tempBought 
													WHERE id  = @tempSale_ID 

													SET @Sold_Qty= ABS(@Temppurchase_Qty)
															 
													IF(@TransType='Bought')
														BEGIN
															UPDATE #mainoutputtable_1_MonthWise_BrokerWise  
															SET	purchase_date=@dates,
																purchase_bill_no=@billno,
																purchase_rate=@rate,
																purchase_qty= CASE	WHEN @Temppurchase_Qty > @purchase_Op_Qty 
																					THEN ABS(@purchase_Op_Qty) 
																					ELSE ABS(@Temppurchase_Qty) 
																				END,
																Flag_Type='Bought'
															WHERE  id = @tempSale_ID  and pkid=@pkid
														END
													IF(@Temppurchase_Qty > @purchase_Op_Qty )
														BEGIN
															UPDATE #mainoutputtable_1_MonthWise_BrokerWise  
															SET sold_qty = ABS(@purchase_Op_Qty) 
															WHERE Flag_Type_Sold = 'Sold' 
															AND   id = @tempSale_ID   and pkid=@pkid
														END
															
													DELETE FROM #tempBought  WHERE id = @tempSale_ID 
													SET @Balance_val = Round((isnull(@purchase_Op_Qty,0) - (@Sold_Qty)),6)
													SET @tablerowscount = (SELECT COUNT(*) FROM  #tempBought)
															
													SET @Bought_COUNT  = @Bought_COUNT  - 1
													SET @qty = @Balance_val

													IF(@Balance_val  < 0)
														BEGIN
														--	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE ScriptCode = @ScriptId AND Broker_Name = @Broker_Name AND MemberName = @Member_Name)-- AND ID = @ID)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															SET @soldQty = ABS(@Balance_val) 
															SET @prioritysId  =(SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise_BrokerWise )--WHERE id=@tempSale_ID )
															SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
															INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise(Dup_pkid,ID, Trans_No,ScriptCode, Flag_Type,Flag_Type_Sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,Broker_Name,MemberName,MemberCode,Trans_Type)
															VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Sold', 'Sold', @prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balance_val),@soldRate,@isIntradayCol,@Broker_Name,@Member_Name,@Member_Code,@Flag_Type)
																	
															UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
															SET prioritys=@prioritysId+1  
															WHERE prioritys >= @prioritysId AND ID<>@tempSale_ID 
																
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) END)  
																	
															IF(@idcount>0)
																BEGIN
 																	UPDATE #mainoutputtable_1_MonthWise_BrokerWise
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																	FROM Fn_split(@Pkid, ',') ) 
																END

															BREAK;
														END
													ELSE IF(@Balance_val  > 0 and @tablerowscount = 0)
														BEGIN
															IF(@TransType='Bought')
																BEGIN
																--select 'text'
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE ScriptCode = @ScriptId AND Broker_Name = @Broker_Name AND MemberName = @Member_Name)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #mainoutputtable_1_MonthWise_BrokerWise)
																			
																	INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise(Dup_pkid,ID,Trans_No,ScriptCode,Flag_Type,Flag_Type_Sold,  prioritys,  script_name,holding_type,purchase_bill_no, purchase_date,purchase_qty,purchase_rate,isintradaycol,Broker_Name,MemberName,MemberCode,Trans_Type)
																	VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Bought','Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balance_val),@rate,@isIntradayCol,@Broker_Name,@Member_Name,@Member_Code,@Flag_Type)
																			
																	UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 																																		
																			
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   
																			CONVERT(VARCHAR(200),pkid) NOT IN ( SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																END
														ENd
													SET @purchase_Op_Qty= (@Balance_val)
												END

													
											DROP TABLE #tempBought
										END
									/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
									ELSE
										BEGIN
											--SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise_BrokerWise)
											--SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1_MonthWise_BrokerWise)
											SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise_BrokerWise)
											SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0) + 1 from #mainoutputtable_1_MonthWise_BrokerWise)

											INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise (Dup_pkid,id,Trans_No,ScriptCode, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,Broker_name,MemberName,MemberCode,Trans_Type) 
										VALUES ( @Dup_pkid,@ID,@Trans_No,@ScriptId, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Broker_name,@Member_Name,@Member_Code,@Flag_Type) 
										END
								END	
							ELSE IF(@TransType LIKE '%Sold%')
								BEGIN
									/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
									SET @COUNT = (SELECT Count(*) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split') AND ISNULL(sold_qty,0)=0  AND isintradaycol=1 
													AND Broker_name= @Broker_name--(CASE WHEN @BrokerCode <>'' THEN @Broker_name ELSE Broker_name END)
													AND MemberName = @Member_Name)
									IF (@COUNT > 0)
									 	BEGIN
											DECLARE @Balanceval_sold FLOAT
											SELECT  ROW_NUMBER ( ) OVER (ORDER BY  Broker_name,scriptcode, holding_type,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
											* INTO #tempSold 
											FROM #mainoutputtable_1_MonthWise_BrokerWise 
											WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split') AND 
											Broker_name= @Broker_name--(CASE WHEN @BrokerCode <>'' THEN @Broker_name ELSE Broker_name END)
											AND MemberName = @Member_Name
											AND ISNULL(sold_qty,0)=0  AND isintradaycol=1 
											ORDER BY NameId
													
											DECLARE @RSoldCOUNT INT = (SELECT COUNT(*) FROM #tempSold)
											DECLARE @TempQty_Sold FLOAT 
												    
											WHILE(@RSoldCOUNT > 0 )
												BEGIN 
													SET @Sold_Qty = @qty
													SET @tempID  =   (SELECT TOP(1) id FROM #tempSold)
													SET @str     =   (SELECT TOP(1) Flag_Type FROM #tempSold WHERE id = @tempID  ORDER BY Dup_pkid,NameId)
													SET @pkid    =   (SELECT TOP(1) pkid  FROM #tempSold WHERE id  = @tempID )
															
													IF(@str='Bought')
														BEGIN
															SELECT	@TempQty_Sold	=	purchase_qty,
																	@PurchaseDate	=	purchase_date,
																	@Purchaserate	=	purchase_rate,
																	@PurchaseBillNo	=	purchase_bill_no
															FROM #tempSold 
															WHERE id  = @tempID 
														END
													IF(@Sold_Qty > 0)
														BEGIN
															SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise_BrokerWise)-- WHERE id=@tempID)
															SET @prioritysId = ISNULL(@prioritysId,0)+1
															UPDATE #mainoutputtable_1_MonthWise_BrokerWise  
																SET	
																	purchase_qty  = CASE WHEN @str ='Bought'
																							THEN CASE	WHEN  @TempQty_Sold >= @Sold_Qty 
																									THEN @Sold_Qty 
																									ELSE @TempQty_Sold 
																								END
																						END,
																	sold_date      = @dates,
																	sold_bill_no   = @billno,
																	sold_rate      = @rate,
																	sold_qty       = CASE WHEN @TempQty_Sold > @Sold_Qty THEN @Sold_Qty ELSE @TempQty_Sold END,
																	Flag_Type_Sold = 'Sold',
																	prioritys      = @prioritysId
															WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND pkid = @pkid
															SET @Balanceval_sold = Round((ABS(@Sold_Qty) - ABS(@TempQty_Sold)),6)
														END
															
													DELETE FROM #tempSold WHERE id = @tempID
													SET @RSoldCOUNT = @RSoldCOUNT - 1
													SET @tablerowscount = (SELECT COUNT(*) FROM  #tempSold)
														
													IF(@Balanceval_sold < 0)
														BEGIN
														--	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE ScriptCode = @ScriptId AND Broker_Name = @Broker_Name AND MemberName = @Member_Name)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															SET @PurchaseQty=ABS(@Sold_Qty) 
															SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise_BrokerWise)-- WHERE id=@tempID)
															SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
															INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,Broker_name,MemberCode,MemberName,Trans_Type)
															VALUES(@Dup_pkid,@tempID,@Trans_No,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval_sold)  ,@Purchaserate,@isIntradayCol,@Broker_name,@Member_Code,@Member_Name,@Flag_Type)
																	
															SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
															UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
															SET prioritys=@prioritysId    
															WHERE prioritys >= @prioritysId AND ID <> @tempID
																	
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) END)  
															IF(@idcount>0)
																BEGIN
																		UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
																		SET Dup_pkid = Dup_pkid + 1 
																		WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
															BREAK;
														END
													ELSE IF(ISNULL(@Balanceval_sold,0) > 0 AND @tablerowscount=0)
														BEGIN
															SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE ScriptCode = @ScriptId AND Broker_Name = @Broker_Name AND MemberName = @Member_Name)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise_BrokerWise) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise_BrokerWise WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #mainoutputtable_1_MonthWise_BrokerWise)

															INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise(Dup_pkid,ID,Trans_No, ScriptCode, Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,Broker_name,MemberCode,MemberName,Trans_Type)
															VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval_sold)  ,@rate,@isIntradayCol,@Broker_name,@Member_Code,@Member_Name,@Flag_Type)

															UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
															SET prioritys=@prioritysId+1  
															WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise_BrokerWise)) END)  
															IF(@idcount>0)
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise_BrokerWise 
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
														END
													SET @qty = @Balanceval_sold
												END	
											DROP TABLE #tempSold
										END
											
									/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
									ELSE
										BEGIN
											--SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise_BrokerWise)
											--SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1_MonthWise_BrokerWise)
											SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise_BrokerWise)
											SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0) +1 from #mainoutputtable_1_MonthWise_BrokerWise)

											INSERT INTO #mainoutputtable_1_MonthWise_BrokerWise(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,Broker_name,MemberCode,MemberName,Trans_Type)
											VALUES(ISNULL(@Dup_pkid,0),@ID, @Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Broker_name,@Member_Code,@Member_Name,@Flag_Type)
										END
											
									SET @purchase_Op_Date	=	''
									SET @purchase_Op_Rate	=	''
									SET @purchase_Op_Qty	=	''
									SET @purchase_Op_Bill	=	''
								END

						END
					FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Broker_name,@Member_Code,@Member_Name
				END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor  
		END 
		--select * from #mainoutputtable_1_MonthWise_BrokerWise --order by Dup_pkid

		IF(@IsBSEISIN=1)
	    BEGIN
		      INSERT INTO #mainoutputtable_Final_MonthWise_BrokerWise_ISINNO 
			  SELECT  mab.pkid,mab.Dup_pkid,mab.Broker_name,mab.Trans_No,mab.id,mab.prioritys,mab.Trans_Type,mab.Split_Type,mab.Flag_Type,mab.Flag_Type_Sold, 
			        mab.flag_script_name, mab.flag_holding_type,
					mab.script_name + '[' +ms.BSE_Code + ']' + '[' +ms.ISIN_No+ ']',mab.holding_type,mab.opening_bill_no ,mab.opening_date,mab.opening_qty,mab.opening_rate,
					mab.opening_amount,mab.purchase_date,mab.purchase_bill_no,mab.purchase_qty,mab.purchase_rate,mab.purchase_amount,mab.sold_date ,mab.sold_bill_no,mab.sold_qty,
					mab.sold_rate,mab.sold_amount,mab.gain_loss,mab.closing_qty,mab.closing_rate,mab.closing_value,mab.short_term,mab.long_term,mab.speculation,mab.gain_speculation,
					mab.loss_speculation,mab.nse_rate,mab.bse_rate,mab.dayscount,mab.isintradaycol,mab.[type],mab.ScriptCode,mab.MemberCode,mab.MemberName  
					from #mainoutputtable_1_MonthWise_BrokerWise mab
					INNER JOIN Mst_Script Ms On  mab.ScriptCode=Ms.Script_Code
		END
		ELSE if(@IsBSEISIN=0)
		BEGIN
		     INSERT INTO #mainoutputtable_Final_MonthWise_BrokerWise_ISINNO 
			 SELECT mab.pkid,mab.Dup_pkid,mab.Broker_name,mab.Trans_No,mab.id ,mab.prioritys,mab.Trans_Type,mab.Split_Type,mab.Flag_Type,mab.Flag_Type_Sold, 
			        mab.flag_script_name, mab.flag_holding_type,mab.script_name,mab.holding_type,mab.opening_bill_no ,mab.opening_date,mab.opening_qty,mab.opening_rate,
					mab.opening_amount,mab.purchase_date,mab.purchase_bill_no,mab.purchase_qty,mab.purchase_rate,mab.purchase_amount,mab.sold_date ,mab.sold_bill_no,mab.sold_qty,
					mab.sold_rate,mab.sold_amount,mab.gain_loss,mab.closing_qty,mab.closing_rate,mab.closing_value,mab.short_term,mab.long_term,mab.speculation,mab.gain_speculation,
					mab.loss_speculation,mab.nse_rate,mab.bse_rate,mab.dayscount,mab.isintradaycol,mab.[type],mab.ScriptCode,mab.MemberCode,mab.MemberName  
					from #mainoutputtable_1_MonthWise_BrokerWise mab
		END

		IF(@IsIntraDay = 0 AND @short_Long_Term != 0  )
			BEGIN
				IF(@short_Long_Term = 1)  -- Long Term
					BEGIN
						INSERT INTO #mainoutputtable_1_Final__MonthWise_BrokerWise (OrderBy, opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate, sort,isintradaycol,MemberCode,MemberName,[type] )

						SELECT  ROW_NUMBER ( ) OVER (ORDER BY  MemberName,broker_name, ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN   CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
							 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId, opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						0,
						Round(ISNULL( CASE 	WHEN  isintradaycol = 0 AND opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
											WHEN  isintradaycol = 0 AND purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4),
						0,
						0,
						0,
						Broker_name,nse_rate,bse_rate,1 sort ,isintradaycol,
						MemberCode,MemberName,Trans_Type
						FROM #mainoutputtable_Final_MonthWise_BrokerWise_ISINNO 
						WHERE ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
									(
										DATEDIFF(DAY,CONVERT(DATETIME,opening_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) > 365 
									)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									(
										DATEDIFF(DAY,CONVERT(DATETIME, purchase_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) > 365
									)
								)
							)
						order by NameId
					END

				ELSE If(@short_Long_Term = 2)  -- Short Term
					BEGIN
					--Select * from #mainoutputtable_1_MonthWise_BrokerWise
						INSERT INTO #mainoutputtable_1_Final__MonthWise_BrokerWise (OrderBy, opening_bill_no, id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss , closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate, sort,isintradaycol,MemberCode,MemberName,[type]  )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY   MemberName, broker_name,holding_type,ScriptCode,--pkid,
						 case  WHEN  Dup_pkid is Null Then Pkid
							   WHEN  Dup_pkid is NOt Null then Dup_pkid 
							   else Dup_pkid end,prioritys,				
						Case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
							 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
								opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4) as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						Round(ISNULL(
								CASE	WHEN  isintradaycol = 0 AND opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN  isintradaycol = 0 AND purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4),
						0,
						0,
						0,
						0,Broker_name,nse_rate,bse_rate,1 sort,isintradaycol ,
						MemberCode,MemberName,Trans_Type 
						FROM #mainoutputtable_Final_MonthWise_BrokerWise_ISINNO 
						WHERE  ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
										(		
											DATEDIFF(DAY,CONVERT(DATETIME,opening_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) <= 365 
										)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									  (		
										DATEDIFF(DAY,CONVERT(DATETIME, purchase_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) <= 365
									  )
								)
							)
						order by NameId
					END

				ELSE If(@short_Long_Term = 4)  -- Short Term + Long Term
					BEGIN
						INSERT INTO #mainoutputtable_1_Final__MonthWise_BrokerWise (OrderBy, opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate, sort,isintradaycol,MemberCode,MemberName,[type])

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  MemberName, broker_name,ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						
						opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						 Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) <= 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) <= 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						(CASE   WHEN  isintradaycol = 0 AND ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
								    (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
							  THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						
						(CASE WHEN  isintradaycol = 0 AND ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365) OR
								   (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365))  
							  THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,Broker_name,nse_rate,bse_rate,1 sort,isintradaycol
						,MemberCode,MemberName,Trans_Type  
						FROM #mainoutputtable_Final_MonthWise_BrokerWise_ISINNO 
						WHERE  ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						order by NameId
					END
				ELSE If(@short_Long_Term = 5)  -- Without Sepeculation
					BEGIN
						INSERT INTO #mainoutputtable_1_Final__MonthWise_BrokerWise (OrderBy, opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate, sort,isintradaycol,MemberCode,MemberName,[type])

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  MemberName, broker_name,ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						
						opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						 Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) <= 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) <= 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						(CASE   WHEN  isintradaycol = 0 AND ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
								    (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
							  THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						
						(CASE WHEN  isintradaycol = 0 AND ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365) OR
								   (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >365))  
							  THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,Broker_name,nse_rate,bse_rate,1 sort,isintradaycol
						,MemberCode,MemberName,Trans_Type  
						FROM #mainoutputtable_Final_MonthWise_BrokerWise_ISINNO 
						WHERE  ISNULL(isintradaycol,0)=0
						order by NameId
					END
			END

		ELSE If(@short_Long_Term = 3 AND @IsIntraDay = 1 )  -- Only Speculation
			BEGIN
				INSERT INTO #mainoutputtable_1_Final__MonthWise_BrokerWise (OrderBy, opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate, sort,isintradaycol,MemberCode,MemberName,[type])

				SELECT  ROW_NUMBER ( ) OVER (ORDER BY case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END,  MemberName,broker_name,ScriptCode,holding_type desc)  AS NameId,
						
						opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
				ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),purchase_date,ISNULL(purchase_bill_no,0),
				ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,sold_date ,sold_bill_no ,isnull(sold_qty,0) ,
				ISNULL(sold_rate,0),ISNULL(sold_amount,0) ,
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4) as gain_loss,
				
				closing_qty ,closing_rate ,closing_value ,
				0,
				0,
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4) ,
				0,
				0,Broker_name,nse_rate,bse_rate,1 sort,isintradaycol 
				,MemberCode,MemberName,Trans_Type  
				FROM #mainoutputtable_Final_MonthWise_BrokerWise_ISINNO 
				WHERE  (ISNULL(closing_qty,0) = 0)  AND (ISNULL(isintradaycol,0)=1) AND (ISNULL(purchase_qty,0)! = 0 AND  ISNULL(sold_qty,0) ! = 0) 
				order by NameId
			END
		ELSE
			BEGIN		
				INSERT INTO #mainoutputtable_1_Final__MonthWise_BrokerWise (OrderBy, opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate, sort,isintradaycol,MemberCode,MemberName,[type])

				SELECT  
				ROW_NUMBER ( ) OVER (ORDER BY  MemberName, broker_name,holding_type,ScriptCode,--pkid,
				 case  WHEN  Dup_pkid is Null Then Pkid
				       WHEN  Dup_pkid is NOt Null then Dup_pkid 
				       else Dup_pkid end,prioritys,				
                Case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,

				opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,opening_date,
				ISNULL(opening_qty ,0),ISNULL(opening_Rate,0),ISNULL(opening_amount,0),purchase_date,purchase_bill_no,
				ISNULL(purchase_qty,0) ,ISNULL(purchase_rate ,0),ISNULL(purchase_amount ,0),sold_date ,sold_bill_no ,ISNULL(sold_qty ,0),
				ISNULL(sold_rate,0),ISNULL(sold_amount ,0),
				    Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) > 365   --short term for openings
									THEN  ISNULL(sold_rate,0) * ISNULL(sold_qty,0) - ISNULL(opening_rate,0) * ISNULL(opening_qty,0)
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) <= 365 --short term for purchase
									THEN  ISNULL(sold_rate ,0)* ISNULL(sold_qty,0) - ISNULL(purchase_rate,0) * ISNULL(purchase_qty  ,0)--long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, opening_rate, ISNULL(sold_rate,0), CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), ISNULL(opening_qty,0), ISNULL(sold_qty,0))) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, purchase_rate, ISNULL(sold_rate,0), CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), ISNULL(purchase_qty,0), ISNULL(sold_qty,0))) 
				
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				  ISNULL(closing_qty,0) ,ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
				CASE WHEN isintradaycol = 0 AND  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365)     -- short term for openings
						THEN  ISNULL(sold_rate ,0) *  ISNULL(sold_qty ,0)- ISNULL(opening_rate,0) * ISNULL(opening_qty ,0)
					WHEN isintradaycol = 0 AND (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365)  -- short term for purchase
						THEN  ISNULL(sold_rate ,0)* ISNULL(sold_qty ,0)- ISNULL(purchase_rate,0)*ISNULL(purchase_qty ,0)
					ELSE 0.0 END,
						
				CASE WHEN  isintradaycol = 0 AND ((opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)     --long term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365))  --long term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, ISNULL(opening_rate,0), ISNULL(sold_rate,0), CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, ISNULL(purchase_rate,0),ISNULL( sold_rate,0), CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  isintradaycol = 1 AND (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				Broker_name,nse_rate,bse_rate,1 sort,isintradaycol
				,MemberCode,MemberName,Trans_Type    
				FROM #mainoutputtable_Final_MonthWise_BrokerWise_ISINNO 
				order by NameId
			END
				UPDATE #mainoutputtable_1_Final__MonthWise_BrokerWise SET prioritys=0
				DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final__MonthWise_BrokerWise)
				UPDATE #mainoutputtable_1_Final__MonthWise_BrokerWise
				SET prioritys  = @i , @i = @i + 1

				--Select * from #mainoutputtable_1_MonthWise_BrokerWise

		IF(@OUTPUT_Flag='Details')
			BEGIN
				IF(@Investmenttype != 2)
					BEGIN
						SELECT id,prioritys,ScriptCode,script_name 'Script Name',Holding_Type,Holding_Type as flag_Holding_Type,Broker_name,opening_bill_no, CONVERT(DATETIME, opening_date,101) 'Opening Date',
						ISNULL(opening_qty,2) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(DATETIME, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(DATETIME, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',ISNULL(gain,0) 'Gain',ISNULL(loss,0) 'Loss',ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND gain!=0 THEN gain  ELSE 0 END gain_speculation,CASE WHEN isintradaycol=1 AND loss!=0  THEN loss  ELSE 0 END loss_speculation,
						ISNULL(nse_rate,0) nse_rate , ISNULL(bse_rate,0)bse_rate ,isintradaycol ,1 sort,[type] 
						FROM #mainoutputtable_1_Final__MonthWise_BrokerWise
						WHERE (opening_qty != 0  OR purchase_qty != 0  or sold_qty != 0)  
						order by Broker_name,script_name,Holding_Type						
					END
				ELSE
					BEGIN
						SELECT id,prioritys,ScriptCode,script_name 'Script Name',Holding_Type,opening_bill_no,CONVERT(DATE, opening_date,103) 'Opening Date',
						ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',
						ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',
						ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',ISNULL(gain,0) 'Gain',ISNULL(loss,0) 'Loss',ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0)!=0 THEN gain  ELSE '0' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0)!=0  THEN loss  ELSE '0' END loss_speculation,Broker_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),ISNULL(isintradaycol,0),1 sort,[type] 
						FROM #mainoutputtable_1_Final__MonthWise_BrokerWise
						WHERE (opening_qty != 0  OR purchase_qty != 0  or sold_qty != 0)  
						ORDER BY  id,Broker_name,script_name,Holding_Type
					END
			END
		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
				SELECT  0 id ,  0 prioritys,'' opening_bill_no, '' ScriptCode,script_name 'Script Name',  Holding_Type,
				NULL 'Opening Date', SUM(opening_qty) 'Opening Qty', 
				CASE WHEN SUM(opening_qty) != 0
					 THEN SUM(opening_amount)/ NULLIF(SUM(opening_qty),0)  
					 ELSE 0
				END  'Opening Rate', 
				SUM(opening_amount) 'Opening Amount',
				NULL 'Purchase Date','' AS 'Purchase BillNo', SUM(purchase_qty)  'Purchase Qty', 
				SUM(ISNULL(purchase_amount,0))  / nullif(SUM(ISNULL(purchase_qty,0)),0) 'Purchase Rate', SUM(purchase_amount)  'Purchase Amount',
				NULL 'Sold Date', '' AS 'Sold BillNo', SUM(sold_qty) 'Sold Qty', 
				CASE WHEN SUM(sold_qty) != 0
					 THEN SUM(sold_amount)/nullif(SUM(sold_qty),0)   
					 ELSE 0
				END  'Sold Rate',
				SUM(sold_amount) 'Sold Amount', SUM(gain_loss ) 'Gain/Loss', SUM(gain)  'Gain', SUM(loss)  'Loss',
				SUM(closing_qty)  'Closing Qty', 

				CASE WHEN SUM(closing_qty) != 0
					 THEN (SUM(closing_value) / SUM(NULLIF(closing_qty,0))) 
					 ELSE 0
				END  'Closing Rate',
				SUM(closing_value)  'Closing Value', SUM(short_term)  as short_term, SUM(long_term) as long_term,
				SUM(speculation) as speculation, SUM(gain_speculation)gain_speculation, SUM(loss_speculation)loss_speculation,   Broker_name,0 nse_rate,0 bse_rate,1 sort --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
				FROM
					(
						SELECT MAX(id+0)id ,MAX (prioritys+0) prioritys,'' opening_bill_no,'' ScriptCode, script_name,   Holding_Type,'' 'Opening Date',SUM(opening_qty) 'Opening_Qty',sum(opening_rate) opening_rate ,SUM(opening_amount) 'Opening_Amount',
						'' 'Purchase Date','' purchase_bill_no,SUM(ISNULL(purchase_qty,0)) 'Purchase_Qty', SUM(ISNULL(purchase_rate,0)) purchase_rate,SUM(ISNULL(purchase_amount,0)) 'Purchase_Amount',
						'' 'Sold Date',sold_bill_no ,SUM(sold_qty) 'Sold_Qty', SUM(sold_rate)sold_rate  , SUM(sold_amount) 'Sold_Amount',SUM(gain_loss) 'Gain_Loss',SUM(gain) 'Gain',SUM(loss) 'Loss',
						SUM(ISNULL(closing_qty,0)) 'Closing_Qty',SUM(ISNULL(closing_rate,0)) 'Closing_Rate',SUM(ISNULL(closing_value,0)) 'Closing_Value',
						sum(ISNULL(short_term,0)) as short_term,
						sum(ISNULL(long_term,0)) as long_term,
						sum(ISNULL(speculation,0)) as speculation,
						SUM(ISNULL(gain_speculation,0)) gain_speculation,SUM(ISNULL(loss_speculation,0)) loss_speculation,  Broker_name,0 nse_rate,0 bse_rate,1 sort --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
						FROM #mainoutputtable_1_Final__MonthWise_BrokerWise 
						GROUP BY Broker_name,script_name, Holding_Type,purchase_bill_no,sold_bill_no ,opening_date,purchase_date,sold_date,isintradaycol
					)a
					GROUP BY  Broker_name,script_name ,Holding_Type 				 						 
					ORDER BY  Broker_name,Holding_Type ,script_name,sort
			 END
		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN
			
				SELECT  ISNULL(prioritys,0) ,Trans_No,ScriptCode,0 id ,@memcode,@yearcode, script_name ,Holding_Type,script_name flag_script_name,Holding_Type flag_Holding_Type,
				CONVERT(date, opening_date,103),ISNULL(opening_qty ,0),ISNULL(opening_Rate,0),ISNULL(opening_amount,0),
				CONVERT(date, purchase_date,103),purchase_bill_no,ISNULL(purchase_qty ,0),ISNULL(purchase_rate ,0),ISNULL(purchase_amount ,0),
				CONVERT(date, sold_date,103) ,sold_bill_no ,ISNULL(sold_qty ,0),
				ISNULL(sold_rate,0),ISNULL(sold_amount ,0),ISNULL(gain_loss ,0),ISNULL(gain ,0),ISNULL(loss,0),ISNULL(closing_qty ,0),ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
				ISNULL(short_term,0),ISNULL(long_term,0),ISNULL(speculation,0),ISNULL(gain_speculation,0),ISNULL(loss_speculation,0),Broker_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol
				FROM #mainoutputtable_1_Final__MonthWise_BrokerWise
				ORDER BY Broker_name,script_name,CONVERT(date, purchase_date,103)--,holding_type
			END
		ELSE IF(@OUTPUT_Flag='Annexture')
			BEGIN
				SELECT	'' opening_bill_no,
						0 id,
						0 prioritys,
						ScriptCode,
						'' 'Family_Name',
						MemberName 'Member_Name',
						'' 'Family_Code',
						MemberCode 'Member_Code',
						script_name 'Script Name',  
						Holding_Type,
						NULL 'Opening Date', 
						SUM(opening_qty) 'Opening Qty', 
						CASE WHEN SUM(opening_qty) != 0
							 THEN SUM(opening_amount)/ NULLIF(SUM(opening_qty),0)  
							 ELSE 0
						END  'Opening Rate', 
						SUM(opening_amount) 'Opening Amount',
						NULL 'Purchase Date',
						'' AS 'Purchase BillNo', 
						SUM(purchase_qty)  'Purchase Qty', 
						SUM(ISNULL(purchase_amount,0))  / nullif(SUM(ISNULL(purchase_qty,0)),0) 'Purchase Rate', 
						SUM(purchase_amount)  'Purchase Amount',
						NULL 'Sold Date', 
						'' AS 'Sold BillNo', 
						SUM(sold_qty) 'Sold Qty', 
						CASE	WHEN SUM(sold_qty) != 0
								THEN SUM(sold_amount)/nullif(SUM(sold_qty),0)   
								ELSE 0
						END  'Sold Rate',
						SUM(sold_amount) 'Sold Amount', 
						SUM(gain_loss ) 'Gain/Loss', 
						SUM(gain)  'Gain', 
						SUM(loss)  'Loss',
						SUM(closing_qty)  'Closing Qty', 
						CASE  WHEN SUM(closing_qty) != 0
							  THEN (SUM(closing_value) / SUM(NULLIF(closing_qty,0))) 
							  ELSE 0
						END  'Closing Rate',
						SUM(closing_value)  'Closing Value', 
						SUM(short_term)  as short_term, 
						SUM(long_term) as long_term,
						SUM(speculation) as speculation, 
						SUM(gain_speculation)gain_speculation, 
						SUM(loss_speculation)loss_speculation,   
						'' consultant_name, 
						0 nse_rate,
						0 bse_rate,
						1 sort,
						broker_code 
						
		     		FROM
					(
						SELECT MAX(id+0)id ,MAX (prioritys+0) prioritys,'' opening_bill_no,ScriptCode, script_name,   Holding_Type,'' 'Opening Date',SUM(opening_qty) 'Opening_Qty',sum(opening_rate) opening_rate ,SUM(opening_amount) 'Opening_Amount',
						'' 'Purchase Date','' purchase_bill_no,SUM(ISNULL(purchase_qty,0)) 'Purchase_Qty', SUM(ISNULL(purchase_rate,0)) purchase_rate,SUM(ISNULL(purchase_amount,0)) 'Purchase_Amount',
						'' 'Sold Date',sold_bill_no ,SUM(sold_qty) 'Sold_Qty', SUM(sold_rate)sold_rate  , SUM(sold_amount) 'Sold_Amount',SUM(gain_loss) 'Gain_Loss',SUM(gain) 'Gain',SUM(loss) 'Loss',
						SUM(ISNULL(closing_qty,0)) 'Closing_Qty',SUM(ISNULL(closing_rate,0)) 'Closing_Rate',SUM(ISNULL(closing_value,0)) 'Closing_Value',
						sum(ISNULL(short_term,0)) as short_term,
						sum(ISNULL(long_term,0)) as long_term,
						sum(ISNULL(speculation,0)) as speculation,
						SUM(ISNULL(gain_speculation,0)) gain_speculation,SUM(ISNULL(loss_speculation,0)) loss_speculation,  Broker_name,0 nse_rate,0 bse_rate,1 sort,MemberCode,MemberName,
						MA.AC_Code as 'broker_code'
						FROM #mainoutputtable_1_Final__MonthWise_BrokerWise F
						LEFT JOIN MST_Account MA ON MA.AC_Name = F.Broker_name AND MA.Member_Code in (SELECT Value FROM membercodestable(@memcode,','))  AND MA.Year_Code = @yearcode
						GROUP BY MemberCode,MemberName,Broker_name,ScriptCode,script_name, Holding_Type,purchase_bill_no,sold_bill_no ,opening_date,purchase_date,sold_date,isintradaycol,MA.AC_Code,MA.AC_Name
					)a
					GROUP BY  a.MemberCode,a.MemberName,a.broker_code,Broker_name,a.ScriptCode,script_name ,Holding_Type
					ORDER BY  MemberName,Broker_name,Holding_Type ,script_name,sort
			END
		ELSE IF(@OUTPUT_Flag='ClosingStocks')
			BEGIN
				SELECT  id,
						Trans_No ,
						script_name,
						ScriptCode,
						Holding_Type,
						Broker_Name,
						CASE
							WHEN ISNULL(closing_qty,0) < 0		THEN sold_bill_no
							WHEN ISNULL(opening_date,'') != ''   OR  ISNULL(purchase_date,'') != '' THEN  purchase_bill_no
							ELSE ''
						END  AS  'bill_no',
						CASE
							WHEN ISNULL(closing_qty,0) < 0		THEN CONVERT(DATE,sold_date,101)
							WHEN ISNULL(opening_date,'') != ''	THEN  CONVERT(DATE,opening_date,101)
							WHEN ISNULL(purchase_date,'') != '' THEN CONVERT(DATE,purchase_date,101)
						END  AS  'trans_dt',
						ABS(ISNULL(closing_qty,0)) 'Qty',
						ISNULL(closing_rate,0) 'rate',
						ISNULL(closing_value,0) 'amount',
						isintradaycol,
						CASE
							WHEN ISNULL(closing_qty,0)    < 0		THEN 'Sold'
							WHEN ISNULL(opening_date,'')  != ''		THEN 'Opening'
							WHEN ISNULL(purchase_date,'') != ''		THEN  'Bought'
							ELSE ''
						END  AS  'Type'
				from #mainoutputtable_1_Final__MonthWise_BrokerWise 
				WHERE ISNULL(closing_qty,0) <> 0
				ORDER BY  trans_dt,Trans_No						
			END
		ELSE IF (@OUTPUT_Flag = 'Summary')
			 BEGIN
			
			   INSERT INTO #mainoutputtable_1_Final_Summary_Monthwise
				SELECT  ISNULL(prioritys,0) ,Trans_No,ScriptCode,0 id ,@memcode,@yearcode, script_name ,Holding_Type,script_name flag_script_name,Holding_Type flag_Holding_Type,
				CONVERT(date, opening_date,103),ISNULL(opening_qty ,0),ISNULL(opening_Rate,0),ISNULL(opening_amount,0),
				CONVERT(date, purchase_date,103),purchase_bill_no,ISNULL(purchase_qty ,0),ISNULL(purchase_rate ,0),ISNULL(purchase_amount ,0),
				CONVERT(date, sold_date,103) ,sold_bill_no ,ISNULL(sold_qty ,0),
				ISNULL(sold_rate,0),ISNULL(sold_amount ,0),ISNULL(gain_loss ,0),ISNULL(gain ,0),ISNULL(loss,0),ISNULL(closing_qty ,0),ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
				ISNULL(short_term,0),ISNULL(long_term,0),ISNULL(speculation,0),ISNULL(gain_speculation,0),ISNULL(loss_speculation,0),Broker_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol
				
				FROM #mainoutputtable_1_Final__MonthWise_BrokerWise
				--Where closing_qty<>0
				ORDER BY Broker_name,script_name,CONVERT(date, purchase_date,103)
				 
		SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
		T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
		T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
		T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
		T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
		T1.Broker_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,   

		ISNULL( Dr.BSE_Rate ,0) AS 'bse_rate', /**/
		ISNULL(Dr.NSE_Rate,0)  AS 'nse_rate' /**/
		
		INTO #alldata_Summary 
		FROM #mainoutputtable_1_Final_Summary_Monthwise  T1
		LEFT JOIN BrokerBill T2 ON T2.Trans_No=T1.Trans_no AND T2.Member_Code=T1.MemberCode AND T2.YearCode=T1.Yearcode
		LEFT JOIN DailyRate DR ON DR.Script_Code = T1.ScriptCode  and Dr.Trans_Dt = @Todate /**/
		ORDER BY Broker_name
				
		TRUNCATE TABLE #mainoutputtable_1_Final_Summary_Monthwise

		INSERT INTO #mainoutputtable_1_Final_Summary_Monthwise ( id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		Broker_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt) 

		SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,ISNULL(opening_qty,0),ISNULL(opening_rate,0),ISNULL(opening_amount,0),
		purchase_date,purchase_bill_no,ISNULL(purchase_qty,0),ISNULL(purchase_rate,0),ISNULL(purchase_amount,0),
		sold_date,sold_bill_no,ISNULL(sold_qty,0),ISNULL(sold_rate,0),ISNULL(sold_amount,0),ISNULL(gain_loss,0),ISNULL(gain,0),ISNULL(loss,0),
		ISNULL(closing_qty,0),ISNULL(closing_rate,0),ISNULL(closing_value,0),ISNULL(short_term,0),ISNULL(long_term,0),ISNULL(speculation,0),ISNULL(gain_speculation,0),ISNULL(loss_speculation,0),
		Broker_name,
		Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
		sort,isintradaycol,ISNULL(Other_amt,0),ISNULL(ServTax_Amt,0),ISNULL(Stt_amt ,0)
		FROM #alldata_Summary  


		GROUP BY Broker_name,id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 
		ORDER BY Broker_name
			  
	 IF(@RecordOnlyhavingClosingbalanceZero = 0)
			BEGIN		
				IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
							BEGIN
					
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
										END AS 'Avg. Rate',

									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
										END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt, Broker_name
								FROM #mainoutputtable_1_Final_Summary_Monthwise
								GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,Broker_name
								HAVING SUM(closing_qty) != 0
								--HAVING (sum (CASE WHEN @RecordOnlyhavingClosingbalanceZero = 0 
								--	THEN closing_qty end  )!=0
									
														END
						ELSE IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0)
							BEGIN							
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								''  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',

								SUM(ISNULL(Other_amt,0))Other_amt, Broker_name
								FROM #mainoutputtable_1_Final_Summary_Monthwise
								GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
						ELSE IF(@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1)
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
										END AS 'Avg. Rate',

									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
										END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,Broker_name
								FROM #mainoutputtable_1_Final_Summary_Monthwise
								GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate,opening_date, purchase_date,sold_date,closing_qty
								HAVING SUM(closing_qty) != 0
							END
						ELSE 
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
									CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt,  Broker_name
								FROM #mainoutputtable_1_Final_Summary_Monthwise
								GROUP BY Broker_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					--END
			END
		ELSE
			BEGIN
					IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
							BEGIN
						
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) >=0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
										END AS 'Avg. Rate',

									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
										END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt, Broker_name
								FROM #mainoutputtable_1_Final_Summary_Monthwise
								GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,Broker_name
								HAVING SUM(closing_qty) = 0
								--HAVING (sum (CASE WHEN @RecordOnlyhavingClosingbalanceZero = 0 
								--	THEN closing_qty end  )!=0
									
														END
						ELSE IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0)
							BEGIN							
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								''  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
										END AS 'Avg. Rate',

									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
										END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  Broker_name
								FROM #mainoutputtable_1_Final_Summary_Monthwise
								GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) = 0
							END
						ELSE IF(@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1)
							BEGIN
								
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
										END AS 'Avg. Rate',

									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
										END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt, Broker_name
								FROM #mainoutputtable_1_Final_Summary_Monthwise
								GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate,opening_date, purchase_date,sold_date,closing_qty
								HAVING SUM(closing_qty) != 0
							END
						ELSE --IF(@WithActualAvgRate = 0)
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
									CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt,  Broker_name
								FROM #mainoutputtable_1_Final_Summary_Monthwise
								GROUP BY Broker_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) = 0
							END
			END

	    Select Broker_Name,Sum(ISNULL (gain_loss,0)) from #mainoutputtable_1_Final_Summary_Monthwise
		Group By Broker_Name
		Having Sum(ISNULL (gain_loss,0))!=0
		Order by 1
			
		Select  Round(sum(Other_amt),4) from BrokerBill where Member_code=@memcode and Yearcode=@yearcode and isfnoBill=@Investmenttype and Trans_Dt<=@Todate

	
	--DROP TABLE #allSummarydata
	END
		DROP TABLE #mainoutputtable_1_MonthWise_BrokerWise
		DROP TABLE #mainoutputtable_Final_MonthWise_BrokerWise_ISINNO 
		-- DROP TABLE #allSummarydata
		DROP TABLE #alldata 
		 
  END  

















































GO
/****** Object:  StoredProcedure [dbo].[proc_Monthwise_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Monthwise_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Monthwise_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency] AS' 
END
GO
-- proc_Monthwise_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency 0,5,'0','30001','1120182019','2018-04-01 12:00:00:00','2019-03-31 03:50:37:50','','','','', '0' ,'0','Details'
ALTER PROCEDURE [dbo].[proc_Monthwise_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency] 
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@BrokerCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX),
@IsWithTax bit = 0,
@RecordOnlyhavingClosingbalanceZero as bit = 0,@WithActualAvgRate as bit= 0, @DateWiseClosinStock as bit= 0,
@Script_Name varchar(max) = '')
AS 
  BEGIN  
  SET NOCOUNT ON;
		DECLARE @StartYearDate varchar(20) = '04/01/'+ (SELECT SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101)
		CREATE TABLE #mainoutputtable_1_Broker_month_wise
        (  
			pkid INT identity(1,1),
			Dup_pkid int,
			Broker_name VARCHAR(MAX),
			Trans_No VARCHAR(20),
			id INT,
			prioritys INT,
			Trans_Type  VARCHAR(50), 
			Split_Type VARCHAR(50), 
			Flag_Type VARCHAR(10),
			Flag_Type_Sold VARCHAR(10),
			flag_script_name  VARCHAR(500),
			flag_holding_type VARCHAR(200), 
			script_name  VARCHAR(500),
			holding_type VARCHAR(200), 
			opening_bill_no VARCHAR(10),	
			opening_date DATETIME,
			opening_qty  FLOAT DEFAULT 0,
			opening_rate  FLOAT DEFAULT 0,
			opening_amount AS( [opening_qty] * [opening_rate] ), 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount AS( purchase_qty * purchase_rate ), 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount AS ( sold_qty * sold_rate ), 
			gain_loss float,
			closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 
			closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
			closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
			short_term FLOAT DEFAULT 0,
			long_term  FLOAT DEFAULT 0,
			speculation  FLOAT DEFAULT 0,
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			dayscount FLOAT DEFAULT 0,
			isintradaycol INT,
			[type] VARCHAR(20) ,
			ScriptCode  VARCHAR(50),
			Strike_Price float DEFAULT 0,
			OptionType VARCHAR(100),
			Last_Date VARCHAR(100),
			MemberCode VARCHAR(50),
			MemberName VARCHAR(max)
        )  

		CREATE TABLE #mainoutputtable_1_Final_Brokerwise_Month
        ( 
			Dup_pkid int,
			OrderBy varchar(100),
			Trans_No VARCHAR(20),
			id INT,
			prioritys INT   ,
			Split_Type VARCHAR(50),
			Flag_Type VARCHAR(10),
			Flag_Type_Sold VARCHAR(10),
			flag_script_name  VARCHAR(500),
			flag_holding_type VARCHAR(200), 
			script_name  VARCHAR(500),
			holding_type VARCHAR(200), 
			opening_bill_no VARCHAR(10),	
			opening_date DATETIME,
			opening_qty  FLOAT DEFAULT 0,
			opening_rate  FLOAT DEFAULT 0,
			opening_amount FLOAT DEFAULT 0, 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount FLOAT DEFAULT 0 , 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount FLOAT DEFAULT 0, 
			gain_loss FLOAT DEFAULT 0,
			gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
			loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
			closing_qty FLOAT DEFAULT 0, 
			closing_rate FLOAT DEFAULT 0,
			closing_value FLOAT DEFAULT 0,
			short_term FLOAT DEFAULT 0,
			long_term FLOAT DEFAULT 0, 
			speculation FLOAT DEFAULT 0, 
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			Broker_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			dayscount FLOAT DEFAULT 0,
			isintradaycol INT,[type] VARCHAR(20),
			sort   VARCHAR(5),
			ScriptCode  VARCHAR(50),
			Strike_Price float DEFAULT 0,
			OptionType VARCHAR(100),
			Last_Date VARCHAR(100),
			MemberCode VARCHAR(50),
			MemberName VARCHAR(max)
        ) 

		CREATE TABLE #Openings
        (
		   id INT, 
		   Trans_No VARCHAR(20),
		   script_name  VARCHAR(500),
		   script_code VARCHAR(50),
		   holding_type VARCHAR(200),
		   bill_no VARCHAR(100),	
		   trans_dt Datetime,
		   StrikePrice float,
		   OptionType VARCHAR(100),
		   MonthYear VARCHAR(100),
		   Last_dt Datetime,
		   Exp_Rate float,
		   Broker_name  VARCHAR(100),
		   DP_Code  VARCHAR(50),
		   qty  FLOAT DEFAULT 0,
		   rate  FLOAT DEFAULT 0,
		   amount FLOAT DEFAULT 0, 
		   isintraday bit DEFAULT 0, 
		   consultant_name VARCHAR(500),
		   Consultant_Code  VARCHAR(20),
		   Member_Code VARCHAR(20),
		   Member_Name VARCHAR(max),  
		   BillType varchar(20)
	   )  

	    CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
           prioritys INT,Trans_No VARCHAR(50),id INT,scriptCode  VARCHAR(500),script_name  VARCHAR(500),holding_type VARCHAR(200),flag_script_name  VARCHAR(500),flag_holding_type VARCHAR(200),
           opening_date VARCHAR(50),opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
           purchase_date VARCHAR(50),purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
           sold_date VARCHAR(50),sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   Broker_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   Other_amt FLOAT DEFAULT 0,
		   ServTax_Amt FLOAT DEFAULT 0,
		   Stt_amt FLOAT DEFAULT 0,
		   sort   VARCHAR(5),
		   isintradaycol  INT,
		   Last_Date dateTime,
		   Strike_Price float,
		   OptionType varchar(max) 
        ) 

		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty INT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT  
		DECLARE @tablerowscount INT
		IF(@status = 0) 
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
				@openingDate VARCHAR(50),@openingRate FLOAT,@openingQty INT,@openingAmount FLOAT,
				@purchaseDate VARCHAR(50),@PurchaseBillNo  VARCHAR(50),@purchaseRate FLOAT,@purchaseQty int,@purchaseAmount FLOAT,
				@soldDate VARCHAR(50),@soldBillNo  VARCHAR(50),@soldRate FLOAT,@soldQty INT,@soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50),@Broker_name  VARCHAR(100), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(10),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,@PurchaseIntraFlag VARCHAR(100),
				@SaleIntraFlag VARCHAR(10), @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@ScriptId VARCHAR(50),@Dup_pkid int, @Pkid varchar(50),@idcount int,
				@Strike_Price FLOAT,@OptionType VARCHAR(50),@Last_Date VARCHAR(50), @Member_Code varchar(50), @Member_Name varchar(max)    

				CREATE TABLE #SCriptName
				(
					ScriptName varchar(MAX)
				)

				IF(@Script_Name != '')
					INSERT INTO #SCriptName SELECT value FROM Fn_split(@Script_Name, ',') 
				ELSE 
					BEGIN
						INSERT INTO #SCriptName 
						Select distinct (Ms.script_name 
								+ '/' + CONVERT(VARCHAR(10),t.Last_Date,103) 
								+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
								+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' END) 
						from brokerbill_Trans t
						Left Join mst_Script ms on ms.script_Code = t.script_Code 
					END

				CREATE TABLE #BrokerCodes
				(
					BrokerCodes varchar(MAX)
				)
				 
				IF(@BrokerCode != '')
					INSERT INTO #BrokerCodes SELECT value FROM Fn_split(@BrokerCode, ',') 
				ELSE 
					INSERT INTO #BrokerCodes SELECT Broker_Code FROM brokerbill
					
				SELECT	ROW_NUMBER ( ) OVER (ORDER BY  mm.Member_Code,
						mm.Member_Name,ma.AC_Name, t.script_code, t.trans_dt ) AS NameId,
						t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,
						t.TransType,t.Script_Code,t.Last_Date,t.Qty,
						Case When @IsWithTax = 0 Then t.Rate Else t.Exp_Rate END As 'Rate',--t.Rate,`
						t.YearCode, t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,
						t.Exp_Rate,
						t.FrmNm,t.ID,
						Ms.bse_code,Ms.nse_code,
						
						Ms.script_name 
						+ '/' + CONVERT(varchar(20),t.Last_Date,103) 
						+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
						+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' END	script_name,
						'Empty' AS 'Holding Type',
						CASE WHEN (((t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101)) AND t.TransType='Bought') THEN 'Opening'
							 WHEN t.TransType='Bought' AND  t.Bill_no != 'Opening'  THEN 'Bought' 
							 WHEN TransType='Sold' THEN 'Sold' 
						END AS 'Flag_Type',
						ma.AC_Name as 'Broker_Name',
						t.isstock,
						mm.Member_Code,
						mm.Member_Name
						INTO #alldata 
				FROM brokerbill_trans t 
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN BrokerBill BB ON BB.Member_Code = t.Member_code  and bb.Trans_no=t.Trans_No
				LEFT JOIN mst_account ma ON ma.AC_Code = BB.Broker_Code and t.member_Code=ma.member_Code and ma.Year_Code=bb.YearCode
				LEFT JOIN mst_account ma1	ON ma1.AC_Code = BB.Broker_Code AND ma1.Member_Code = BB.Member_code and ma1.Year_Code = BB.YearCode  and bb.Trans_no=t.Trans_No
			    LEFT JOIN Mst_Member mm	ON t.member_code = mm.Member_code 
				WHERE  t.isfnobill = @Investmenttype 
				AND t.trans_dt >=  @Fromdate AND t.trans_dt <= @Todate 
				AND t.member_code IN (SELECT Value FROM membercodestable(@memcode,','))
				AND  t.yearcode = @yearcode  
				AND  (Ms.script_name 
						+ '/' + CONVERT(varchar(20),t.Last_Date,103) 
						+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
						+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' END )
				IN (SELECT * FROM #SCriptName)
				AND	 BB.Broker_code IN (SELECT * FROM #BrokerCodes)
				AND  ISNULL(t.isIntraDay,0) =(CASE WHEN @IsIntraDay=0 THEN  ISNULL(t.isIntraDay,0) ELSE @IsIntraDay END)
				AND t.isstock=(select case when @Is_BFCF = 1 then  '' else  t.isstock end) 
				GROUP BY mm.Member_Code,
						mm.Member_Name, ma.AC_Name,t.YearCode, script_name,t.Trans_Dt,t.Bill_no,t.Trans_No,Sr_No,TransType,t.Script_Code,MonthYear,Last_Date,LotSize,Qty,LotQty,Disp_qty,
				Bal_qty,G_Rate,t.Brok_Amt,ServTax_Amount,Rate,t.Amount,Stt_Amount,
				EntrySource,t.Ref_TransNo,Ref_SrNo,MergedEntry,t.isFNOBill,Strike_Price,OptionType,isIntraDay,Brok_PerUnit,lockedbymerger,
				frac_Qty,Org_Trans_No,Org_SrNo,isDeleteMerger,isstock,ScripwiseExpense,isClient_code,isClient_Brokrage,c_Qty,C_Gross_Rate,
				C_Net_Rate,C_Amount,C_STT,C_STax,C_MisChg,TransactionChg,C_StampDuty,Exp_Rate,PerExp_Unit,FrmNm,ID,bse_code,nse_code,t.isstock
				ORDER  BY   NameId

				--SELECT * FROM #ALLDATA
			
				DECLARE @isIntradayCol INT 
				DECLARE @COUNT INT 
				DECLARE @ToDATEfORcLOSIng VARCHAR(15) =  CONVERT(Varchar,CONVERT(DATETime,@fROMdATE,101) - 1,101)
				
				INSERT INTO #Openings
			    EXECUTE proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency 0,@Investmenttype,@Ac_Type,@memcode,@Yearcode,@FromDate,@ToDATEfORcLOSIng,@ScriptCode,@Broker_name,@BSE_NSE_Code,@Is_BFCF,'0', '' ,'ClosingStocks',@IsWithTax,@Script_Name

			--	select * from #Openings
				
				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT id,Trans_No,script_name,Script_Code ,holding_type,bill_no,CONVERT(VARCHAR(10),trans_dt,101),qty,rate,ISNULL(qty, 0) * ISNULL(rate, 0),ISNULL(isintraday, 0),Broker_name,
				StrikePrice,OptionType,Last_dt,Member_Code,Member_Name   
				FROM #Openings 
				WHERE BillType = 'Opening'
				
				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name 
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
						IF(@Investmenttype=2)
							SET @holding_type='Mutual Fund'
						-- Insert All Openings
						SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_Broker_month_wise WHERE script_name = @scriptname)-- AND ID = @ID)
						SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_Broker_month_wise WHERE Pkid = @Pkid)
						SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #mainoutputtable_1_Broker_month_wise) else @Dup_pkid end)
						SET @Dup_pkid = ISNULL(@Dup_pkid,0)
						SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_Broker_month_wise WHERE Dup_pkid > @Dup_pkid)
						SET @Dup_pkid = @Dup_pkid + 1

					 	DECLARE @IDs INT=0
						DECLARE @Flag_Types VARCHAR(10)
						SET @Flag_Types = (SELECT CASE WHEN @billno = 'Opening' THEN 'Opening' ELSE 'Bought' END)
						IF(@Flag_Types='Opening'  OR (@billno IN('Split') AND CONVERT(DATE,@dates,101)  < CONVERT(DATE ,@StartYearDate,101))
						OR (@billno NOT IN('Bought','Sold') AND CONVERT(date,@dates,101)  < CONVERT(date ,@StartYearDate,101)))
							BEGIN	
								INSERT INTO #mainoutputtable_1_Broker_month_wise   
								(Dup_pkid,opening_bill_no ,id, Trans_No,ScriptCode  ,  Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,Broker_name, Strike_Price, OptionType, Last_Date,MemberCode,MemberName) 
								SELECT  @Dup_pkid,@billno,@ID, @Trans_No,@ScriptId  , 'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name
							END	
						SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),0) FROM #mainoutputtable_1_Broker_month_wise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_Broker_month_wise)) END)  
						IF(@idcount>0)
							BEGIN
								UPDATE #mainoutputtable_1_Broker_month_wise 
								SET Dup_pkid = Dup_pkid + 1 
								WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
							END
			 			FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name
						END 

				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 
				DECLARE @salecount INT=0,@Boughtcount INT=0,@Flag_Type VARCHAR(20)

				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
				Select	id,bill_no,BillType,BillType,script_Code,script_name,holding_type,
						Trans_No,CONVERT(VARCHAR(10), trans_dt,101),qty,rate,amount,
						ISNULL(isintraday, 0)isIntraDay,Broker_name,StrikePrice
						,OptionType,Last_dt,Member_Code,Member_Name
				from #Openings
				WHERE BillType != 'Opening'
				
				UNION ALL 

				SELECT id,Bill_no,Flag_Type,TransType,Script_Code,script_name,[holding type],Trans_No,CONVERT(VARCHAR(10), trans_dt,101), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Broker_name, Strike_Price, OptionType, Last_Date,Member_Code,Member_Name
				FROM #alldata WHERE 
				(TransType in ('Bought','Sold')  AND CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
				
				--Select * from #mainoutputtable_1_Broker_month_wise
				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType,@ScriptId,@scriptname, @holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name 
				
				
				WHILE (@@FETCH_STATUS = 0) 
						BEGIN
 			
							SET @COUNT									=	0
							DECLARE @IsOpening INT						=	0
							DECLARE @prioritysId INT					=	0
							DECLARE @str VARCHAR(MAX)					=	''	
							DECLARE @purchase_Op_Qty FLOAT				=	0
							DECLARE @purchase_Op_Bill VARCHAR(20)		=	''
							DECLARE @purchase_Op_Date VARCHAR(20)		=	''
							DECLARE @purchase_Op_Rate FLOAT				=	0
							DECLARE	@PurQTY FLOAT						=	0
							DECLARE	@BalPurQTY FLOAT					=	0
							DECLARE @BalSoldQTY FLOAT					=	0
							DECLARE @Balpurchase_Op_Qty FLOAT			=	0
							DECLARE @BalOpeningQTY FLOAT				=	0
							DECLARE	@Sold_Qty FLOAT						=	0
							DECLARE @tempID INT							=	0
							
							IF(@isIntradayCol=0)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) 
															FROM #mainoutputtable_1_Broker_month_wise 
															WHERE script_name = @scriptname 
															AND Flag_Type_Sold IN('Sold')  and  Flag_Type ='Sold'  
															AND ISNULL(sold_qty,0) != 0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) 
															AND isintradaycol=0 
															AND MemberName = @Member_Name  
															AND Broker_name = @Broker_name)

											--Select * from #mainoutputtable_1_Broker_month_wise
											IF (@COUNT > 0)
												BEGIN
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  script_name, case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId, 
													* INTO #tempSoldValExists 
													FROM
													#mainoutputtable_1_Broker_month_wise 
													WHERE script_name=@scriptname AND holding_type=@holding_type  AND isintradaycol=0 AND 
													Broker_name = @Broker_name
													AND MemberName = @Member_Name
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold ='Sold'  and  Flag_Type ='Sold' AND isintradaycol=0
													ORDER BY NameId

													DECLARE @R_Sold_COUNT INT=(SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty INT 
												
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists ORDER BY Dup_pkid,NameId)
															SET @str = @TransType

															SELECT TOP 1	@Sold_Qty		= sold_qty,
																			@soldDate		= sold_date,
																			@soldRate		= sold_Rate,
																			@soldBillNo		= sold_bill_no,
																			@Pkid			= Pkid
																	
															FROM #tempSoldValExists
															WHERE id  = @tempSaleID 

															SET @purchase_Op_Qty = @qty

															IF(@TransType='Opening')
																BEGIN
																	UPDATE #mainoutputtable_1_Broker_month_wise  
																	SET	opening_date	=	@dates,
																		opening_rate	=	@rate,
																		opening_qty		=	CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	UPDATE #mainoutputtable_1_Broker_month_wise  
																	SET	purchase_date	=	@dates,
																		purchase_rate	=	@rate,
																		purchase_bill_no=   @PurchaseBillNo, 
																		purchase_qty		=	CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(purchase_qty,0)=0 AND pkid = @pkid
																END
															
															IF(@Sold_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #mainoutputtable_1_Broker_month_wise  
																	SET sold_qty = @purchase_Op_Qty 
																	WHERE  id  = @tempSaleID AND Flag_Type_Sold='Sold' AND pkid = @pkid
																END

															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND Pkid = @Pkid
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempSoldValExists )
															DECLARE @Balancedval   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)

															IF(@Balancedval  < 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_Broker_month_wise WHERE script_name = @scriptname)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_Broker_month_wise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #mainoutputtable_1_Broker_month_wise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_Broker_month_wise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1


																	SET @soldQty=ABS(@Balancedval) 
																	SET @prioritysId  =(SELECT MAX(prioritys) FROM #mainoutputtable_1_Broker_month_wise) 
																	SET @prioritysId = ISNULL(@prioritysId,0)+1

																	INSERT INTO #mainoutputtable_1_Broker_month_wise(Dup_pkid,ID,Trans_No,ScriptCode  , Flag_Type,Flag_Type_Sold ,prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberCode,MemberName)
																	VALUES(@Dup_pkid,@tempSaleID ,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name)
																	
																	UPDATE #mainoutputtable_1_Broker_month_wise 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 

																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_Broker_month_wise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_Broker_month_wise)) END)  
																	
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #mainoutputtable_1_Broker_month_wise 
																			SET Dup_pkid = Dup_pkid + 1 
																			where Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																		SET @Balancedval=0
																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_Broker_month_wise WHERE script_name = @scriptname)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_Broker_month_wise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #mainoutputtable_1_Broker_month_wise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_Broker_month_wise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  = (SELECT MAX(prioritys + 1) FROM #mainoutputtable_1_Broker_month_wise)

																	if(@TransType='Opening')
																		BEGIN
																			INSERT INTO #mainoutputtable_1_Broker_month_wise(Dup_pkid,ID,Trans_No,ScriptCode, Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberCode,MemberName)
																			VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name)

																			UPDATE #mainoutputtable_1_Broker_month_wise 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	ELSE if(@TransType='Bought')
																		BEGIN
																			INSERT INTO #mainoutputtable_1_Broker_month_wise(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberCode,MemberName)
																			VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name)

																			UPDATE #mainoutputtable_1_Broker_month_wise 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_Broker_month_wise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_Broker_month_wise)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #mainoutputtable_1_Broker_month_wise 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid 
																			and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																ENd
															ELSE IF(@Balancedval=0)
																BEGIN
																	break;
																END

															SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
															SET @qty=@Balancedval
														END
													

													DROP TABLE #tempSoldValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_Broker_month_wise)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1_Broker_month_wise)
												 
													INSERT INTO #mainoutputtable_1_Broker_month_wise (Dup_pkid,id,Trans_No,ScriptCode, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberCode,MemberName) 
													VALUES ( @Dup_pkid,@ID,@Trans_No,@ScriptId, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name) 
												END
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
								
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */

											SET @COUNT = (SELECT Count(*) FROM #mainoutputtable_1_Broker_month_wise 
												WHERE script_name=@scriptname 
												AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') 
												AND ISNULL(sold_qty,0)=0  
												AND isintradaycol=0  AND MemberName = @Member_Name 
												AND Broker_name = @Broker_name)
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  script_name ,case when opening_date IS NOT NULL then opening_date else purchase_date end ) AS NameId, 
													* INTO #tempValExists 
													FROM
													#mainoutputtable_1_Broker_month_wise 
													WHERE script_name=@scriptname
													AND MemberName = @Member_Name 
													AND Broker_name = @Broker_name 
													AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') 
													AND ISNULL(sold_qty,0)=0  AND isintradaycol=0 
													ORDER BY NameId

													DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty int 
													
													
													WHILE(@RCOUNT > 0)
														BEGIN 
															SET @Sold_Qty = @qty
															SET @tempID = (Select top(1) id from #tempValExists  ORDER BY Dup_pkid)
															SET @str = (Select top(1) Flag_Type From #tempValExists Where id  = @tempID)
														
															IF(@str='Opening')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= opening_qty,
																					@openingDate	= opening_date,
																					@openingrate	= opening_rate,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID
																END
															ELSE IF(@str='Bought')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= purchase_qty,
																					@PurchaseDate	= purchase_date,
																					@Purchaserate	= purchase_rate,
																					@PurchaseBillNo = purchase_bill_no,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID
																END
															    
															IF(@Sold_Qty > 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_Broker_month_wise)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	UPDATE #mainoutputtable_1_Broker_month_wise  
																		SET	
																			opening_qty = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							END,
																			purchase_qty  = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							END,
																			sold_date=@dates,
																			sold_bill_no = @billno,
																			sold_rate=@rate,
																			sold_qty= CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold='Sold',
																			prioritys       = @prioritysId
																	WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND Pkid=@Pkid
																	SET @Balanceval = ABS(@Sold_Qty) - ABS(@TempSoldQty)
																END
															
														DELETE FROM #tempValExists WHERE id = @tempID AND Pkid=@Pkid
														SET @tablerowscount = (SELECT COUNT(*) FROM  #tempValExists )
														SET @RCOUNT = @RCOUNT - 1

														IF(@Balanceval  < 0)
															BEGIN
																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_Broker_month_wise WHERE Pkid = @Pkid)
																SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #mainoutputtable_1_Broker_month_wise) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_Broker_month_wise WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1
															
															 
																--SET @prioritysId  =(SELECT MAX(ISNULL(@prioritysId,0)+1) FROM #mainoutputtable_1_Broker_month_wise)

																IF(@str='Opening')
																	BEGIN
																		SET @openingQty=ABS(@Balanceval) 
																		SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_Broker_month_wise)-- WHERE id=@tempID)
																		SET @prioritysId = ISNULL(@prioritysId,0)+1

																		INSERT INTO #mainoutputtable_1_Broker_month_wise(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberName,MemberCode)
																		VALUES(@Dup_pkid,@tempID,@Trans_No,@ScriptId, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Name,@Member_Code)

																		SET @prioritysId = ISNULL(@prioritysId,0)+1
																
																		UPDATE #mainoutputtable_1_Broker_month_wise 
																		SET prioritys=@prioritysId+1  WHERE prioritys >=  @prioritysId 
																		AND ID <> @tempID
																	END
																ELSE 
																	BEGIN
																		SET @PurchaseQty = ABS(@Sold_Qty) 
																		SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_Broker_month_wise)-- WHERE id=@tempID)
																		SET @prioritysId = ISNULL(@prioritysId,0)+1
																		
																		INSERT INTO #mainoutputtable_1_Broker_month_wise(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberName,MemberCode)
																		VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Name,@Member_Code)
																		UPDATE #mainoutputtable_1_Broker_month_wise SET prioritys=@prioritysId  WHERE prioritys > @prioritysId AND ID<>@tempID

																		SET @prioritysId = ISNULL(@prioritysId,0)+1
																			
																		UPDATE #mainoutputtable_1_Broker_month_wise 
																		SET prioritys=@prioritysId    
																		WHERE prioritys >= @prioritysId AND ID <> @tempID
																	END
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_Broker_month_wise)) ELSE CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),1) FROM #mainoutputtable_1_Broker_month_wise)) END)  
																IF(@idcount>0)
																BEGIN
																	UPDATE #mainoutputtable_1_Broker_month_wise SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
																set @Balanceval=0;
															BREAK;	
															END
														ELSE if(@Balanceval>0 and @tablerowscount=0)
															BEGIN

																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_Broker_month_wise WHERE Pkid = @Pkid)
																SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #mainoutputtable_1_Broker_month_wise) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_Broker_month_wise WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1
																SET @prioritysId  = (SELECT MAX(prioritys+1) FROM #mainoutputtable_1_Broker_month_wise)

																INSERT INTO #mainoutputtable_1_Broker_month_wise(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberName,MemberCode)
																VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Name,@Member_Code)

																UPDATE #mainoutputtable_1_Broker_month_wise 
																SET prioritys=@prioritysId+1  
																WHERE prioritys > @prioritysId AND ID<>@tempSaleID 

																SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_Broker_month_wise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_Broker_month_wise)) END)  

																IF(@idcount>0)
																BEGIN
																	UPDATE #mainoutputtable_1_Broker_month_wise 
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																	FROM Fn_split(@Pkid, ',') ) 
																END
															ENd
															ELSE IF(ISNULL(@Balanceval,0) =0)
																BEGIN
																	SET @Balanceval=0
																	BREAK;
																END

														SET @qty = @Balanceval
													END
													DROP TABLE #tempValExists
												END
											
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
										
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_Broker_month_wise)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1_Broker_month_wise)
													INSERT INTO #mainoutputtable_1_Broker_month_wise(Dup_pkid,ID,Trans_No, ScriptCode, Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberName,MemberCode)
													VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId,  'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Name,@Member_Code)

												END
											SET @purchase_Op_Date	=	''
											SET @purchase_Op_Rate	=	''
											SET @purchase_Op_Qty	=	''
											SET @purchase_Op_Bill	=	''
										END
								END
							 
							FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type ,@TransType,@ScriptId, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name
						END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 
		--	  select * from #mainoutputtable_1_Broker_month_wise
				INSERT INTO #mainoutputtable_1_Final_Brokerwise_Month (OrderBy, opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate, sort,isintradaycol,Strike_Price,OptionType,Last_Date,MemberCode,MemberName  )

				SELECT ROW_NUMBER ( ) OVER (
				ORDER BY MemberName,Script_Name,
					case   WHEN  Dup_pkid is Null Then Pkid
						   WHEN  Dup_pkid is NOt Null then Dup_pkid 
						   ELSE Dup_pkid end,
					prioritys,
				case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END desc)  
			    AS NameId,
				opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,
				
					    Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365) --short term for purchase
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
						
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365) --short term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) = 0) 
							AND (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				Broker_name,nse_rate,bse_rate,1 sort,isintradaycol ,Strike_Price,OptionType,Last_Date,MemberCode,MemberName 
				FROM #mainoutputtable_1_Broker_month_wise 
				order by NameId
		
			UPDATE #mainoutputtable_1_Final_Brokerwise_Month SET prioritys=0
			DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final_Brokerwise_Month)
			UPDATE #mainoutputtable_1_Final_Brokerwise_Month
			SET prioritys  = @i , @i = @i + 1
		IF(@OUTPUT_Flag='Details')
			BEGIN
				IF(@BrokerCode!='')
					BEGIN
						SELECT prioritys,ScriptCode,script_name 'Script Name',Holding_Type,opening_bill_no,
						CONVERT(date, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_rate,0) 'Opening Rate',
						ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(date, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',
						ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(date, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',
						ISNULL(sold_rate,0) 'Sold Rate',
						ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',
						ISNULL(gain,0) 'Gain',
						ISNULL(loss,0) 'Loss',
						ISNULL(closing_qty,0) 'Closing Qty',
						ISNULL(closing_rate,0) 'Closing Rate',
						ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0) as 'short_term', 
						ISNULL(long_term,0) as 'long_term',
						ISNULL(speculation,0) as 'speculation',
						CASE WHEN isintradaycol=1 and gain!=0 THEN gain  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 and loss!=0  THEN loss  ELSE '' END loss_speculation,Broker_name,nse_rate,bse_rate,isintradaycol,1 sort 
						FROM #mainoutputtable_1_Final_Brokerwise_Month
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
						ORDER BY Broker_name,script_name,prioritys,Holding_Type,id
					END
				ELSE
					BEGIN
				
						SELECT prioritys,ScriptCode,script_name 'Script Name',Holding_Type,opening_bill_no,
						CONVERT(date, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(date, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(date, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',
						ISNULL(sold_rate,0) 'Sold Rate',
						ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',
						CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',
						CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
						ISNULL(closing_qty,0) 'Closing Qty',
						ISNULL(closing_rate,0) 'Closing Rate',
						ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0) as 'short_term', 
						ISNULL(long_term,0) as 'long_term',
						ISNULL(speculation,0) as 'speculation',
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						Broker_name,nse_rate,bse_rate,isintradaycol,1 sort 
						FROM #mainoutputtable_1_Final_Brokerwise_Month
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
						ORDER BY Broker_name,script_name,prioritys,Holding_Type --,id
					END
			END

		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
				SELECT  '' Opening_Bill_No,0 id ,  0 prioritys,'' ScriptCode, script_name 'Script Name', '' Holding_Type,
				NULL 'Opening Date', SUM(ISNULL(opening_qty,0)) 'Opening Qty', 
				 ISNULL((ISNULL(SUM(opening_amount),0)  / NULLIF(SUM(Opening_qty),0)),0) 'Opening Rate', 
				 SUM(opening_amount) 'Opening Amount',
				NULL 'Purchase Date',MAX(purchase_bill_no) 'Purchase BillNo', 
				SUM(ISNULL(purchase_qty,0))  'Purchase Qty', 
				ISNULL((ISNULL(SUM(purchase_amount),0)  / SUM(NULLIF(purchase_qty,0))),0)  'Purchase Rate', 
				--SUM(purchase_amount)  'Purchase Amount',
				SUM(ISNULL(purchase_amount,0)) 'Purchase Amount',
				NULL 'Sold Date', MAX(sold_bill_no) 'Sold BillNo',
				 SUM(ISNULL(sold_qty,0)) 'Sold Qty', 
				 ISNULL((ISNULL(SUM(sold_amount),0) / NULLIF (SUM(sold_qty),0)),0) 'Sold Rate', 
				SUM(ISNULL(sold_amount,0)) 'Sold Amount', 
				SUM(ISNULL(gain_loss,0) ) 'Gain/Loss', 
				SUM(ISNULL(gain,0))  'Gain', 
				SUM(ISNULL(loss,0))  'Loss',
				SUM(ISNULL(closing_qty,0))  'Closing Qty',  
				ISNULL((ISNULL(SUM(closing_value),0) / NULLIF(SUM(closing_qty),0)),0)   'Closing Rate', 
				SUM(ISNULL(closing_value,0))  'Closing Value', 
				SUM(ISNULL(short_term,0))  short_term, 
				SUM(ISNULL(long_term,0))  long_term,
				SUM(ISNULL(speculation,0)) speculation, 
				SUM(ISNULL(gain_speculation,0))gain_speculation, 
				SUM(ISNULL(loss_speculation,0))loss_speculation, Broker_name,0 nse_rate,0 bse_rate,1 sort --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
				FROM
					(
						SELECT  '' Opening_Bill_No,MAX(id+0)id ,MAX (prioritys+0) prioritys,'' ScriptCode, script_name  ,'' Holding_Type,'' 'Opening Date',SUM(ISNULL(opening_qty,0)) 'Opening_Qty',sum(opening_rate) opening_rate ,SUM(opening_amount) 'Opening_Amount',
						'' 'Purchase Date',purchase_bill_no,SUM(purchase_qty) 'Purchase_Qty', SUM(ISNULL(purchase_rate,0)) purchase_rate,SUM(purchase_amount) 'Purchase_Amount',
						'' 'Sold Date',sold_bill_no ,SUM(ISNULL(sold_qty,0)) 'Sold_Qty', SUM(sold_rate)sold_rate  , SUM(ISNULL(sold_amount,0)) 'Sold_Amount',SUM(gain_loss) 'Gain_Loss',SUM(gain) 'Gain',SUM(loss) 'Loss',
						SUM(closing_qty) 'Closing_Qty',SUM(closing_rate) 'Closing_Rate',SUM(closing_value) 'Closing_Value',SUM(short_term) short_term,SUM(long_term) long_term,
						SUM(speculation) speculation,SUM(gain_speculation) gain_speculation,SUM(loss_speculation) loss_speculation, Broker_name,0 nse_rate,0 bse_rate,1 sort --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
						FROM #mainoutputtable_1_Final_Brokerwise_Month 
						GROUP BY script_name,Holding_Type,purchase_bill_no,sold_bill_no,Broker_name 
					)a
				GROUP BY  script_name,Broker_name  
				ORDER BY   script_name,id
				
				 
				--ORDER BY  prioritys 
			END

		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN
			
				SELECT  prioritys ,Trans_No,id ,  ScriptCode,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,
				opening_date,ISNULL(opening_qty,0) ,ISNULL(opening_rate,0),ISNULL(opening_amount,0),
				CONVERT(date, purchase_date,101),purchase_bill_no,ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,
				CONVERT(date, sold_date,101),sold_bill_no ,ISNULL(sold_qty,0) ,sold_rate,ISNULL(sold_amount,0) ,
				ISNULL(gain_loss,0) 'gain_loss',
				ISNULL(gain,0) gain,
				ISNULL(loss,0) loss,
				ISNULL(closing_qty,0) closing_qty,
				ISNULL(closing_rate,0) closing_rate,
				ISNULL(closing_value,0) closing_value,
				ISNULL(short_term,0) short_term,
				ISNULL(long_term,0) long_term,
				ISNULL(speculation,0) speculation,
				ISNULL(gain_speculation,0) gain_speculation,
				ISNULL(loss_speculation,0) loss_speculation,
				Broker_name,nse_rate,bse_rate,0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort 
				,isintradaycol,Last_Date,Strike_Price,OptionType
				FROM #mainoutputtable_1_Final_Brokerwise_Month
				ORDER BY Broker_name,script_name,CONVERT(date, purchase_date,101)
			END

			ELSE IF(@output_Flag='ClosingStocks')
			BEGIN
				 SELECT id,
						--sr_no,
						Trans_No ,
						script_name,
						ScriptCode,
						Holding_Type,
						CASE
							WHEN ISNULL(closing_qty,0) < 0		THEN sold_bill_no
							WHEN ISNULL(opening_date,'') != ''   OR  ISNULL(purchase_date,'') != '' THEN  purchase_bill_no
							ELSE ''
						END  AS  'bill_no',
						CASE
							WHEN ISNULL(closing_qty,0) < 0		THEN CONVERT(DATE,sold_date,101)
							WHEN ISNULL(opening_date,'') != ''	THEN  CONVERT(DATE,opening_date,101)
							WHEN ISNULL(purchase_date,'') != '' THEN CONVERT(DATE,purchase_date,101)
						END  AS  'trans_dt',
						Strike_Price,
						OptionType,
						'' MonthYear,
						Last_Date,
						'' Exp_Rate,
						Broker_name,
						'' DP_Code,
						ABS(ISNULL(closing_qty,0)) 'Qty',
						ISNULL(closing_rate,0) 'rate',
						ISNULL(closing_value,0) 'amount',
						isintradaycol,
						'' consultant_name,
						'' Consultant_code,
						MemberCode,
						MemberName,
						CASE
							WHEN ISNULL(closing_qty,0)    < 0		THEN 'Sold'
							WHEN ISNULL(opening_date,'')  != ''		THEN 'Opening'
							WHEN ISNULL(purchase_date,'') != ''		THEN  'Bought'
							ELSE ''
						END  AS  'Type'
				from #mainoutputtable_1_Final_Brokerwise_Month 
				WHERE ISNULL(closing_qty,0) <> 0
				ORDER BY Trans_No			
			END
			ELSE IF(@OUTPUT_Flag='Annexture')
				BEGIN
				 SELECT	'' opening_bill_no,
						0 id,
						0 prioritys,
						ScriptCode,
						'' 'Family_Name',
						MemberName 'Member_Name',
						'' 'Family_Code',
						MemberCode 'Member_Code',
						script_name 'Script Name',  
						Holding_Type,
						NULL 'Opening Date', 
						SUM(ISNULL(opening_qty,0)) 'Opening Qty', 
						CASE WHEN SUM(opening_qty) != 0
							 THEN SUM(opening_amount)/ NULLIF(SUM(opening_qty),0)  
							 ELSE 0
						END  'Opening Rate', 
						SUM(opening_amount) 'Opening Amount',
						NULL 'Purchase Date',
						'' AS 'Purchase BillNo', 
						SUM(ISNULL(purchase_qty,0))  'Purchase Qty', 
						SUM(ISNULL(purchase_amount,0))  / nullif(SUM(ISNULL(purchase_qty,0)),0) 'Purchase Rate', 
						SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
						NULL 'Sold Date', 
						'' AS 'Sold BillNo', 
						SUM(ISNULL(sold_qty,0)) 'Sold Qty', 
						CASE	WHEN SUM(sold_qty) != 0
								THEN SUM(ISNULL(sold_amount,0))/nullif(SUM(sold_qty),0)   
								ELSE 0
						END  'Sold Rate',
						SUM(ISNULL(sold_amount,0)) 'Sold Amount', 
						SUM(ISNULL(gain_loss,0) ) 'Gain/Loss', 
						SUM(ISNULL(gain,0))  'Gain', 
						SUM(ISNULL(loss,0))  'Loss',
						SUM(ISNULL(closing_qty,0))  'Closing Qty', 
						CASE  WHEN SUM(closing_qty) != 0
							  THEN (SUM(closing_value) / SUM(NULLIF(closing_qty,0))) 
							  ELSE 0
						END  'Closing Rate',
						SUM(closing_value)  'Closing Value', 
						SUM(ISNULL(short_term,0))  as short_term, 
						SUM(ISNULL(long_term,0)) as long_term,
						SUM(ISNULL(speculation,0)) as speculation, 
						SUM(ISNULL(gain_speculation,0))gain_speculation, 
						SUM(ISNULL(loss_speculation,0))loss_speculation,   
						'' consultant_name, 
						0 nse_rate,
						0 bse_rate,
						1 sort,
						broker_code 					
				FROM
					(
						SELECT MAX(id+0)id ,MAX (prioritys+0) prioritys,'' opening_bill_no,ScriptCode, script_name,   Holding_Type,'' 'Opening Date',
						SUM(ISNULL(opening_qty,0)) 'Opening_Qty',sum(ISNULL(opening_rate,0)) opening_rate ,SUM(ISNULL(opening_amount,0)) 'Opening_Amount',
						'' 'Purchase Date','' purchase_bill_no,SUM(ISNULL(purchase_qty,0)) 'Purchase_Qty',
						 SUM(ISNULL(purchase_rate,0)) purchase_rate,SUM(ISNULL(purchase_amount,0)) 'Purchase_Amount',
						'' 'Sold Date',sold_bill_no ,SUM(ISNULL(sold_qty,0)) 'Sold_Qty', SUM(sold_rate)sold_rate  , SUM(ISNULL(sold_amount,0)) 'Sold_Amount',SUM(ISNULL(gain_loss,0)) 'Gain_Loss',SUM(ISNULL(gain,0)) 'Gain',SUM(ISNULL(loss,0)) 'Loss',
						SUM(ISNULL(closing_qty,0)) 'Closing_Qty',
						SUM(ISNULL(closing_rate,0)) 'Closing_Rate',SUM(ISNULL(closing_value,0)) 'Closing_Value',
						sum(ISNULL(short_term,0)) as short_term,
						sum(ISNULL(long_term,0)) as long_term,
						sum(ISNULL(speculation,0)) as speculation,
						SUM(ISNULL(gain_speculation,0)) gain_speculation,
						SUM(ISNULL(loss_speculation,0)) loss_speculation,  Broker_name,0 nse_rate,0 bse_rate,1 sort,MemberCode,MemberName,
						MA.AC_Code as 'broker_code'
						FROM #mainoutputtable_1_Final_Brokerwise_Month F
						LEFT JOIN MST_Account MA ON MA.AC_Name = F.Broker_name AND MA.Member_Code in (SELECT Value FROM membercodestable(@memcode,','))  AND MA.Year_Code = @yearcode
						GROUP BY MemberCode,MemberName,Broker_name,ScriptCode,script_name, Holding_Type,purchase_bill_no,sold_bill_no ,opening_date,purchase_date,sold_date,isintradaycol,MA.AC_Code,MA.AC_Name
					)a
					GROUP BY  a.MemberCode,a.MemberName,a.broker_code,Broker_name,a.ScriptCode,script_name ,Holding_Type
					ORDER BY  MemberName,Broker_name,Holding_Type ,script_name,sort
				END
				ELSE IF(@OUTPUT_Flag='Summary')
			BEGIN
			
				Insert into #mainoutputtable_1_Final_Summary
				SELECT  prioritys ,Trans_No,id ,  ScriptCode,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,
				CONVERT(date, purchase_date,101),purchase_bill_no,purchase_qty ,purchase_rate ,purchase_amount ,
				CONVERT(date, sold_date,101),sold_bill_no ,sold_qty ,sold_rate,sold_amount ,gain_loss ,gain ,loss,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate,0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort 
				,isintradaycol,Last_Date,Strike_Price,OptionType
				FROM #mainoutputtable_1_Final_Brokerwise_Month
				ORDER BY Broker_name,script_name,CONVERT(date, purchase_date,101)

				SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
				T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
				T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
				T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
				T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
				T1.Broker_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt ,  
				Isnull(Dr.Bse_FO_Rate,0) AS 'bse_rate', /**/
				Isnull(Dr.Nse_FO_Rate,0) AS 'nse_rate' /**/
		
				INTO #alldata_Summary 
				FROM #mainoutputtable_1_Final_Summary  T1
				LEFT JOIN BrokerBill T2 ON T1.Trans_No=T2.Trans_no
				LEFT JOIN DailyRate  DR  
				ON 
					DR.InvestmentType != 0 and Dr.InvestmentType != 2 AND
					DR.Script_Code = T1.ScriptCode 
					and 
				     dr.Trans_Dt =  Convert(varchar,@Todate,101)
					 AND 
					Convert(varchar,DR.Expir_Date ,101) =  Convert(varchar,T1.Last_Date,101)
					 AND
					ISNULL(Substring(RTRIM(LTRIM(T1.OptionType)),0,3),'') = ISNULL( DR.OptionType,'')
					 AND
					ISNULL(DR.Strike_Price,0) = ISNULL(T1.Strike_Price,'')
				ORDER BY Broker_name

		
				TRUNCATE TABLE #mainoutputtable_1_Final_Summary

				INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
				opening_date,opening_qty,opening_rate,opening_amount,
				purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
				sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
				closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
				Broker_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt) 

				SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
				opening_date,opening_qty,opening_rate,opening_amount,
				purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
				sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
				closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
				Broker_name,
				Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
				sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 
				FROM #alldata_Summary  


				GROUP BY Broker_name,id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
				opening_date,opening_qty,opening_rate,opening_amount,
				purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
				sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
				closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
				sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 
				ORDER BY Broker_name

																																																																																																																																																																																																																																																																																																																																																																																																																						IF(@RecordOnlyhavingClosingbalanceZero = 0)
			   IF(@RecordOnlyhavingClosingbalanceZero = 0)
			    BEGIN
			    	IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
					BEGIN			
						SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',
						SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
						CASE
							WHEN closing_qty < 0 THEN sold_date
							WHEN ISNULL(opening_date,'') != '' THEN opening_date
							WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
						END  AS  'Closing Date',
						bse_rate  AS  'BSERATE',
						bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
						CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
						nse_rate AS  'NSERATE',
						nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
						CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
						SUM(gain_loss) AS 'Profit/Loss',
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
								ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
							0 END 
							END AS 'Avg. Rate',

						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
								ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
							0 END 
							END AS 'Value After Profit/Loss',
						SUM(ISNULL(Other_amt,0))Other_amt,  Broker_name
						FROM #mainoutputtable_1_Final_Summary
						GROUP BY holding_type,script_name,bse_rate,nse_rate,
						CASE
							WHEN closing_qty < 0 THEN sold_date
							WHEN ISNULL(opening_date,'') != '' THEN opening_date
							WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
						END,bse_rate,nse_rate,Broker_name
						HAVING SUM(closing_qty) != 0
					END
					ELSE IF(@WithActualAvgRate = 1 OR @DateWiseClosinStock = 1)
					BEGIN
					
						SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
						CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
						bse_rate  AS  'BSERATE',
						bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
						CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
						nse_rate AS  'NSERATE',
						nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
						CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
						SUM(gain_loss) AS 'Profit/Loss',
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
								ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
							0 END 
							END AS 'Avg. Rate',

						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
								ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
							0 END 
							END AS 'Value After Profit/Loss',
						SUM(ISNULL(Other_amt,0))Other_amt,  Broker_name
						FROM #mainoutputtable_1_Final_Summary
						GROUP BY Broker_name,holding_type,script_name,
						CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
						END,
						bse_rate,nse_rate
						HAVING SUM(closing_qty) != 0
					
					END
					ELSE IF(@WithActualAvgRate = 0)
					BEGIN
					  
						SELECT holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
						bse_rate  AS  'BSERATE',
						bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
						CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
						nse_rate AS  'NSERATE',
						nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
						CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
						SUM(gain_loss) AS 'Profit/Loss',
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
							END AS 'Avg. Rate',

						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
							END AS 'Value After Profit/Loss',
						0 Other_amt, Broker_name
						FROM #mainoutputtable_1_Final_Summary
						GROUP BY Broker_name,holding_type,script_name,bse_rate,nse_rate 
						HAVING SUM(closing_qty) != 0
					END
			END
		ELSE IF(@RecordOnlyhavingClosingbalanceZero = 1)
			BEGIN
				IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
					BEGIN
						SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
						CASE
							WHEN closing_qty < 0 THEN sold_date
							WHEN ISNULL(opening_date,'') != '' THEN opening_date
							WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
						END  AS  'Closing Date',
						bse_rate  AS  'BSERATE',
						bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
						CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
						nse_rate AS  'NSERATE',
						nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
						CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
						SUM(gain_loss) AS 'Profit/Loss',
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
								ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
							0 END 
							END AS 'Avg. Rate',

						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
								ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
							0 END 
							END AS 'Value After Profit/Loss',
						SUM(ISNULL(Other_amt,0))Other_amt,  Broker_name
						FROM #mainoutputtable_1_Final_Summary
						GROUP BY Broker_name,holding_type,script_name,bse_rate,nse_rate ,
						CASE
							WHEN closing_qty < 0 THEN sold_date
							WHEN ISNULL(opening_date,'') != '' THEN opening_date
							WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
						END
						HAVING SUM(closing_qty) = 0
					END
				else IF (@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0)
					BEGIN
						SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
						''  'Closing Date',
						bse_rate  AS  'BSERATE',
						bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
						CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
						nse_rate AS  'NSERATE',
						nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
						CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
						SUM(gain_loss) AS 'Profit/Loss',
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
								ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
							0 END 
							END AS 'Avg. Rate',

						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
								ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
							0 END 
							END AS 'Value After Profit/Loss',
						SUM(ISNULL(Other_amt,0))Other_amt,  Broker_name
						FROM #mainoutputtable_1_Final_Summary
						GROUP BY Broker_name,holding_type,script_name,bse_rate,nse_rate  
					END

				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
						bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
						bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
						CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
						nse_rate AS  'NSERATE',
						nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
						CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
						SUM(gain_loss) AS 'Profit/Loss',
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
								ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
							0 END 
							END AS 'Avg. Rate',

						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
								ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
							0 END 
							END AS 'Value After Profit/Loss',
						0 Other_amt,'' Broker_name
						FROM #mainoutputtable_1_Final_Summary
						GROUP BY holding_type,script_name,bse_rate,nse_rate
						HAVING SUM(closing_qty) = 0
					END
			END

		END
	END

		DROP TABLE #mainoutputtable_1_Broker_month_wise 
		 
		DROP TABLE #alldata 
		 



































GO
/****** Object:  StoredProcedure [dbo].[proc_MonthWise_Stockholdingposition_Equity]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_MonthWise_Stockholdingposition_Equity]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_MonthWise_Stockholdingposition_Equity] AS' 
END
GO





-- proc_Stockholdingposition_Equity 0,0,'0','A0001','1120172018','05/01/2017','04/30/2017','','','','', '0' ,'0','ClosingStocks'
-- proc_MonthWise_Stockholdingposition_Equity 0,0,'0','Y0001','1120172018','04/01/2017','03/31/201','','0','','', '0' ,'1','details'
-- proc_MonthWise_Stockholdingposition_Equity 0,0,'0','30001','1120182019','2018-04-01 12:00:00:00','2019-03-31 03:50:37:50','','','','', '0' ,'','Details',0,0,0,0
ALTER  PROCEDURE [dbo].[proc_MonthWise_Stockholdingposition_Equity] --0,0,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','ScriptWiseTotal'

(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),
@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX),@IsWithTax bit = 0,@IsScripWise bit = 1,@RecordOnlyhavingClosingbalanceZero bit = 0,@WithActualAvgRate bit = 0, 
@DateWiseClosinStock  bit = 0, @IsLTCG bit=0,@IsBSEISIN bit=0)
AS 
  BEGIN 
	  SET NOCOUNT ON;
		DECLARE @StartYearDate varchar(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate = CONVERT(VARCHAR(10),@StartYearDate,101)
		CREATE TABLE #mainoutputtable_1_MonthWise
        ( 
		   pkid INT identity(1,1), 
		   Dup_pkid INT, Trans_No VARCHAR(20),
		   Ac_type VARCHAR(100),
		   id INT,
		   sr_no int,
		   prioritys INT,
		   Trans_Type  VARCHAR(100), 
		   Split_Type VARCHAR(100), 
		   Flag_Type VARCHAR(100),
		   Flag_Type_Sold VARCHAR(100),
		   flag_script_name  VARCHAR(Max),
		   flag_holding_type VARCHAR(Max), 
		   script_name  VARCHAR(Max),
		   holding_type VARCHAR(Max),
		   opening_bill_no VARCHAR(50),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount AS( [opening_qty] * [opening_rate] ), 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount AS( 
		   purchase_qty * purchase_rate ), 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount AS ( sold_qty * sold_rate ), 
           gain_loss float,
		   closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0))-(ISNULL([sold_qty],0)) END ), 

           closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
		   closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
		   short_term FLOAT DEFAULT 0,
		   long_term  FLOAT DEFAULT 0,
           speculation  FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,	   
		   isintradaycol INT,[type] VARCHAR(100) , ScriptCode Varchar(50) ,
		   Broker_Code VARCHAR(100),Dp_code VARCHAR(100),Consultant_code VARCHAR(20)
        )  

		 CREATE TABLE #mainoutputtable_1_MonthWise_Final_BSE_ISISNo
        ( 
		   pkid int,
		   Dup_pkid int, 		 
           Trans_No VARCHAR(50),
		   Ac_type VARCHAR(100),
		   id INT,
		   sr_no int,
		   prioritys INT,
		   Trans_Type  VARCHAR(100),
		   Split_Type VARCHAR(100), 
		   Flag_Type VARCHAR(100),
		   Flag_Type_Sold VARCHAR(100),
		   flag_script_name  VARCHAR(Max),
		   flag_holding_type VARCHAR(Max), 
		   script_name  VARCHAR(Max),
		   holding_type VARCHAR(Max),
		   opening_bill_no VARCHAR(100),		     
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,	  
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,		   
		   isintradaycol INT,
		   [type] VARCHAR(100),		  
		   ScriptCode Varchar(50) ,
		   Broker_Code VARCHAR(100),
		   Dp_code  VARCHAR(100),
		   Consultant_code VARCHAR(20)     
	   )

	     CREATE TABLE #mainoutputtable_1_MonthWise_Final
        ( 
		   pkid int,
		   Dup_pkid int, 
		   OrderBy varchar(100),
           Trans_No VARCHAR(50),
		   Ac_type VARCHAR(100),
		   id INT,
		   sr_no int,
		   prioritys INT,
		   Split_Type VARCHAR(100), 
		   Flag_Type VARCHAR(100),
		   Flag_Type_Sold VARCHAR(100),
		   flag_script_name  VARCHAR(Max),
		   flag_holding_type VARCHAR(Max), 
		   script_name  VARCHAR(Max),
		   holding_type VARCHAR(Max),
		   opening_bill_no VARCHAR(100),		     
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,		   
		   isintradaycol INT,
		   [type] VARCHAR(50),
		   sort   VARCHAR(5) , 
		   ScriptCode Varchar(50) ,
		   Broker_Code VARCHAR(100),
		   Dp_code  VARCHAR(100),
		   Consultant_code VARCHAR(20)
       
	   ) 

	    CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
			prioritys INT,
			Trans_No VARCHAR(50),
			id INT,
			Ac_type VARCHAR(100),
			Broker_Code VARCHAR(20),
			Consultant_Code varchar(20), 
			ScriptCode  VARCHAR(50), 
			script_name  VARCHAR(Max),
			holding_type VARCHAR(Max),
			flag_script_name  VARCHAR(Max),
			flag_holding_type VARCHAR(Max),
			opening_date VARCHAR(10),opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
			purchase_date VARCHAR(10),purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
			sold_date VARCHAR(10),sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
			gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
			closing_qty FLOAT DEFAULT 0, 
			closing_rate FLOAT DEFAULT 0,
			closing_value FLOAT DEFAULT 0,
			short_term FLOAT DEFAULT 0,
			long_term FLOAT DEFAULT 0, 
			speculation FLOAT DEFAULT 0, 
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			consultant_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			Other_amt FLOAT DEFAULT 0,
			ServTax_Amt FLOAT DEFAULT 0,
			Stt_amt FLOAT DEFAULT 0,
			sort   VARCHAR(5),
			isintradaycol  INT 
        ) 

	    CREATE TABLE #Openings
        (
		   id INT, 
		   Trans_No VARCHAR(20),
		   sr_no int,
		   script_name  VARCHAR(Max),
		   script_Code  VARCHAR(50),
		   holding_type VARCHAR(Max),
		   Act_Type     varchar(50),
		   Broker_Code  VARCHAR(100),
		   Consultant_Code  VARCHAR(50),
		   DP_Code  VARCHAR(50),
		   bill_no VARCHAR(100),		     
           trans_dt Datetime,
		   qty  FLOAT DEFAULT 0,
		   rate  FLOAT DEFAULT 0,
		   amount FLOAT DEFAULT 0, 
           isintraday bit DEFAULT 0, 
		   consultant_name VARCHAR(500),
		   BillType varchar(100)
	   ) 

		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty FLOAT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(100)
		DECLARE @showIntraday INT ,@ScriptId VARCHAR(50) ,@Ac_Types VARCHAR(50) 
		IF(@status=0)
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
				@openingDate VARCHAR(50),@openingRate FLOAT,@openingQty FLOAT,@openingAmount FLOAT,
				@purchaseDate VARCHAR(50),@PurchaseBillNo  VARCHAR(100),@purchaseRate FLOAT,@purchaseQty FLOAT,@purchaseAmount FLOAT,
				@soldDate VARCHAR(50),@soldBillNo  VARCHAR(100),@soldRate FLOAT,@soldQty FLOAT,@soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50),@Consultant_Name  VARCHAR(100), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(100),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,
				@PurchaseIntraFlag VARCHAR(100),@SaleIntraFlag VARCHAR(10),@BillType varchar(100)
	
				DECLARE @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@Sr_No INT,@Broker_code VARCHAR(100),@Dp_code VARCHAR(100),@Consultant_code VARCHAR(20),@Dup_pkid int, @Pkid varchar(100),@idcount int  

				CREATE TABLE #SCriptCodes_MonthWise
				(
					ScriptCode varchar(MAX)
				)

				IF(@ScriptCode != '')
					INSERT INTO #SCriptCodes_MonthWise SELECT value FROM Fn_split(@ScriptCode, ',') 
				ELSE 
					INSERT INTO #SCriptCodes_MonthWise select BBT.Script_Code from mst_script 
					INNER JOIN BrokerBill_Trans  BBT ON BBT.Script_Code=Mst_Script.Script_Code  
					GROUP BY BBT.Script_Code

				CREATE TABLE #ConsultantCodes_MonthWise
				(
					ConsultantCodes varchar(MAX)
				)
				
				IF(@ConsultantCode = '0')	
					BEGIN
						SELECT DISTINCT p.member_code,p.year_code,
							STUFF((	SELECT distinct ',' + p1.Consultant_Code
									FROM Mst_Consultant p1
									FOR XML PATH(''), TYPE
									).value('.', 'NVARCHAR(MAX)')
							,1,1,'') ConsultantCode
						into #temoConsultant
						FROM Mst_Consultant p
						SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant )--WHERE member_code = @memcode AND year_code = @yearcode)
						DROP table #temoConsultant
					END
								 
				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes_MonthWise SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes_MonthWise select MC.Consultant_Code from Mst_Consultant MC
					JOIN BrokerBill_Trans BBT ON BBT.Consultant_code = MC.Consultant_Code
					GROUP BY MC.Consultant_Code  
					 
				SELECT  ROW_NUMBER ( ) OVER (ORDER BY t.script_code,t.Ac_Type,t.trans_dt ) AS NameId,	t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,t.TransType,t.Ac_Type,t.Script_Code, t.Qty,
				Case When @IsWithTax = 0 Then t.Rate Else t.Exp_Rate END As 'Rate',--t.Rate,`
				t.Member_code,t.YearCode,t.Consultant_code,t.isFNOBill,  t.isIntraDay, t.FrmNm,t.ID,
				Ms.bse_code,Ms.nse_code,Ms.script_name,UPPER(ma.ac_name) AS 'Holding Type',
					CASE    WHEN TransType='Sold' THEN 'Sold' 
					        WHEN (((t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101))AND t.TransType='Bought') THEN 'Opening'
							WHEN TransType   = 'Bought' AND t.Bill_no = 'Bonus' THEN 'Bonus' 
							WHEN TransType   = 'Bought' AND t.Bill_no ='Rights'THEN 'Rights' 
							WHEN TransType   = 'Bought' AND  t.Bill_no ='Split' THEN 'Split' 
							WHEN TransType='Bought' AND  t.Bill_no ='Transfer' THEN 'Transfer' 						
							WHEN TransType='Bought' AND Frmnm = 'IPO' THEN 'IPO'  
							WHEN TransType='Bought' AND Frmnm='MFDRI' THEN 'Devidend Re-Investment'
							WHEN t.TransType = 'Bought' AND  t.Bill_no != 'Opening'  THEN 'Bought' 
					     	END AS 'Flag_Type',
						ISNULL(cm.Consultant_Name,'')Consultant_Name,
						ISNULL(BB.Broker_Code,'') Broker_Code,'' dp_code --,t.isstock 
				INTO #alldata
				FROM brokerbill_trans t  WITH (NOLOCK)
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN mst_account ma ON t.ac_type = ma.ac_code AND ma.member_code = @memcode AND ma.Year_Code=@yearcode
				LEFT JOIN Mst_Consultant cm ON t.Consultant_code = cm.Consultant_code
				LEFT JOIN BrokerBill BB oN BB.Trans_No=t.Trans_No  AND BB.Member_Code=@memcode AND BB.YearCode=@yearcode
				WHERE 
				t.isfnobill = @Investmenttype  
				AND t.trans_dt >=  @Fromdate AND t.trans_dt <= @Todate 
				AND t.member_code = @memcode AND t.yearcode = @yearcode  AND 
				t.Ac_Type =(CASE WHEN  @Ac_Type='0' THEN t.Ac_Type  ELSE  @Ac_Type END)
				AND	t.script_code IN (SELECT * FROM #SCriptCodes_MonthWise)
				AND	t.Consultant_code IN (SELECT * FROM #ConsultantCodes_MonthWise)
				AND ISNULL(t.isIntraDay,0) = (CASE WHEN ISNULL(@IsIntraDay,0)=0 THEN ISNULL(isIntraDay,0) ELSE ISNULL(@IsIntraDay,0) END) 
				AND t.MergedEntry=0 AND ISNULL( t.Ref_SrNo,0) != 1
				AND (IsSLBS=0 OR IsSLBS IS NUll) 
				GROUP BY t.Trans_Dt,t.Trans_No,t.Sr_No,t.Script_Code,script_name,t.Ac_Type,ma.AC_Name,t.Consultant_code,cm.Consultant_Name ,BB.Broker_Code, 
				t.Bill_no,TransType,t.Qty,Rate,t.Exp_Rate,t.Amount,Stt_Amount,t.Member_Code,t.YearCode,t.MergedEntry,t.isFNOBill,isIntraDay,FrmNm,ID,bse_code,nse_code
			 	 
				--Select * from #alldata

				DECLARE @isIntradayCol INT 
				DECLARE  @COUNT INT = 0
				DECLARE @ToDATEfORcLOSIng VARCHAR(15) =  CONVERT(Varchar,CONVERT(DATETime,@fROMdATE,101) - 1,101)
				
				INSERT INTO #Openings
				EXECUTE proc_Stockholdingposition_Equity 0,@Investmenttype,@Ac_Type,@memcode,@Yearcode,@FromDate,@ToDATEfORcLOSIng,@ScriptCode,@ConsultantCode,@BSE_NSE_Code,@Is_BFCF,'0','','ClosingStocks',@IsScripWise,@IsWithTax,1,@IsLTCG 
					
				--Select * from #Openings

				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT	*
				FROM #Openings 
				WHERE BillType = 'Opening'
			    UNION ALL 
				SELECT   id,Trans_No,Sr_No,script_name,Script_Code,[holding type],Ac_type,Broker_Code,Consultant_code  ,DP_Code, Bill_no,CONVERT(VARCHAR(10), trans_dt,101),qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name,'Opening'
				FROM #alldata WHERE  
				Flag_Type = 'Opening'
				
				
				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No,@Sr_No, @scriptname,@ScriptId,@holding_type,@Ac_types,@Broker_Code, @Consultant_code  ,@DP_Code, @billno,@dates,@qty, @rate, @amount, @isIntradayCol ,@Consultant_Name, @BillType
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
					
						IF(@Investmenttype=2)
							SET @holding_type='Mutual Fund'
						SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
						SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
						SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
						SET @Dup_pkid = ISNULL(@Dup_pkid,0)
						SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
						SET @Dup_pkid = @Dup_pkid + 1
						DECLARE @IDs INT=0

						INSERT INTO #mainoutputtable_1_MonthWise
							(Dup_pkid,Sr_No,  opening_bill_no ,id, DP_Code,ScriptCode,Broker_Code, Consultant_code  , Trans_No,Ac_type,  Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,consultant_name,Trans_Type) 
						VALUES
							(@Dup_pkid,@Sr_No, @billno,@ID,@Dp_code,@ScriptId,@Broker_code,@Consultant_code,@Trans_No,@Ac_types,'Opening',@scriptname,@holding_type,@dates,ABS(@qty),@rate,@isIntradayCol ,@Consultant_Name,'Opening')
							
							 
						SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),0) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  

						IF(@idcount > 0)
							BEGIN
								UPDATE #mainoutputtable_1_MonthWise SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
							END
						        FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No,@Sr_No, @scriptname,@ScriptId,@holding_type,@Ac_types,@Broker_Code, @Consultant_code  ,@DP_Code, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@BillType
					END 
				CLOSE alldatacursor 
				DEALLOCATE alldatacursor

				DECLARE @tablerowscount INT
				DECLARE @salecount INT = 0,@Boughtcount INT = 0,@Flag_Type VARCHAR(100)
			
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
				Select id,sr_no,bill_no,BillType,BillType,script_name,script_Code,holding_type,Act_Type,Broker_Code,Consultant_Code,DP_Code,Trans_No,CONVERT(VARCHAR(10), trans_dt,101),qty,rate,amount, ISNULL(isintraday, 0)isIntraDay,consultant_name
				from #Openings
				WHERE BillType != 'Opening'
				UNION ALL 
				SELECT   id,Sr_No, Bill_no,Flag_Type,TransType,script_name,Script_Code, [holding type],Ac_type,Broker_Code, Consultant_code  ,DP_Code, Trans_No,CONVERT(VARCHAR(10), trans_dt,101), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name
				FROM #alldata WHERE  
				(TransType in('Bought','Sold')  AND CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
				
				--Select * from #Openings
				
				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Sr_No, @billno,@Flag_Type , @TransType, @scriptname,@ScriptId,@holding_type,@Ac_types,@broker_Code, @Consultant_code  ,@DP_Code, @Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
				WHILE (@@FETCH_STATUS = 0)
						BEGIN
							--Select * from #mainoutputtable_1_MonthWise
							SET @COUNT = 0
							DECLARE @IsOpening INT = 0, @prioritysId INT=0, @str VARCHAR(MAX)=''	, @purchase_Op_Qty FLOAT =0,
							@purchase_Op_Bill VARCHAR(20)='',@purchase_Op_Date VARCHAR(20)='',@purchase_Op_Rate FLOAT=0,
							@PurQTY FLOAT = 0,@BalPurQTY FLOAT = 0,@BalSoldQTY FLOAT = 0,@Balpurchase_Op_Qty FLOAT=0,
							@BalOpeningQTY FLOAT = 0, @Sold_Qty FLOAT = 0, @tempID INT = 0
							
							IF(@isIntradayCol=0)
								BEGIN
									IF(@Investmenttype=2)
										 SET @holding_type='Mutual Fund'

									IF(@TransType LIKE '%Bought%')
										BEGIN
										
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (	SELECT COUNT(*)
															FROM #mainoutputtable_1_MonthWise 
															WHERE holding_type = @holding_type 
															AND script_name=@scriptname 
															AND Flag_Type_Sold = 'Sold'  
															AND Flag_Type ='Sold' 
															AND ISNULL(sold_qty,0) !=0 
															AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) 
															AND isintradaycol = 0  
															AND consultant_name = (CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
											
											IF (@COUNT > 0)
												BEGIN
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  Ac_Type,scriptcode, CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,* 
													INTO #tempSoldValExists 
													FROM #mainoutputtable_1_MonthWise 
													WHERE holding_type = @holding_type 
															AND script_name=@scriptname 
															AND Flag_Type_Sold = 'Sold'  
															AND Flag_Type ='Sold' 
															AND ISNULL(sold_qty,0) !=0 
															AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) 
															AND isintradaycol = 0  
															AND consultant_name = (CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
													ORDER BY NameId
													
													DECLARE @R_Sold_COUNT FLOAT = ( SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty FLOAT 
													WHILE(@R_Sold_COUNT  > 0 )
														BEGIN
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists ORDER BY Dup_pkid,NameId)
															SET @str = @TransType
															SET @Sold_Qty = (SELECT TOP(1) sold_qty  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @soldDate = (SELECT TOP (1) sold_date  FROM #tempSoldValExists WHERE id = @tempSaleID )
															SET @soldRate = (SELECT TOP (1) sold_rate  FROM #tempSoldValExists WHERE id = @tempSaleID )
															SET @soldBillNo = (SELECT TOP (1) sold_bill_no  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @purchase_Op_Qty = @qty
														 
															IF(@TransType='Opening')
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise  
																	SET	
																	opening_date=@dates,
																	opening_rate=@rate,
																	opening_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																	Flag_Type = 'Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid
																END
															ELSE IF(@TransType = 'Bought')
																BEGIN
																	
																	UPDATE #mainoutputtable_1_MonthWise  
																	SET	
																	purchase_date=@dates,
																	purchase_bill_no=@billno,
																	purchase_rate=@rate,
																	purchase_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																	Flag_Type = 'Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(purchase_qty,0)=0 AND pkid = @pkid
																END
															if(@Sold_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise  
																	SET	sold_qty = @purchase_Op_Qty WHERE  id  = @tempSaleID AND Flag_Type_Sold='Sold' AND pkid = @pkid
																END
															
															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND pkid = @pkid
															DECLARE @Balancedval   FLOAT = Round((ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)),6) /* This is related to pending sold qty from table. If it is Negative then 
															 it will save into sale data else it is positive means Bought is greater So it will be inserted into Purchase Entry */
															
															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempSoldValExists)
															IF(@Balancedval  < 0)
																BEGIN
																	--SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	--Select @Dup_pkid

																	SET @soldQty = ABS(@Balancedval) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise) 
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																
																	INSERT INTO #mainoutputtable_1_MonthWise(ID,Sr_No, Dup_pkid, DP_Code,ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Trans_No, Flag_Type,Flag_Type_Sold,  prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name,Trans_Type)
																	VALUES(@tempSaleID , @Sr_No, @Dup_pkid ,@DP_Code,@ScriptId,@Ac_Types ,@Broker_Code, @Consultant_code  ,@Trans_No,'Sold','Sold', @prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	UPDATE #mainoutputtable_1_MonthWise SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  

																	IF(@idcount>0)
																		BEGIN
																			UPDATE #mainoutputtable_1_MonthWise SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																		SET @Balancedval = 0
																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount=0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId = (SELECT MAX(prioritys+1) FROM #mainoutputtable_1_MonthWise)

																	IF(@TransType='Opening')
																		BEGIN
																			INSERT INTO #mainoutputtable_1_MonthWise(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name,Trans_Type)
																			VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId,@Ac_Types ,@Broker_Code,  @Consultant_code  ,'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																			UPDATE #mainoutputtable_1_MonthWise SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	ELSE IF(@TransType='Bought')
																		BEGIN
																			INSERT INTO #mainoutputtable_1_MonthWise(ID,Sr_No, Dup_pkid,DP_Code,Trans_No, ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																			VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId,@Ac_Types ,@Broker_Code, @Consultant_code  , 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																			UPDATE #mainoutputtable_1_MonthWise SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																		SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #mainoutputtable_1_MonthWise SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																	ENd
															ELSE IF(@Balancedval=0)
																BEGIN
																	break;
																END
															SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
															SET @qty = @Balancedval
															 
														END
													DROP TABLE #tempSoldValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													--SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise)
													--SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1_MonthWise)
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise)
													SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0)+1 from #mainoutputtable_1_MonthWise)

													INSERT INTO #mainoutputtable_1_MonthWise (id,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type,Broker_Code, Consultant_code  , prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name,Trans_Type) 
													VALUES ( @ID,@Sr_No, ISNULL(@Dup_pkid,0),@DP_Code,@Trans_No,@ScriptId,@Ac_Types,@Broker_Code, @Consultant_code  , @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name,@Flag_Type) 
												END

										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
											--SET @COUNT = (SELECT Count(*) FROM #mainoutputtable_1_MonthWise WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') AND ISNULL(sold_qty,0)=0  AND isnull(isintradaycol,0)=0 AND consultant_name= @Consultant_Name  )
											SET @COUNT = (SELECT Count(*) FROM #mainoutputtable_1_MonthWise WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer','Devidend Re-Investment') AND ISNULL(sold_qty,0)=0  AND isnull(isintradaycol,0)=0 AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  Ac_type,ScriptCode,case when opening_date <> NULL then opening_date else purchase_date end) AS NameId,* 
													INTO #tempValExists 
													FROM
													#mainoutputtable_1_MonthWise WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer','Devidend Re-Investment') 
													AND (consultant_name = CASE WHEN  @ConsultantCode <> '' THEN  @Consultant_Name ELSE consultant_name END) 
													AND ISNULL(sold_qty,0) = 0  AND isintradaycol = 0 
													ORDER BY NameId
													
													DECLARE @RCOUNT INT = (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty FLOAT 
													 
													WHILE(@RCOUNT > 0 )
														BEGIN 
															SET @Sold_Qty= @qty
														 
															SET @tempID = (SELECT TOP(1) id FROM #tempValExists ORDER BY dup_pkid)
															SET @str = (SELECT TOP(1) Flag_Type FROM #tempValExists WHERE id = @tempID  )
															
															IF(@str='Opening')
																BEGIN
																	SET @TempSoldQty=(SELECT TOP(1) opening_qty  FROM #tempValExists WHERE id  = @tempID)
																	SET @openingDate=(SELECT TOP(1) opening_date FROM #tempValExists WHERE id  = @tempID)
																	SET @openingrate=(SELECT TOP(1) opening_rate FROM #tempValExists WHERE id  = @tempID)
																	SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempValExists WHERE id  = @tempID )
																END
															ELSE IF(@str='Bought')
																BEGIN
																	SET @TempSoldQty=(SELECT TOP(1) purchase_qty FROM #tempValExists WHERE id  = @tempID)
																	SET @PurchaseDate=(SELECT TOP(1) purchase_date FROM #tempValExists WHERE id  = @tempID)
																	SET @Purchaserate=(SELECT TOP(1) purchase_rate FROM #tempValExists WHERE id  = @tempID)
																	SET @PurchaseBillNo=(SELECT TOP(1) purchase_bill_no FROM #tempValExists WHERE id  = @tempID)
																	SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempValExists WHERE id  = @tempID )
																END

															IF(@Sold_Qty > 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	UPDATE #mainoutputtable_1_MonthWise  
																		SET	
																			opening_qty = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							END,
																			purchase_qty  = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							END,
																			sold_date = @dates,
																			sold_bill_no = @billno,
																			sold_rate = @rate,
																			sold_qty = CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold = 'Sold',
																			prioritys = @prioritysId
																	WHERE  id = @tempID AND ISNULL(sold_qty,0)=0 AND pkid = @Pkid
																	SET @Balanceval = Round((ABS(@Sold_Qty) - ABS(@TempSoldQty)),6)
																END
															--select * from #mainoutputtable_1_MonthWise
															DELETE FROM #tempValExists WHERE id = @tempID AND pkid = @pkid
															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempValExists)
															SET @RCOUNT = @RCOUNT - 1
															--SET @Sold_Qty = @qty
														
															IF(@Balanceval < 0)
																BEGIN
																	--SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId )--AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	 
																	IF(@str='Opening')
																		BEGIN
																			SET @openingQty = ABS(@Balanceval) 
																			SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise)-- WHERE id=@tempID)
																			SET @prioritysId = ISNULL(@prioritysId,0)+1
																			INSERT INTO #mainoutputtable_1_MonthWise(ID,opening_bill_no, Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code,  Consultant_code  ,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name,Trans_Type)
																			VALUES(@tempID,'Opening',@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																			
 																			
																			SET @prioritysId = ISNULL(@prioritysId,0)+1
																			UPDATE #mainoutputtable_1_MonthWise SET prioritys=@prioritysId   WHERE prioritys >= @prioritysId AND ID <> @tempID
																		END
																	ELSE 
																		BEGIN
																			SET @PurchaseQty = ABS(@Sold_Qty) 
																			SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise)-- WHERE id=@tempID)
																			SET @prioritysId = ISNULL(@prioritysId,0)+1
																			INSERT INTO #mainoutputtable_1_MonthWise(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code, Consultant_code  , ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																			VALUES(@tempID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																			SET @prioritysId = ISNULL(@prioritysId,0)+1
																			UPDATE #mainoutputtable_1_MonthWise SET prioritys=@prioritysId    WHERE prioritys >= @prioritysId AND ID <> @tempID
																		END
																	 
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(MAX),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(MAX),(SELECT ISNULL(MAX(pkid),1) FROM #mainoutputtable_1_MonthWise  )) END)  
																	--select  @Pkid,* from #mainoutputtable_1_MonthWise
																	
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #mainoutputtable_1_MonthWise SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																		SET @Balanceval=0;
																	BREAK;
																END
														
															ELSE IF(ISNULL(@Balanceval,0) > 0 and @tablerowscount=0)
																BEGIN
																	--SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #mainoutputtable_1_MonthWise)
																	INSERT INTO #mainoutputtable_1_MonthWise(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code, Consultant_code  , ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name,@flag_Type)
																	UPDATE #mainoutputtable_1_MonthWise SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
																	
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #mainoutputtable_1_MonthWise SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																END
															ELSE IF(ISNULL(@Balanceval,0) =0)
																BEGIN
																	SET @Balanceval=0
																	BREAK;
																END
																 
															SET @qty = @Balanceval
														END

												DROP TABLE #tempValExists
											END
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
									
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise)
													SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0)+1 from #mainoutputtable_1_MonthWise)

													INSERT INTO #mainoutputtable_1_MonthWise(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type,Broker_Code, Consultant_code  ,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
													VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId, @Ac_Types,@Broker_Code, @Consultant_code  , 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
												END
											
											SET @purchase_Op_Date=''
											SET @purchase_Op_Rate=''
											SET @purchase_Op_Qty=''
											SET @purchase_Op_Bill=''
										END
								END
							IF(@isIntradayCol=1)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											--SELECT * FROM #mainoutputtable_1_MonthWise --WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and ISNULL(Flag_Type,'')='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=1  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
											SET @COUNT = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold ='Sold' and  Flag_Type  = 'Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=1  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
											IF (@COUNT > 0)
												BEGIN
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY   Ac_Type,scriptcode,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* INTO #tempBought	
													FROM	#mainoutputtable_1_MonthWise 
													WHERE script_name=@scriptname AND holding_type=@holding_type  AND isintradaycol=1 
													AND (consultant_name = CASE WHEN  @Consultant_Name <> '' THEN @Consultant_Name ELSE consultant_name END)
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold =  'Sold'   AND  Flag_Type = 'Sold' AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
													ORDER BY NameId
													 
													DECLARE @Bought_COUNT INT = ( SELECT COUNT(*) FROM #tempBought )
													DECLARE @Temppurchase_Qty FLOAT 
													SET @purchase_Op_Qty = @qty
													DECLARE @Balance_val FLOAT
													WHILE(@Bought_COUNT  > 0)
														BEGIN 
															DECLARE @tempSale_ID INT = (SELECT TOP(1) id FROM #tempBought ORDER BY Dup_pkid)
															SET @str=@TransType
															SET @Temppurchase_Qty = (SELECT TOP(1) sold_qty  FROM #tempBought WHERE id  = @tempSale_ID )
															SET @soldDate = (SELECT TOP (1) sold_date  FROM #tempBought WHERE id  = @tempSale_ID )
															SET @soldRate = (SELECT TOP (1) sold_rate  FROM #tempBought WHERE id  = @tempSale_ID )
															SET @soldBillNo = (SELECT TOP (1) sold_bill_no  FROM #tempBought WHERE id  = @tempSale_ID )
															SET @Sold_Qty= ABS(@Temppurchase_Qty)
															SET @pkid = (SELECT TOP(1) pkid  FROM #tempBought WHERE id  = @tempSale_ID )
															 
															IF(@TransType='Bought')
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise  
																	SET	
																	purchase_date=@dates,
																	purchase_bill_no=@billno,
																	purchase_rate=@rate,
																	purchase_qty= CASE WHEN @Temppurchase_Qty > @purchase_Op_Qty THEN ABS(@purchase_Op_Qty) ELSE ABS(@Temppurchase_Qty) END,
																	Flag_Type='Bought'
																	WHERE  id = @tempSale_ID  and pkid=@pkid
																END
															IF(@Temppurchase_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise  SET sold_qty=ABS(@purchase_Op_Qty) WHERE Flag_Type_Sold='Sold' AND   id = @tempSale_ID   and pkid=@pkid
																END
															
															
															DELETE FROM #tempBought  WHERE id = @tempSale_ID 
															SET @Balance_val = Round((isnull(@purchase_Op_Qty,0) - (@Sold_Qty)),6)
															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempBought)
															
															SET @Bought_COUNT  = @Bought_COUNT  - 1
															SET @qty = @Balance_val

															IF(@Balance_val  < 0)
																BEGIN
																	--SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty = ABS(@Balance_val) 
																	SET @prioritysId  =(SELECT MAX(prioritys) FROM #MainOutputtable_1_MonthWise )--WHERE id=@tempSale_ID )
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	INSERT INTO #MainOutputtable_1_MonthWise(ID,Sr_No, Dup_pkid,DP_Code,ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Trans_No, Flag_Type,Flag_Type_sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name,Trans_Type)
																	VALUES(@tempSale_ID ,@Sr_No, @Dup_pkid,@DP_Code,@ScriptId,@Ac_Types ,@Broker_Code, @Consultant_code  ,@Trans_No,'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balance_val),@soldRate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	
																	UPDATE #MainOutputtable_1_MonthWise SET prioritys=@prioritysId+1  WHERE prioritys >= @prioritysId AND ID<>@tempSale_ID 
																
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1_MonthWise)) END)  
																	
																	IF(@idcount>0)
																		BEGIN
																		  UPDATE #mainoutputtable_1_MonthWise SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END

																	BREAK;
																END
															ELSE IF(@Balance_val  > 0 and @tablerowscount = 0)
																BEGIN
																	IF(@TransType='Bought')
																		BEGIN
																			SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																			SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																			SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																			SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																			SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																			SET @Dup_pkid = @Dup_pkid + 1

																			SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #mainoutputtable_1_MonthWise)
																			
																			INSERT INTO #mainoutputtable_1_MonthWise(ID,Sr_No, Dup_pkid,DP_Code,Trans_No, ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																			VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId,@Ac_Types ,@Broker_Code, @Consultant_code  , 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balance_val)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																			
																			UPDATE #mainoutputtable_1_MonthWise SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																			
																			SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
																			IF(@idcount>0)
																				BEGIN
																					UPDATE #mainoutputtable_1_MonthWise SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																				END
																		END
																ENd
															SET @purchase_Op_Qty= (@Balance_val)
														END

													
													DROP TABLE #tempBought
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise)
													SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0) + 1 from #mainoutputtable_1_MonthWise)

													INSERT INTO #mainoutputtable_1_MonthWise (id,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type,Broker_Code, Consultant_code  , prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name,Trans_Type) 
													VALUES ( @ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId,@Ac_Types,@Broker_Code, @Consultant_code  , @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name,@Flag_Type) 
												END
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
										 	SET @COUNT = (SELECT Count(*) FROM #mainoutputtable_1_MonthWise WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer','Other') AND ISNULL(sold_qty,0)=0  AND isnull(isintradaycol,0)=1 AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval_sold FLOAT
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  Ac_type,ScriptCode,case when opening_date <> NULL then opening_date else purchase_date end ) AS NameId,* 
													INTO #tempSold 
													FROM
													#mainoutputtable_1_MonthWise WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer','Other') 
													AND (consultant_name = CASE WHEN  @ConsultantCode <> '' THEN  @Consultant_Name ELSE consultant_name END) 
													AND ISNULL(sold_qty,0) = 0  AND isintradaycol = 1 
													ORDER BY NameId
													
													DECLARE @RSoldCOUNT INT = (SELECT COUNT(*) FROM #tempSold)
													DECLARE @TempQty_Sold FLOAT 
												    
													WHILE(@RSoldCOUNT > 0 )
														BEGIN 
															SET @Sold_Qty = @qty
															SET @tempID = (SELECT TOP(1) id FROM #tempSold)
															SET @str = (SELECT TOP(1) Flag_Type FROM #tempSold WHERE id = @tempID  ORDER BY Dup_pkid,NameId)
															SET @pkid = (SELECT TOP(1) pkid  FROM #tempSold WHERE id  = @tempID )
															
															IF(@str='Bought')
																BEGIN
																	SET @TempQty_Sold=(SELECT TOP(1) purchase_qty FROM #tempSold WHERE id  = @tempID)
																	SET @PurchaseDate=(SELECT TOP(1) purchase_date FROM #tempSold WHERE id  = @tempID)
																	SET @Purchaserate=(SELECT TOP(1) purchase_rate FROM #tempSold WHERE id  = @tempID)
																	SET @PurchaseBillNo=(SELECT TOP(1) purchase_bill_no FROM #tempSold WHERE id  = @tempID)
																END
															IF(@Sold_Qty > 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	UPDATE #mainoutputtable_1_MonthWise  
																		SET	
																			purchase_qty  = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempQty_Sold >= @Sold_Qty THEN @Sold_Qty ELSE @TempQty_Sold END
																							END,
																			sold_date=@dates,
																			sold_bill_no=@billno,
																			sold_rate=@rate,
																			sold_qty= CASE WHEN @TempQty_Sold > @Sold_Qty THEN @Sold_Qty ELSE @TempQty_Sold END,
																			Flag_Type_Sold='Sold',
																			prioritys = @prioritysId
																	WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND pkid = @pkid
																	SET @Balanceval_sold = Round((ABS(@Sold_Qty) - ABS(@TempQty_Sold)),6)
																END
															
															DELETE FROM #tempSold WHERE id = @tempID
															SET @RSoldCOUNT = @RSoldCOUNT - 1
															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempSold)
														
															IF(@Balanceval_sold < 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @PurchaseQty=ABS(@Sold_Qty) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	INSERT INTO #mainoutputtable_1_MonthWise(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code, Consultant_code  , ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval_sold)  ,@Purchaserate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	UPDATE #mainoutputtable_1_MonthWise SET prioritys=@prioritysId    WHERE prioritys >= @prioritysId AND ID <> @tempID
																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
																	IF(@idcount>0)
																		BEGIN
																			 UPDATE #mainoutputtable_1_MonthWise SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																	BREAK;
																END
															ELSE IF(ISNULL(@Balanceval_sold,0) > 0 AND @tablerowscount=0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #mainoutputtable_1_MonthWise)
																	INSERT INTO #mainoutputtable_1_MonthWise(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code, Consultant_code  , ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval_sold)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	UPDATE #mainoutputtable_1_MonthWise SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #mainoutputtable_1_MonthWise SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																END
													
															SET @qty = @Balanceval_sold
														END	
														 
													DROP TABLE #tempSold
												END
											
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise)
													SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0) +1 from #mainoutputtable_1_MonthWise)

													INSERT INTO #mainoutputtable_1_MonthWise(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type,Broker_Code, Consultant_code  ,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
													VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId, @Ac_Types,@Broker_Code, @Consultant_code  , 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
												END
											
											SET @purchase_Op_Date=''
											SET @purchase_Op_Rate=''
											SET @purchase_Op_Qty=''
											SET @purchase_Op_Bill=''
										END

								END
							FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Sr_No, @billno,@Flag_Type , @TransType, @scriptname,@ScriptId,@holding_type,@Ac_types,@broker_Code, @Consultant_code  , @DP_Code,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
						END 
				
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 
		--select * from #mainoutputtable_1_MonthWise

	    if(@IsBSEISIN=1)
		BEGIN
				INSERT INTO #mainoutputtable_1_MonthWise_Final_BSE_ISISNo 				
				SELECT ma.pkid,ma.Dup_pkid,ma.Trans_No,ma.Ac_type,ma.id,ma.sr_no, ma.prioritys,ma.Trans_Type, ma.Split_Type, ma.Flag_Type, ma.Flag_Type_Sold,ma.flag_script_name,
				ma.flag_holding_type,  
				ma.script_name + '[' +ms.BSE_Code + ']' + '[' +ms.ISIN_No+ ']',ma.holding_type,ma.opening_bill_no ,ma.opening_date ,ma.opening_qty,ma.opening_rate ,ma.opening_amount ,ma.purchase_date ,ma.purchase_bill_no ,
				ma.purchase_qty,ma.purchase_rate,ma.purchase_amount ,ma.sold_date ,ma.sold_bill_no ,ma.sold_qty,ma.sold_rate,ma.sold_amount ,ma.gain_loss ,ma.closing_qty,
				ma.closing_rate,ma.closing_value,ma.short_term ,ma.long_term ,ma.speculation ,ma.gain_speculation ,ma.loss_speculation ,ma.consultant_name ,ma.nse_rate ,ma.bse_rate, 
				ma.isintradaycol,ma.[type],ma.ScriptCode ,ma.Broker_Code,ma.Dp_code ,ma.Consultant_code 
				from #mainoutputtable_1_MonthWise ma 
				INNER JOIN Mst_Script Ms On  ma.ScriptCode=Ms.Script_Code
		END
		ELSE if(@IsBSEISIN=0)
			BEGIN
			    -- select 'text'
		 	   -- Select * into temp1234 from #mainoutputtable_1
				INSERT INTO #mainoutputtable_1_MonthWise_Final_BSE_ISISNo  
				SELECT ma.pkid,ma.Dup_pkid,ma.Trans_No,ma.Ac_type,ma.id,ma.sr_no, ma.prioritys,ma.Trans_Type, ma.Split_Type, ma.Flag_Type, ma.Flag_Type_Sold,ma.flag_script_name,
				ma.flag_holding_type, ma.script_name,ma.holding_type,ma.opening_bill_no ,ma.opening_date ,ma.opening_qty,ma.opening_rate ,ma.opening_amount ,ma.purchase_date,
				ma.purchase_bill_no ,ma.purchase_qty, ma.purchase_rate,ma.purchase_amount ,ma.sold_date ,ma.sold_bill_no ,ma.sold_qty,ma.sold_rate,ma.sold_amount ,ma.gain_loss,
				ma.closing_qty,ma.closing_rate ,ma.closing_value,ma.short_term ,ma.long_term ,ma.speculation ,ma.gain_speculation ,ma.loss_speculation ,
				ma.consultant_name ,ma.nse_rate ,ma.bse_rate, ma.isintradaycol,ma.[type],ma.ScriptCode ,ma.Broker_Code,ma.Dp_code ,ma.Consultant_code 
				from #mainoutputtable_1_MonthWise ma 
				--INNER JOIN Mst_Script Ms On  ma.script_name=Ms.Script_Name
		END

		IF(@IsIntraDay = 0 AND @short_Long_Term != 0  )
			BEGIN
				IF(@short_Long_Term = 1 AND @IsLTCG=1)  -- Long Term With LTCG
					BEGIN
						INSERT INTO #mainoutputtable_1_MonthWise_Final (OrderBy,sr_no, opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  , Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

						SELECT  ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN   CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
							 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId, sr_no,opening_bill_no,
						id,Ac_type,Broker_Code,Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,

						Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4)
						as gain_loss,

						closing_qty ,closing_rate ,ROUND(closing_value,4) ,
						0,
						Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4),
						0,0,0,consultant_name,nse_rate,bse_rate,1 sort ,isintradaycol,
						Trans_Type
						FROM #mainoutputtable_1_MonthWise_Final_BSE_ISISNo 
						WHERE ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
									(
										 
									       DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME,opening_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365 
									)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									(
										DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME, purchase_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365
									)
								)
							)
							order by NameId
					END
					
				ELSE If(@short_Long_Term = 2)  -- Short Term
					BEGIN
					--  select * from #mainoutputtable_1_MonthWise
						INSERT INTO #mainoutputtable_1_MonthWise_Final (OrderBy, sr_no,opening_bill_no, id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

							SELECT ROW_NUMBER ( ) OVER (ORDER BY   holding_type,ScriptCode,--Pkid,
						 case  WHEN  Dup_pkid is Null Then Pkid
							   WHEN  Dup_pkid is NOt Null then Dup_pkid 
							   else Dup_pkid end,prioritys,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
							 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,sr_no,
						opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4) as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						Round(ISNULL(
								CASE	WHEN isintradaycol = 0 and opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN isintradaycol = 0 and purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
										ELSE 0.0
								END 
						,0),4) ,
						0,0,0,0,consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,
						Trans_Type
						FROM #mainoutputtable_1_MonthWise_Final_BSE_ISISNo 
						WHERE  ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
										(		
											DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME,opening_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) <= 365 
										)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									  (		
											DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME, purchase_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) <= 365
									  )
								)
							)
					order by NameId				
					END				
				ELSE If(@short_Long_Term = 4 AND @IsLTCG=1)  -- Short Term + Long Term With LTCG
					BEGIN
						INSERT INTO #mainoutputtable_1_MonthWise_Final (OrderBy,sr_no, opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,sr_no,
						
						opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						
						closing_qty ,closing_rate ,closing_value ,
						(CASE  WHEN isintradaycol = 0 AND  ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
								    (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
							  THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						(CASE WHEN isintradaycol = 0 AND  ( (ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365) OR
								   (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365))  
							  THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,
						Trans_Type 
						FROM #mainoutputtable_1_MonthWise_Final_BSE_ISISNo 
						WHERE  ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						order by NameId
					END
				ELSE If(@short_Long_Term = 5 AND @IsLTCG=1)  -- Withou Speculation (Share Trading) With LTCG
					BEGIN
						INSERT INTO #mainoutputtable_1_MonthWise_Final (OrderBy,sr_no, opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,sr_no,
						
						opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						
						closing_qty ,closing_rate ,closing_value ,
						(CASE  WHEN isintradaycol = 0 AND  ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
								    (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
							  THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						(CASE WHEN isintradaycol = 0 AND  ( (ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365) OR
								   (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365))  
							  THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,
						Trans_Type 
						FROM #mainoutputtable_1_MonthWise_Final_BSE_ISISNo 
						WHERE ISNULL(isintradaycol,0)=0
						order by NameId
					END
                ELSE IF(@short_Long_Term = 1 ) -- Long Term
				    BEGIN
					    INSERT INTO #mainoutputtable_1_MonthWise_Final (OrderBy,sr_no, opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  , Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

						SELECT  ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN   CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
							 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId, sr_no,opening_bill_no,
						id,Ac_type,Broker_Code,Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,

						Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN sold_rate * sold_qty - opening_rate*opening_qty
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN sold_rate * sold_qty - purchase_rate*purchase_qty  
											ELSE 0.0	
										END,0) ,4)
						as gain_loss,

						closing_qty ,closing_rate ,ROUND(closing_value,4) ,
						0,
						Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN sold_rate * sold_qty - opening_rate*opening_qty
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN sold_rate * sold_qty - purchase_rate*purchase_qty  
											ELSE 0.0	
										END,0) ,4),
						0,0,0,consultant_name,nse_rate,bse_rate,1 sort ,isintradaycol,
						Trans_Type
						FROM #mainoutputtable_1_MonthWise 
						WHERE ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
									(
										 
									       DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME,opening_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365 
									)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									(
										DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME, purchase_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365
									)
								)
							)
							order by NameId
					END
                ELSE IF(@short_Long_Term = 4)  -- Short Term + Long Term 
				   BEGIN
				        INSERT INTO #mainoutputtable_1_MonthWise_Final (OrderBy,sr_no, opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,sr_no,
						
						opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN  sold_rate * sold_qty - opening_rate * opening_qty
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN sold_rate * sold_qty - purchase_rate * purchase_qty 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						
						closing_qty ,closing_rate ,closing_value ,
						(CASE  WHEN isintradaycol = 0 AND  ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
								    (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
							  THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN sold_rate * sold_qty - opening_rate * opening_qty
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN sold_rate * sold_qty - purchase_rate * purchase_qty
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						(CASE WHEN isintradaycol = 0 AND  ( (ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365) OR
								   (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365))  
							  THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN sold_rate * sold_qty - opening_rate * opening_qty
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN sold_rate * sold_qty - purchase_rate * purchase_qty
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,
						Trans_Type 
						FROM #mainoutputtable_1_MonthWise_Final_BSE_ISISNo 
						WHERE  ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						order by NameId
				   END
                ELSE IF(@short_Long_Term = 5) -- Withou Speculation (Share Trading)
				   BEGIN
				      INSERT INTO #mainoutputtable_1_MonthWise_Final (OrderBy,sr_no, opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,sr_no,
						
						opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN sold_rate * sold_qty - opening_rate * opening_qty
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN sold_rate * sold_qty - purchase_rate * purchase_qty 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						
						closing_qty ,closing_rate ,closing_value ,
						(CASE  WHEN isintradaycol = 0 AND  ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
								    (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
							  THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN sold_rate * sold_qty - purchase_rate * purchase_qty
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						(CASE WHEN isintradaycol = 0 AND  ( (ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365) OR
								   (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365))  
							  THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN sold_rate * sold_qty - opening_rate * opening_qty
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN sold_rate * sold_qty - purchase_rate * purchase_qty
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,
						Trans_Type 
						FROM #mainoutputtable_1_MonthWise_Final_BSE_ISISNo 
						WHERE ISNULL(isintradaycol,0)=0
						order by NameId
				   END
			END

		ELSE IF(@short_Long_Term = 3 AND @IsIntraDay = 1 )  -- Only Speculation
			BEGIN
				INSERT INTO #mainoutputtable_1_MonthWise_Final (OrderBy,sr_no, opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

				SELECT ROW_NUMBER ( ) OVER (ORDER BY  case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END,ScriptCode,holding_type desc)  AS NameId,sr_no,
				opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name,Holding_Type,opening_date,
				ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),purchase_date,ISNULL(purchase_bill_no,0),
				ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,sold_date ,sold_bill_no ,isnull(sold_qty,0) ,
				ISNULL(sold_rate,0),ISNULL(sold_amount,0) ,
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4) as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				0,0,
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4),
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,
				Trans_Type
				FROM #mainoutputtable_1_MonthWise_Final_BSE_ISISNo 
				WHERE  (ISNULL(closing_qty,0) = 0)  AND (ISNULL(isintradaycol,0)=1) AND (ISNULL(purchase_qty,0)! = 0 AND  ISNULL(sold_qty,0) ! = 0) 
				order by NameId
			END

		ELSE IF(@IsLTCG=1)
			BEGIN
				  --order by script_name				
				INSERT INTO #mainoutputtable_1_MonthWise_Final ( pkid,sr_no,Dup_pkid,OrderBy, opening_bill_no,id,Ac_type,Broker_Code,Dp_code, Consultant_code,Trans_No,ScriptCode, prioritys,script_name,Holding_Type,
				flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

				SELECT pkid,sr_no,Dup_pkid,
				ROW_NUMBER ( ) OVER (ORDER BY   holding_type,ScriptCode,--Pkid,
				 case  WHEN  Dup_pkid is Null Then Pkid
				       WHEN  Dup_pkid is NOt Null then Dup_pkid 
				       else Dup_pkid end,prioritys,
				case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
				opening_bill_no,id,ISNULL(Ac_type,''),ISNULL(Broker_Code,''), ISNULL(Dp_code,'')Dp_code ,ISNULL(Consultant_code ,'') ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type, 
				flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,sold_rate,sold_amount ,
				Round(ISNULL(
					CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term for openings
							THEN  sold_rate * sold_qty - opening_rate*opening_qty
							WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term for purchase
							THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
							ELSE --long term
								CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
											THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
										WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
											THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
										ELSE 0.0
								END
					END,0) ,4)
				as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN  isintradaycol = 0 AND (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365)   --short term for openings
						 THEN  sold_rate * sold_qty - opening_rate * opening_qty 
					 WHEN  isintradaycol = 0 AND (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365) --short term for purchase
						THEN  sold_rate * sold_qty - purchase_rate*purchase_qty 
				ELSE 0.0 END,   -- Short Tem
				CASE WHEN isintradaycol = 0 AND (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --long term for openings
							OR
						  isintradaycol = 0 AND	(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365) --long term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN 
									(Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,  -- Long Term
				CASE WHEN   isintradaycol = 1 AND  (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,
				Trans_Type
				FROM #mainoutputtable_1_MonthWise_Final_BSE_ISISNo 
				order by NameId
			END
        ELSE 
		    BEGIN
				INSERT INTO #mainoutputtable_1_MonthWise_Final ( pkid,sr_no,Dup_pkid,OrderBy, opening_bill_no,id,Ac_type,Broker_Code,Dp_code, Consultant_code,Trans_No,ScriptCode, prioritys,script_name,Holding_Type,
				flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

				SELECT pkid,sr_no,Dup_pkid,
				ROW_NUMBER ( ) OVER (ORDER BY   holding_type,ScriptCode,--Pkid,
				 case  WHEN  Dup_pkid is Null Then Pkid
				       WHEN  Dup_pkid is NOt Null then Dup_pkid 
				       else Dup_pkid end,prioritys,
				case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
				opening_bill_no,id,ISNULL(Ac_type,''),ISNULL(Broker_Code,''), ISNULL(Dp_code,'')Dp_code ,ISNULL(Consultant_code ,'') ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type, 
				flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,sold_rate,sold_amount ,
				Round(ISNULL(
					CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term for openings
							THEN  sold_rate * sold_qty - opening_rate*opening_qty
							WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term for purchase
							THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
							ELSE --long term
								CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
											THEN sold_rate * sold_qty - opening_rate*opening_qty
										WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
											THEN sold_rate * sold_qty - purchase_rate*purchase_qty 
										ELSE 0.0
								END
					END,0) ,4)
				as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN  isintradaycol = 0 AND (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365)   --short term for openings
						 THEN  sold_rate * sold_qty - opening_rate * opening_qty 
					 WHEN  isintradaycol = 0 AND (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365) --short term for purchase
						THEN  sold_rate * sold_qty - purchase_rate*purchase_qty 
				ELSE 0.0 END,   -- Short Tem
				CASE WHEN isintradaycol = 0 AND (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --long term for openings
							OR
						  isintradaycol = 0 AND	(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365) --long term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN sold_rate * sold_qty - opening_rate * opening_qty 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN sold_rate * sold_qty - purchase_rate*purchase_qty 
								ELSE 0.0
						END
				ELSE 0.0 END,  -- Long Term
				CASE WHEN   isintradaycol = 1 AND  (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,
				Trans_Type
				FROM #mainoutputtable_1_MonthWise_Final_BSE_ISISNo 
				order by NameId
			END
		
	--	Select * from #mainoutputtable_1_MonthWise_Final
		IF(@OUTPUT_Flag='Details')
			BEGIN
				IF(@Investmenttype != 2)
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN
							   -- select 'text'
							    UPDATE #mainoutputtable_1_MonthWise_Final SET prioritys=0
								DECLARE @ii INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_MonthWise_Final)
								UPDATE #mainoutputtable_1_MonthWise_Final
								SET prioritys  = @ii , @ii = @ii + 1

								SELECT opening_bill_no, id,prioritys,Ac_type,Broker_Code, Consultant_code  ,ScriptCode, script_name  'Script Name',Holding_Type,
								CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
								CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
								CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
								gain_loss 'Gain/Loss',ISNULL(gain,0) 'Gain',ISNULL(loss,0) 'Loss',ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
								ISNULL(short_term,0) short_term, ISNULL(long_term,0) long_term, ISNULL(speculation,0) speculation,
								CASE WHEN isintradaycol=1 AND ISNULL(gain,0)!=0 THEN ISNULL(gain ,0) ELSE '0' END gain_speculation,
								CASE WHEN isintradaycol=1 AND ISNULL(loss,0)!=0  THEN ISNULL(loss ,0) ELSE '0' END loss_speculation,
								consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),ISNULL(isintradaycol,0),1 sort,[type] 
								FROM #mainoutputtable_1_MonthWise_Final 
								WHERE (opening_qty != 0  OR purchase_qty != 0  or sold_qty != 0)  
								ORDER BY  consultant_name,prioritys,script_name,Holding_Type
							END
						ELSE
							BEGIN
							   --select 'Text'
								UPDATE #mainoutputtable_1_MonthWise_Final SET prioritys=0
								DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_MonthWise_Final)
								UPDATE #mainoutputtable_1_MonthWise_Final
								SET prioritys  = @i , @i = @i + 1
								
								SELECT id,Trans_no, Sr_No, Holding_Type as 'flag_HT', ISNULL(opening_bill_no,'') opening_bill_no , Dup_pkid,prioritys,ScriptCode,  ISNULL(Ac_type,'') Ac_type,   ISNULL(Broker_Code,'')Broker_Code,ISNULL(Consultant_code,'')Consultant_code  ,script_name 'Script Name',Holding_Type, 
								CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount', 
								CONVERT(DATE,purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ROUND(ISNULL(purchase_qty,0),4) 'Purchase Qty',ROUND(ISNULL(purchase_rate,0),4) 'Purchase Rate',ROUND(ISNULL(purchase_amount,0),4) 'Purchase Amount',
								CONVERT(DATE,sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ROUND(ISNULL(sold_qty,0),4) 'Sold Qty',ROUND(ISNULL(sold_rate,0),4) 'Sold Rate',ROUND(ISNULL(sold_amount,0),4) 'Sold Amount',
								ROUND(ISNULL(gain_loss,0),4) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS  'Loss',
								ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
								ISNULL(short_term,0)short_term, ISNULL(long_term,0)long_term, ISNULL(speculation,0)speculation,
								CASE WHEN ISNULL(speculation,0) > 0  THEN ISNULL(gain,0)  ELSE 0 END gain_speculation,
								CASE WHEN ISNULL(speculation,0) < 0  THEN ISNULL(loss,0)  ELSE 0 END loss_speculation,
								'' consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,ISNULL(isintradaycol,0)isintradaycol,1 sort ,[type]
								FROM #mainoutputtable_1_MonthWise_Final
								WHERE (opening_qty != 0  OR purchase_qty != 0  or sold_qty != 0)  
								order by prioritys,script_name,holding_type
							END
					END
				ELSE
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN
							    --print'text'
							    UPDATE #mainoutputtable_1_MonthWise_Final SET prioritys=0
								DECLARE @iii INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_MonthWise_Final)
								UPDATE #mainoutputtable_1_MonthWise_Final
								SET prioritys  = @iii , @iii = @iii + 1
								
								SELECT opening_bill_no, id,prioritys,ScriptCode,' '  Ac_type,    Broker_Code,   Consultant_code  ,script_name 'Script Name', 'Mutual Fund' as 'Holding_Type', 
								CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount', 
								CONVERT(DATE,purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ROUND(ISNULL(purchase_qty,0),4) 'Purchase Qty',ROUND(ISNULL(purchase_rate,0),4) 'Purchase Rate',ROUND(ISNULL(purchase_amount,0),4) 'Purchase Amount',
								CONVERT(DATE,sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ROUND(ISNULL(sold_qty,0),4) 'Sold Qty',ROUND(sold_rate,4) 'Sold Rate',ROUND(ISNULL(sold_amount,0),4) 'Sold Amount',
								ROUND(ISNULL(gain_loss,0),4) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS  'Loss',
								ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
								ISNULL(short_term,0) short_term,ISNULL(long_term,0) long_term,ISNULL(speculation,0) speculation,
								CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
								CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
								consultant_name,ISNULL(nse_rate,0) nse_rate,ISNULL(bse_rate,0) bse_rate,ISNULL(isintradaycol,0) isintradaycol,1 sort ,[type]
								FROM #mainoutputtable_1_MonthWise_Final
								WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)
								ORDER BY prioritys,consultant_name, Holding_Type,script_name,id
							END
						ELSE
							BEGIN	
							    UPDATE #mainoutputtable_1_MonthWise_Final SET prioritys=0
								DECLARE @iiv INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_MonthWise_Final)
								UPDATE #mainoutputtable_1_MonthWise_Final
								SET prioritys  = @iiv , @iiv = @iiv + 1
														   																	        
								SELECT opening_bill_no, id,prioritys,ScriptCode,' '  Ac_type,    Broker_Code,   Consultant_code  ,script_name 'Script Name', 'Mutual Fund' As 'Holding_Type', 
								CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount', 
								CONVERT(DATE,purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ROUND(ISNULL(purchase_qty,0),4) 'Purchase Qty',ROUND(ISNULL(purchase_rate,0),4) 'Purchase Rate',ROUND(ISNULL(purchase_amount,0),4) 'Purchase Amount',
								CONVERT(DATE,sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ROUND(ISNULL(sold_qty,0),4) 'Sold Qty',ROUND(ISNULL(sold_rate,0),4) 'Sold Rate',ROUND(ISNULL(sold_amount,0),4) 'Sold Amount',
								ROUND(ISNULL(gain_loss,0),4) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS  'Loss',
								ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate ,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
								ISNULL(short_term,0) short_term,
								ISNULL(long_term,0) long_term,
								ISNULL(speculation,0) speculation,
								CASE WHEN   ISNULL(speculation,0) > 0 THEN ISNULL(speculation,0)  ELSE '' END gain_speculation,
								CASE WHEN   ISNULL(speculation,0) < 0  THEN ISNULL(speculation,0)  ELSE '' END loss_speculation,
								'' consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,ISNULL(isintradaycol,0)isintradaycol,1 sort ,[type]
								FROM #mainoutputtable_1_MonthWise_Final
								WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)
								ORDER BY prioritys,script_name,id
							END
					END
			END

		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
				SELECT  0 id ,  0 prioritys,'' opening_bill_no,ScriptCode,  Ac_type, script_name 'Script Name',   Holding_Type,
				NULL 'Opening Date', SUM(ISNULL(opening_qty,0)) 'Opening Qty',  
				CASE WHEN SUM(opening_qty) != 0
					 THEN SUM(opening_amount)/ NULLIF(SUM(opening_qty),0)  
					 ELSE 0
				END  'Opening Rate',
				 SUM(ISNULL(opening_amount,0)) 'Opening Amount',
				NULL 'Purchase Date','' 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty',  ISNULL((ISNULL(SUM(purchase_amount),0)  / SUM(NULLIF(purchase_qty,0))),0)   'Purchase Rate', SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
				NULL 'Sold Date', '' 'Sold BillNo', SUM(ISNULL(sold_qty,0)) 'Sold Qty', ISNULL((SUM(ISNULL(sold_amount,0)) / NULLIF (SUM(ISNULL(sold_qty,0)),0)),0) 'Sold Rate', SUM(ISNULL(sold_amount,0)) 'Sold Amount', 
				SUM(ISNULL(gain_loss,0)) 'Gain/Loss', SUM(ISNULL(gain,0))  'Gain', SUM(ISNULL(loss,0))  'Loss',
				
				SUM(ISNULL(closing_qty,0))  'Closing Qty',
				CASE WHEN SUM(closing_qty) != 0
					 THEN (SUM(closing_value) / SUM(NULLIF(closing_qty,0))) 
					 ELSE 0
				END  'Closing Rate',

				SUM(ISNULL(closing_value,0))  'Closing Value', SUM(ISNULL(short_term,0))  short_term, SUM(ISNULL(long_term,0))  long_term,
				SUM(ISNULL(speculation,0)) speculation, SUM(ISNULL(gain_speculation,0)) gain_speculation, SUM(ISNULL(loss_speculation,0)) loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort  
				FROM
					(
						SELECT MAX(id+0)id ,MAX (prioritys+0) prioritys,'' opening_bill_no, ScriptCode,Ac_type,  script_name  ,  Holding_Type,
						NULL 'Opening Date',SUM(ISNULL(opening_qty,0)) 'Opening_Qty',sum(ISNULL(opening_rate,0)) opening_rate ,SUM(ISNULL(opening_amount,0)) 'Opening_Amount',
						NULL 'Purchase Date',purchase_bill_no,SUM(ISNULL(purchase_qty,0)) 'Purchase_Qty', (SUM(ISNULL(purchase_amount,0)) / SUM(NULLIF(ISNULL(purchase_qty,0),0))) purchase_rate,SUM(ISNULL(purchase_amount,0)) 'Purchase_Amount',
						NULL 'Sold Date',sold_bill_no ,SUM(ISNULL(sold_qty,0)) 'Sold_Qty', (SUM(ISNULL(sold_amount,0)) / SUM(NULLIF(ISNULL(sold_qty,0),0))) sold_rate  , SUM(ISNULL(sold_amount,0)) 'Sold_Amount',SUM(ISNULL(gain_loss,0)) 'Gain_Loss',SUM(ISNULL(gain,0)) 'Gain',SUM(ISNULL(loss,0)) 'Loss',
						SUM(ISNULL(closing_qty,0)) 'Closing_Qty', (SUM(ISNULL(closing_value,0)) / SUM(NULLIF(closing_qty,0))) 'Closing_Rate',SUM(ISNULL(closing_value,0)) 'Closing_Value',
						SUM(ISNULL(short_term,0)) AS short_term,SUM(ISNULL(long_term,0)) AS long_term,SUM(ISNULL(speculation,0)) AS speculation,
						SUM(ISNULL(gain_speculation,0)) gain_speculation,SUM(ISNULL(loss_speculation,0)) loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort 
						FROM #mainoutputtable_1_MonthWise_Final 
						GROUP BY ScriptCode,script_name,Holding_Type,Ac_type,purchase_bill_no,sold_bill_no,opening_date,purchase_date ,sold_date,isintradaycol
					)a
				GROUP BY  ScriptCode,script_name,Holding_Type,Ac_type,[Opening Date],[Purchase Date]  
				ORDER BY  Holding_Type,script_name,id
			END

		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN
				SELECT  prioritys ,Trans_No,id ,ISNULL(Ac_type,'')Ac_type,ISNULL(Broker_Code,'')Broker_Code,  ISNULL(Consultant_code,'') Consultant_code ,
				ISNULL(ScriptCode,'')ScriptCode,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,CONVERT(DATE, opening_date,103),
				ISNULL(opening_qty ,0),ISNULL(opening_Rate,0),ISNULL(opening_amount,0),CONVERT(DATE, purchase_date,103),purchase_bill_no,
				ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,CONVERT(DATE,sold_date,103) ,sold_bill_no ,ISNULL(sold_qty ,0),
				ISNULL(sold_rate,0),ISNULL(sold_amount ,0),ISNULL(gain_loss ,0),ISNULL(gain ,0),ISNULL(loss,0),ISNULL(closing_qty ,0),ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
				ISNULL(short_term,0),ISNULL(long_term,0),ISNULL(speculation,0),ISNULL(gain_speculation,0),ISNULL(loss_speculation,0),
				consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0 ),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol
				FROM #mainoutputtable_1_MonthWise_Final
				ORDER BY  Holding_Type,script_name,id
			END

		ELSE IF (@OUTPUT_Flag = 'Summary')
			 BEGIN
			 INSERT INTO #mainoutputtable_1_Final_Summary
			 SELECT prioritys as 'prioritys',Trans_No,id ,ISNULL(Ac_type,'')Ac_type,ISNULL(Broker_Code,'')Broker_Code,  ISNULL(Consultant_code,'') Consultant_code ,
				ISNULL(ScriptCode,'')ScriptCode,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,CONVERT(DATE, opening_date,103),
				ISNULL(opening_qty ,0),ISNULL(opening_Rate,0),ISNULL(opening_amount,0),CONVERT(DATE, purchase_date,103),purchase_bill_no,
				ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,CONVERT(DATE,sold_date,103) ,sold_bill_no ,ISNULL(sold_qty ,0),
				ISNULL(sold_rate,0),ISNULL(sold_amount ,0),ISNULL(gain_loss ,0),ISNULL(gain ,0),ISNULL(loss,0),ISNULL(closing_qty ,0),ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
				ISNULL(short_term,0),ISNULL(long_term,0),ISNULL(speculation,0),ISNULL(gain_speculation,0),ISNULL(loss_speculation,0),
				consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0 ),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol
				
				FROM #mainoutputtable_1_MonthWise_Final
				ORDER BY  Holding_Type,script_name,id

			 SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
					T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
					T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
					T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
					T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
					T1.consultant_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,
					T1.Ac_type,T1.Broker_Code,
					T1.Consultant_Code,T1.ScriptCode,
					ISNULL(Dr.BSE_Rate,0)  AS 'bse_rate', 
					ISNULL(Dr.NSE_Rate,0) AS  'nse_rate' 
			INTO #allSummarydata 
			FROM #mainoutputtable_1_Final_Summary  T1 /**/
			LEFT JOIN BrokerBill T2 ON T1.Trans_No=T2.Trans_no 
			LEFT JOIN DailyRate DR ON DR.Script_Code = T1.ScriptCode  and Dr.Trans_Dt = @Todate /**/

			TRUNCATE TABLE #mainoutputtable_1_Final_Summary

			INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
			opening_date,opening_qty,opening_rate,opening_amount,
			purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
			sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
			closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
			consultant_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,
			Ac_type,Broker_Code,--dematecode,
			Consultant_Code,ScriptCode) 

			SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
			convert(VARCHAR(10), opening_date,103),opening_qty,opening_rate,opening_amount,
			convert(VARCHAR(10),purchase_date,103),purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
			convert(VARCHAR(10),sold_date,103),sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
			closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
			consultant_name,
			Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
			sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt,
			Ac_type,Broker_Code,
			Consultant_Code,ScriptCode    
			FROM #allSummarydata  
			GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
			Ac_type,Broker_Code,
			Consultant_Code,ScriptCode,
			opening_date,opening_qty,opening_rate,opening_amount,
			purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
			sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
			closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
			consultant_name,sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 


			IF(@RecordOnlyhavingClosingbalanceZero = 0)
				BEGIN
				IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN
								SELECT  MAX(id+1)id,holding_type,script_name AS 'Script Name', 
								ROUND(SUM(closing_value),2) AS 'Closing Value',
								SUM(closing_qty) AS 'Closing Qty', 
								ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', 
								SUM(gain_loss) AS  'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END AS 'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',	nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS 'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT   holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', 
								ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								sum(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								sum(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)> 0 THEN (SUM(ISNULL(closing_value,0)) +  abs(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0) > 0  THEN (SUM(ISNULL(closing_value,0)) - abs( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  abs(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) - abs( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,
										Ac_type,Broker_Code,
										ScriptCode,Consultant_Code,	CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END,
										--gain_loss,
										bse_rate,nse_rate,
									bse_rate,nse_rate,consultant_name
										--HAVING SUM(closing_qty) != 0
								HAVING SUM(closing_qty) != 0
							END
					END
				ELSE IF(@WithActualAvgRate = 1 OR @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  MAX(id+1)id,holding_type,script_name AS 'Script Name', 
								ROUND(SUM(closing_value),2) AS 'Closing Value',
								SUM(closing_qty) AS 'Closing Qty', 
								ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', 
								SUM(gain_loss) AS  'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',bse_rate  AS  'BSERATE',bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END AS 'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',	nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS 'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								IF(@WithActualAvgRate = 0 AND @DateWiseClosinStock=1)
									BEGIN
										SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', SUM(gain_loss) AS  'Gain/Loss',
										Ac_type,Broker_Code,
										ScriptCode,Consultant_Code,
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END  AS  'Closing Date',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
												ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
												0 END 
												END AS 'Avg. Rate',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
												ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
												0 END 
												END AS 'Value After Profit/Loss',
										SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY holding_type,script_name,
										Ac_type,Broker_Code,
										ScriptCode,Consultant_Code,
										bse_rate,nse_rate,
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END,bse_rate,nse_rate,consultant_name
										HAVING SUM(closing_qty) != 0
									END
								ELSE
									BEGIN
										
										SELECT   holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) + ABS( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0)>0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
											0 END 
											END AS 'Avg. Rate',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) - ABS( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) + ABS( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
											0 END 
											END AS 'Value After Profit/Loss',
										0 Other_amt, '' consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY holding_type,script_name,bse_rate,nse_rate 
								
										HAVING SUM(closing_qty) != 0
									END
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT   max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(gain_loss) AS  'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name 
							END
						ELSE
							BEGIN
								SELECT   holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty',
								 ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					END
			END
			ELSE IF(@RecordOnlyhavingClosingbalanceZero = 1)
				BEGIN
				IF (@WithActualAvgRate = 1 OR @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN 
								SELECT  MAX(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate', 0 'Closing Value',
								Ac_type,''Broker_Code,
								ScriptCode,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss','' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,Ac_type,script_name,ScriptCode,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
							END
					END

				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE',SUM(gain_loss) AS  'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name

							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE',SUM(gain_loss) AS  'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt,'' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) = 0
							END
					END
			END
			DROP TABLE #allSummarydata
		END
		DROP TABLE #mainoutputtable_1_MonthWise 
		DROP TABLE #alldata 
		DROP TABLE #Openings
	
END  























































GO
/****** Object:  StoredProcedure [dbo].[proc_MonthWise_Stockholdingposition_Equity_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_MonthWise_Stockholdingposition_Equity_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_MonthWise_Stockholdingposition_Equity_Summary] AS' 
END
GO
--Execute  proc_Stockholdingposition_Equity_Summary    0,0,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0',0,1,0
--Execute  proc_Stockholdingposition_Equity_Summary    0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0',1,1,1
ALTER PROCEDURE [dbo].[proc_MonthWise_Stockholdingposition_Equity_Summary]  --''
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,
@RecordOnlyhavingClosingbalanceZero as bit,@WithActualAvgRate as bit, @DateWiseClosinStock as bit)
AS
BEGIN
SET NOCOUNT ON;
		CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
			prioritys INT,
			Trans_No VARCHAR(50),
			id INT,
			Ac_type VARCHAR(50),
			Broker_Code VARCHAR(20),
			Consultant_Code varchar(20), 
			ScriptCode  VARCHAR(50), 
			script_name  VARCHAR(500),
			holding_type VARCHAR(200),
			flag_script_name  VARCHAR(500),
			flag_holding_type VARCHAR(200),
			opening_date VARCHAR(10),opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
			purchase_date VARCHAR(10),purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
			sold_date VARCHAR(10),sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
			gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
			closing_qty FLOAT DEFAULT 0, 
			closing_rate FLOAT DEFAULT 0,
			closing_value FLOAT DEFAULT 0,
			short_term FLOAT DEFAULT 0,
			long_term FLOAT DEFAULT 0, 
			speculation FLOAT DEFAULT 0, 
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			consultant_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			Other_amt FLOAT DEFAULT 0,
			ServTax_Amt FLOAT DEFAULT 0,
			Stt_amt FLOAT DEFAULT 0,
			sort   VARCHAR(5),
			isintradaycol  INT 
        ) 


		IF(@ConsultantCode = '0')
			BEGIN
						
					SELECT DISTINCT p.member_code,p.year_code,
						STUFF((	SELECT distinct ',' + p1.Consultant_Code
								FROM Mst_Consultant p1
								--WHERE p.member_code = p1.member_code AND p.year_code = p1.year_code
								FOR XML PATH(''), TYPE
								).value('.', 'NVARCHAR(MAX)')
						,1,1,'') ConsultantCode
					into #temoConsultant
					FROM Mst_Consultant p

					SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant)-- WHERE member_code = @memcode AND year_code = @yearcode)
					DROP table #temoConsultant
	
			END

		INSERT INTO #mainoutputtable_1_Final_Summary
		EXEC proc_MonthWise_Stockholdingposition_Equity   @status,@Investmenttype,@Ac_Type,@memcode,@yearcode,@Fromdate,@Todate,@ScriptCode,@ConsultantCode,@BSE_NSE_Code,@Is_BFCF,@IsIntraDay,@short_Long_Term,'ALLData'
	 

		SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
		T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
		T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
		T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
		T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
		T1.consultant_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,
		T1.Ac_type,T1.Broker_Code,
		T1.Consultant_Code,T1.ScriptCode,
		ISNULL(Dr.BSE_Rate,0)  AS 'bse_rate', /**/
		ISNULL(Dr.NSE_Rate,0) AS  'nse_rate' /**/
		INTO #alldata 
		FROM #mainoutputtable_1_Final_Summary  T1 /**/
		LEFT JOIN BrokerBill T2 ON T1.Trans_No=T2.Trans_no /**/
		LEFT JOIN DailyRate DR ON DR.Script_Code = T1.ScriptCode  and Dr.Trans_Dt = @Todate /**/
		
		TRUNCATE TABLE #mainoutputtable_1_Final_Summary
		
		INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,
		Ac_type,Broker_Code,--dematecode,
		Consultant_Code,ScriptCode) 

		SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		convert(VARCHAR(10), opening_date,103),opening_qty,opening_rate,opening_amount,
		convert(VARCHAR(10),purchase_date,103),purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		convert(VARCHAR(10),sold_date,103),sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt,
		Ac_type,Broker_Code,
		Consultant_Code,ScriptCode    
		FROM #alldata  
		GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		Ac_type,Broker_Code,
		Consultant_Code,ScriptCode,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,nse_rate,bse_rate,sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 

		
		IF(@RecordOnlyhavingClosingbalanceZero = 0)
			BEGIN
				IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN
								SELECT  MAX(id+1)id,holding_type,script_name AS 'Script Name', 
								ROUND(SUM(closing_value),2) AS 'Closing Value',
								SUM(closing_qty) AS 'Closing Qty', 
								ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', 
								SUM(gain_loss) AS  'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',bse_rate  AS  'BSERATE',bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END AS 'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',	nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS 'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT   holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', 
								ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								sum(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								sum(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)> 0 THEN (SUM(ISNULL(closing_value,0)) +  abs(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0) > 0  THEN (SUM(ISNULL(closing_value,0)) - abs( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  abs(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) - abs( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,
										Ac_type,Broker_Code,
										ScriptCode,Consultant_Code,	CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END,
										--gain_loss,
										bse_rate,nse_rate,
									bse_rate,nse_rate,consultant_name
										--HAVING SUM(closing_qty) != 0
								HAVING SUM(closing_qty) != 0
							END
					END
				ELSE IF(@WithActualAvgRate = 1 OR @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  MAX(id+1)id,holding_type,script_name AS 'Script Name', 
								ROUND(SUM(closing_value),2) AS 'Closing Value',
								SUM(closing_qty) AS 'Closing Qty', 
								ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', 
								SUM(gain_loss) AS  'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',bse_rate  AS  'BSERATE',bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END AS 'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',	nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS 'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								IF(@WithActualAvgRate = 0 AND @DateWiseClosinStock=1)
									BEGIN
										SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', SUM(gain_loss) AS  'Gain/Loss',
										Ac_type,Broker_Code,
										ScriptCode,Consultant_Code,
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END  AS  'Closing Date',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
												ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
												0 END 
												END AS 'Avg. Rate',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
												ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
												0 END 
												END AS 'Value After Profit/Loss',
										SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY holding_type,script_name,
										Ac_type,Broker_Code,
										ScriptCode,Consultant_Code,
										bse_rate,nse_rate,
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END,bse_rate,nse_rate,consultant_name
										HAVING SUM(closing_qty) != 0
									END
								ELSE
									BEGIN
										
										SELECT   holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) + ABS( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0)>0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
											0 END 
											END AS 'Avg. Rate',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) - ABS( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) + ABS( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
											0 END 
											END AS 'Value After Profit/Loss',
										0 Other_amt, '' consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY holding_type,script_name,bse_rate,nse_rate 
								
										HAVING SUM(closing_qty) != 0
									END
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT   max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(gain_loss) AS  'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name 
							END
						ELSE
							BEGIN
								SELECT   holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty',
								 ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					END
			END
		ELSE IF(@RecordOnlyhavingClosingbalanceZero = 1)
			BEGIN
				IF (@WithActualAvgRate = 1 OR @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN 
								SELECT  MAX(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate', 0 'Closing Value',
								Ac_type,''Broker_Code,
								ScriptCode,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss','' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,Ac_type,script_name,ScriptCode,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
							END
					END

				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE',SUM(gain_loss) AS  'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name

							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE',SUM(gain_loss) AS  'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt,'' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) = 0
							END
					END
			END
			DROP TABLE #alldata

END































GO
/****** Object:  StoredProcedure [dbo].[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency] AS' 
END
GO





--[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency] 0,5,'0','30001','1120182019','2018-04-01 12:00:00:00','2019-03-31 03:50:37:50','','','','', '0' ,'0','Summary',0,0,0
--[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency] 0,1,'0','30001','1120182019','2018-04-01 12:00:00:00','2019-03-31 03:50:37:50','','','','', '0' ,'0','Details'
--[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency] 0,5,'0','30001','1120182019','2018-04-01','2018-011-20','','','','','0' ,'0','Summary',0,0,0
ALTER PROCEDURE [dbo].[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency] --0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','ScriptWiseTotal'
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX),
@IsWithTax bit = 0,
@RecordOnlyhavingClosingbalanceZero AS BIT = 0,@WithActualAvgRate AS BIT = 0, @DateWiseClosinStock AS BIT =0,
@Script_Name varchar(max) = '')
AS 
  BEGIN  
  SET NOCOUNT ON;
		DECLARE @StartYearDate VARCHAR(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101)
		CREATE TABLE #MainOutputtable_1_MonthWise
          ( 
			pkid INT identity(1,1),
			Dup_pkid INT,
			Trans_No VARCHAR(20),
			id INT,
			sr_no  INT,
			prioritys INT,
			Trans_Type  VARCHAR(50),
		    Split_Type VARCHAR(50),
			Flag_Type VARCHAR(10),
			Flag_Type_Sold VARCHAR(10),
			flag_script_name  VARCHAR(500),
			flag_holding_type VARCHAR(200), 
			script_name  VARCHAR(500),
			holding_type VARCHAR(200), 
			opening_bill_no VARCHAR(10),		    
			opening_date DATETIME,
			opening_qty  FLOAT DEFAULT 0,
			opening_rate  FLOAT DEFAULT 0,
			opening_amount AS( [opening_qty] * [opening_rate] ), 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount AS( purchase_qty * purchase_rate ), 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount AS ( sold_qty * sold_rate ), 
			gain_loss float,
			closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 AND (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 
			closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
			closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
			short_term FLOAT DEFAULT 0,
			long_term  FLOAT DEFAULT 0,
			speculation  FLOAT DEFAULT 0,
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			consultant_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			dayscount FLOAT DEFAULT 0,
			isintradaycol INT,
			[type] VARCHAR(20) ,
			ScriptCode VARCHAR(50) ,
			 Exp_Rate float DEFAULT 0,
			Strike_Price float DEFAULT 0,
			OptionType VARCHAR(100),
			MonthYear VARCHAR(100),
			Last_Date VARCHAR(100),
			Broker_Code VARCHAR(100),dp_code VARCHAR(100),Consultant_code VARCHAR(500)
        )  

		CREATE TABLE #MainOutputtable_1_MonthWise_Final
        ( 
			pkid int,
			Dup_pkid int, 
			OrderBy varchar(100),
			Trans_No VARCHAR(20),
			id INT,
			sr_no  INT,
			prioritys INT   ,
			Split_Type VARCHAR(50),
			Flag_Type VARCHAR(10),
			Flag_Type_Sold VARCHAR(10),
			flag_script_name  VARCHAR(500),
			flag_holding_type VARCHAR(200), 
			script_name  VARCHAR(500),
			holding_type VARCHAR(200), 
		    opening_bill_no VARCHAR(10),		    
			opening_date DATETIME,
			opening_qty  FLOAT DEFAULT 0,
			opening_rate  FLOAT DEFAULT 0,
			opening_amount FLOAT DEFAULT 0, 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount FLOAT DEFAULT 0 , 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount FLOAT DEFAULT 0, 
			gain_loss FLOAT DEFAULT 0,
			gain AS CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
			loss AS CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
			closing_qty FLOAT DEFAULT 0, 
			closing_rate FLOAT DEFAULT 0,
			closing_value FLOAT DEFAULT 0,
			short_term FLOAT DEFAULT 0,
			long_term FLOAT DEFAULT 0, 
			speculation FLOAT DEFAULT 0, 
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			consultant_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			dayscount FLOAT DEFAULT 0,
			isintradaycol INT,
			[type] VARCHAR(20),
			sort VARCHAR(5),
			ScriptCode VARCHAR(50) ,
			Strike_Price float DEFAULT 0,
			Exp_Rate float DEFAULT 0,
			OptionType VARCHAR(100),
			MonthYear VARCHAR(100),
			Last_Date VARCHAR(100),
			Broker_Code VARCHAR(100),
			dp_code VARCHAR(100),Consultant_code VARCHAR(500)
        ) 

		CREATE TABLE #Openings
        (
		   id INT, 
		   sr_no int,
		   Trans_No VARCHAR(20),
		   script_name  VARCHAR(500),
		   script_code VARCHAR(50),
		   holding_type VARCHAR(200),
		   bill_no VARCHAR(100),	
		   trans_dt Datetime,
		   StrikePrice float,
		   OptionType VARCHAR(100),
		   MonthYear VARCHAR(100),
		   Last_dt Datetime,
		   Exp_Rate float,
		   Broker_Code  VARCHAR(100),
		   DP_Code  VARCHAR(50),
		   qty  FLOAT DEFAULT 0,
		   rate  FLOAT DEFAULT 0,
		   amount FLOAT DEFAULT 0, 
		   isintraday bit DEFAULT 0, 
		   consultant_name VARCHAR(500),
		   Consultant_Code  VARCHAR(20),
		   BillType varchar(20)
	   )  

	   	CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
			prioritys INT,
			Trans_No VARCHAR(50),
			id INT,
			ScriptCode VARCHAR(50), 
			Broker_Code VARCHAR(100),
			dematcode VARCHAR(100),
			Consultant_code  VARCHAR(100),
			script_name  VARCHAR(500),
			holding_type VARCHAR(200),
			flag_script_name  VARCHAR(500),
			flag_holding_type VARCHAR(200),
			opening_date DATETIME,opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
			purchase_date DATETIME,purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
			sold_date DATETIME,sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
			gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
			closing_qty FLOAT DEFAULT 0, 
			closing_rate FLOAT DEFAULT 0,
			closing_value FLOAT DEFAULT 0,
			short_term FLOAT DEFAULT 0,
			long_term FLOAT DEFAULT 0, 
			speculation FLOAT DEFAULT 0, 
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			consultant_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			Other_amt FLOAT DEFAULT 0,
			ServTax_Amt FLOAT DEFAULT 0,
			Stt_amt FLOAT DEFAULT 0,
			sort   VARCHAR(5),
			isintradaycol  INT,
			Last_Date dateTime,
			Strike_Price float,
			OptionType varchar(max)
        ) 

		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty INT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT  
		DECLARE @tablerowscount INT,@sr_no  INT 
      IF(@status = 0)
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(max),
				@openingDate VARCHAR(50),@openingRate FLOAT,@openingQty INT,@openingAmount FLOAT,
				@purchaseDate VARCHAR(50),@PurchaseBillNo  VARCHAR(50),@purchaseRate FLOAT,@purchaseQty INT,@purchaseAmount FLOAT,
				@soldDate VARCHAR(50),@soldBillNo  VARCHAR(50),@soldRate FLOAT,@soldQty INT,@soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50),@Consultant_Name  VARCHAR(MAX), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(10),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,
				@PurchaseIntraFlag VARCHAR(100),@SaleIntraFlag VARCHAR(10), @Dup_pkid int, @Pkid varchar(50),@idcount int,@BillType varchar(20)  
				 
				DECLARE @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@ScriptId VARCHAR(MAX),
				@Strike_Price FLOAT,@OptionType VARCHAR(50),@Last_Date VARCHAR(50),@MonthYear VARCHAR(50),
				@Exp_Rate VARCHAR(50),@Broker_Code VARCHAR(50),@dp_code VARCHAR(50),@Consultant_code  VARCHAR(MAX)

				CREATE TABLE #SCriptName_MonthWise
				(
					ScriptName varchar(MAX)
				)
				
				IF(@Script_Name != '')
					INSERT INTO #SCriptName_MonthWise SELECT value FROM Fn_split(@Script_Name, ',') 
				ELSE 
					BEGIN
						INSERT INTO #SCriptName_MonthWise 
						Select distinct (Ms.script_name 
								+ '/' + CONVERT(VARCHAR(10),t.Last_Date,103) 
								+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
								+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' END) 
						from brokerbill_Trans t
						Left Join mst_Script ms on ms.script_Code = t.script_Code 
					END
			
				CREATE TABLE #ConsultantCodes_MonthWise
				(
					ConsultantCodes varchar(MAX)
				)

				IF(@ConsultantCode = '0')	
					BEGIN
						SELECT DISTINCT p.member_code,p.year_code,
							STUFF((	SELECT distinct ',' + p1.Consultant_Code
									FROM Mst_Consultant p1
									FOR XML PATH(''), TYPE
									).value('.', 'NVARCHAR(MAX)')
							,1,1,'') ConsultantCode
						into #temoConsultant
						FROM Mst_Consultant p

						SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant) --WHERE member_code = @memcode AND year_code = @yearcode)
						DROP table #temoConsultant
					END
				 
				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes_MonthWise SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes_MonthWise select Consultant_Code from Mst_Consultant
				
				SELECT	ROW_NUMBER ( ) OVER (ORDER BY t.script_code,t.trans_dt ) AS NameId,t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,t.TransType, '' Ac_Type,t.Script_Code, t.Qty,
				Case When @IsWithTax = 0 Then t.Rate Else t.Exp_Rate END As 'Rate',--t.Rate,`
				t.Member_code,t.YearCode,t.Consultant_code,t.isFNOBill,t.Strike_Price,t.OptionType,MonthYear,Last_Date,t.isIntraDay,t.Exp_Rate,t.FrmNm,t.ID,Ms.bse_code,Ms.nse_code,			
				Ms.script_name 
				+ '/' + CONVERT(VARCHAR(10),t.Last_Date,103) 
				+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
				+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' END script_name,
					'Empty' AS 'Holding Type',
					CASE WHEN (((t.Bill_no = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101)) AND t.TransType='Bought') THEN 'Opening'
						WHEN t.TransType='Bought' AND  t.Bill_no != 'Opening'  THEN 'Bought' 
						WHEN TransType='Sold' THEN 'Sold' 
						END AS 'Flag_Type',
						cm.Consultant_Name,ISNULL(BB.Broker_Code,'') Broker_Code,ISNULL(BBD.dp_code,'') dp_code   ,t.isstock
						INTO #alldata 
				FROM brokerbill_trans t WITH(NOLOCK)
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN  Mst_Consultant cm ON t.Consultant_code = cm.Consultant_code  
				LEFT JOIN BrokerBill_DmatInfo BBD ON BBD.Trans_No=t.Trans_No 
				LEFT JOIN BrokerBill BB ON BB.Trans_No=t.Trans_No 
				WHERE  t.isfnobill = @Investmenttype
				AND  t.trans_dt >=  @Fromdate AND t.trans_dt <= @Todate  
			    AND  t.member_code = @memcode AND t.yearcode = @yearcode  
				AND  (Ms.script_name 
				+ '/' + CONVERT(VARCHAR(10),t.Last_Date,103) 
				+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
				+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' END)
				IN (SELECT * FROM #SCriptName_MonthWise)
				AND	 t.Consultant_code IN (SELECT * FROM #ConsultantCodes_MonthWise)
				AND  isnull(t.isIntraDay,0) =(CASE WHEN @IsIntraDay=0 THEN  isnull(isIntraDay,0) ELSE ISNULL(@IsIntraDay,0) END)
				AND  t.isstock=(select case when @Is_BFCF = 1 then  '' else  t.isstock end)		
				GROUP BY t.Script_Code,script_name,t.Consultant_code,cm.Consultant_Name ,BB.Broker_Code,BBD.dp_code,t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,
						 TransType,MonthYear,Last_Date,t.Qty,Rate,t.Amount,t.Member_Code,t.YearCode,
						 t.EntrySource,t.Ref_TransNo,Ref_SrNo,t.MergedEntry,t.isFNOBill,Strike_Price,OptionType,isIntraDay,Exp_Rate,FrmNm,ID,bse_code,nse_code ,t.isstock
						
				--Select * from #SCriptName_MonthWise
				--Select * from #alldata	

				DECLARE @isIntradayCol INT 
				DECLARE  @COUNT INT = 0	 

				DECLARE @ToDATEfORcLOSIng VARCHAR(15) =  CONVERT(Varchar,CONVERT(DATETime,@fROMdATE,101) - 1,101)
				
				INSERT INTO #Openings
				EXECUTE proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency 0,@Investmenttype,@Ac_Type,@memcode,@Yearcode,@FromDate,@ToDATEfORcLOSIng,@ScriptCode,@ConsultantCode,@BSE_NSE_Code,@Is_BFCF,'0','','ClosingStocks',@IsWithTax,@Script_Name

				--Select * from #Openings
		
				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT	*
				FROM #Openings 
				WHERE BillType = 'Opening'
				
				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@sr_no,@Trans_No, @scriptname, @ScriptId, @holding_type, @billno,@dates,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@Consultant_code,@BillType
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
						IF(@Investmenttype=2)
							SET @holding_type='Mutual Fund'

						SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1_MonthWise WHERE script_name = @scriptname)
						SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1_MonthWise) else @Dup_pkid end)
						SET @Dup_pkid = ISNULL(@Dup_pkid,0)
						SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
						SET @Dup_pkid = @Dup_pkid + 1
						DECLARE @IDs INT=0

						INSERT INTO #MainOutputtable_1_MonthWise   
						(
							opening_bill_no ,sr_no,id,Dup_pkid,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Consultant_code,ScriptCode,Trans_No,   
							Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,consultant_name
						) 
						SELECT  @billno,@sr_no,@ID,@Dup_pkid, @Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,
								@dp_code,@Consultant_code, @ScriptId, @Trans_No, 'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Consultant_Name
								
						IF(@idcount>0)
							BEGIN
								UPDATE #MainOutputtable_1_MonthWise SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
							END
						FETCH NEXT FROM alldatacursor 
						INTO @ID,@sr_no,@Trans_No, @scriptname, @ScriptId, @holding_type, 
							 @billno,@dates,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,
							 @Broker_Code,@dp_code,@qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@Consultant_code,@BillType
					END 
					
				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 	
																
				DECLARE @salecount INT=0,@Boughtcount INT=0,@Flag_Type VARCHAR(20)				
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 

				Select id,sr_no ,bill_no ,BillType ,BillType,script_code,script_name,holding_type,StrikePrice,OptionType , MonthYear ,
				Last_dt,Exp_Rate,Broker_Code,DP_Code,Trans_No,CONVERT(DATETIME, trans_dt,103),qty,rate,qty * rate,ISNULL(isintraday, 0) 
				,consultant_name ,Consultant_Code           
				from #Openings
				where BillType='Sold'
				Union All
				SELECT id,sr_no,Bill_no,Flag_Type,TransType,Script_Code, script_name,[holding type],
				Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,
				Trans_No,CONVERT(DATETIME, trans_dt,103), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name,Consultant_code
				FROM #alldata WHERE 
				(TransType in ('Bought','Sold')  AND CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
				--Union All
				
				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@sr_no,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Strike_Price,@OptionType,
				@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name,@Consultant_code 
								
				WHILE (@@FETCH_STATUS = 0) 
						BEGIN
							SET @COUNT									=	0
							DECLARE @IsOpening			INT				=	0
							DECLARE @prioritysId		INT				=	0
							DECLARE @str				VARCHAR(MAX)	=	''	
							DECLARE @purchase_Op_Qty	FLOAT			=	0
							DECLARE @purchase_Op_Bill	VARCHAR(20)		=	''
							DECLARE @purchase_Op_Date	VARCHAR(20)		=	''
							DECLARE @purchase_Op_Rate	FLOAT			=	0
							DECLARE	@PurQTY				FLOAT			=	0
							DECLARE	@BalPurQTY			FLOAT			=	0
							DECLARE @BalSoldQTY			FLOAT			=	0
							DECLARE @Balpurchase_Op_Qty FLOAT			=	0
							DECLARE @BalOpeningQTY		FLOAT			=	0
							DECLARE	@Sold_Qty			FLOAT			=	0
							DECLARE @tempID				int				=	0

							IF(@isIntradayCol = 0)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1_MonthWise WHERE   script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and   Flag_Type ='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=0 AND Consultant_Name = (CASE WHEN @ConsultantCode <> '' THEN @Consultant_Name ELSE consultant_name END))																				   
										
											IF (@COUNT > 0)
												BEGIN
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  script_name, case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId, 
													* INTO #tempSoldValExists 
													FROM
													#MainOutputtable_1_MonthWise 
													WHERE script_name=@scriptname AND holding_type=@holding_type  AND isintradaycol=0 AND 
													consultant_name = (CASE WHEN @ConsultantCode <> '' THEN @Consultant_Name ELSE consultant_name END)
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold ='Sold'  and  Flag_Type ='Sold' AND isintradaycol=0
													ORDER BY NameId

													DECLARE @R_Sold_COUNT INT=(SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty INT 
												
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists ORDER BY Dup_pkid,NameId)
															SET @str = @TransType

															SELECT TOP 1	@Sold_Qty		= sold_qty,
																			@soldDate		= sold_date,
																			@soldRate		= sold_Rate,
																			@soldBillNo		= sold_bill_no,
																			@Pkid			= Pkid
																	
															FROM #tempSoldValExists
															WHERE id  = @tempSaleID 
															
															SET @purchase_Op_Qty = @qty
									
															IF(@TransType='Opening')
																BEGIN
																
																	UPDATE #MainOutputtable_1_MonthWise  
																	SET	opening_date	=	@dates,
																		opening_rate	=	@rate,																	 
																		opening_qty		=	CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	UPDATE #MainOutputtable_1_MonthWise  
																	SET	purchase_date	=	@dates,
																		purchase_rate	=	@rate,
																		purchase_bill_no=   @PurchaseBillNo,
																		purchase_qty		=	CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid

																END
															
															IF(@Sold_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1_MonthWise  
																	SET sold_qty = @purchase_Op_Qty 
																	WHERE  id  = @tempSaleID AND Flag_Type_Sold='Sold' AND pkid = @pkid
																END

															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND pkid = @pkid
														
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempSoldValExists )
															DECLARE @Balancedval   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)
										
															IF(@Balancedval  < 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1_MonthWise WHERE script_name = @scriptname)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty=ABS(@Balancedval) 
																	SET @prioritysId  =(SELECT MAX(prioritys) FROM #MainOutputtable_1_MonthWise) 
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	INSERT INTO #MainOutputtable_1_MonthWise(Dup_pkid,sr_no, ID,Consultant_code,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No,ScriptCode, Flag_Type,Flag_Type_Sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name)
																	VALUES(@Dup_pkid,@sr_no,@tempSaleID ,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No,@ScriptId,'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name)
																	
																	UPDATE #MainOutputtable_1_MonthWise 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1_MonthWise)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1_MonthWise 
																			SET Dup_pkid = Dup_pkid + 1 
																			where Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																		SET @Balancedval=0
																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1_MonthWise WHERE script_name = @scriptname)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1_MonthWise)
																	IF(@TransType='Opening')
																		BEGIN
																			INSERT INTO #MainOutputtable_1_MonthWise(Dup_pkid,ID,sr_no,Consultant_code,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No,ScriptCode, Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@sr_no,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No,@ScriptId, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name)

																			UPDATE #MainOutputtable_1_MonthWise 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	ELSE IF(@TransType='Bought')
																		BEGIN
																			INSERT INTO #MainOutputtable_1_MonthWise(Dup_pkid,ID,sr_no,Consultant_code,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@sr_no,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No,@ScriptId, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name)

																			UPDATE #MainOutputtable_1_MonthWise 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1_MonthWise)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1_MonthWise 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																END
															ELSE IF(@Balancedval=0)
															BEGIN
																break;
															END
															
															SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
															SET @qty = @Balancedval
														END
													
													DROP TABLE #tempSoldValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #MainOutputtable_1_MonthWise)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #MainOutputtable_1_MonthWise)
												 
													INSERT INTO #MainOutputtable_1_MonthWise (Dup_pkid,id,sr_no,Consultant_code,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No,ScriptCode, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name) 
													VALUES ( @Dup_pkid,@ID,@sr_no,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No,@ScriptId, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name) 
												END
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1_MonthWise WHERE   script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Transfer') AND ISNULL(sold_qty,0)=0  AND isintradaycol=0  AND Consultant_Name = (CASE WHEN @ConsultantCode <> '' THEN @Consultant_Name ELSE consultant_name END))
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  script_name ,case when opening_date <> NULL then opening_date else purchase_date end ) AS NameId, 
													* INTO #tempValExists 
													FROM
													#MainOutputtable_1_MonthWise WHERE --holding_type=@holding_type AND 
													script_name =@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') 
													AND consultant_name = (CASE WHEN isnull(@ConsultantCode,'') != '' THEN @Consultant_Name ELSE consultant_name END) 
													AND ISNULL(sold_qty,0)=0  AND isintradaycol=0 
													ORDER BY NameId
												 
													DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty int 
													
													--SET @Sold_Qty = @qty
													WHILE(@RCOUNT > 0)
														BEGIN 
															SET @Sold_Qty = @qty
															SET @tempID = (SELECT TOP(1) id FROM #tempValExists ORDER BY Dup_pkid)
															SET @str = (SELECT TOP(1) Flag_Type FROM #tempValExists WHERE id  = @tempID)
														
															IF(@str = 'Opening')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= opening_qty,
																					@openingDate	= opening_date,
																					@openingrate	= opening_rate,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID

																END
															ELSE IF(@str='Bought')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= purchase_qty,
																					@PurchaseDate	= purchase_date,
																					@Purchaserate	= purchase_rate,
																					@PurchaseBillNo = purchase_bill_no,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID

																END
															    
															IF(@Sold_Qty > 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1_MonthWise)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	UPDATE #MainOutputtable_1_MonthWise  
																		SET	
																			opening_qty = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							END,
																			purchase_qty  = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							END,
																			sold_date=@dates,
																			sold_bill_no=@billno,
																			sold_rate=@rate,
																			sold_qty= CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold='Sold',
																			prioritys       = @prioritysId
																	WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND pkid = @pkid
																	
																	SET @Balanceval = ABS(@Sold_Qty) - ABS(@TempSoldQty)
																END
															
														DELETE FROM #tempValExists WHERE id = @tempID AND pkid = @pkid
														SET @tablerowscount=(SELECT COUNT(*) FROM  #tempValExists )
														SET @RCOUNT = @RCOUNT - 1
													
													IF(@Balanceval  < 0)
														BEGIN
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1_MonthWise WHERE Pkid = @Pkid)
															SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1_MonthWise) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1
															--SET @prioritysId  =(SELECT MAX(isnull(prioritys,0))+1 FROM #MainOutputtable_1_MonthWise) 

															IF(@str='Opening')
																BEGIN
																	SET @openingQty=ABS(@Balanceval) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1_MonthWise)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	INSERT INTO #MainOutputtable_1_MonthWise(Dup_pkid,
																	ID,sr_no,Consultant_code,  Strike_Price, OptionType, MonthYear, Last_Date, Exp_Rate, Broker_Code, dp_code,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@tempID,@sr_no,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No,@ScriptId, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name)

																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																
																	UPDATE #MainOutputtable_1_MonthWise 
																	SET prioritys=@prioritysId+1  WHERE prioritys >=  @prioritysId 
																	AND ID <> @tempID
																END
															ELSE 
																BEGIN
																	SET @PurchaseQty = ABS(@Sold_Qty) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1_MonthWise)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																		
																	INSERT INTO #MainOutputtable_1_MonthWise(Dup_pkid,ID,sr_no,Consultant_code,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@ID,@sr_no,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name)
																	UPDATE #MainOutputtable_1_MonthWise SET prioritys=@prioritysId  WHERE prioritys > @prioritysId AND ID <> @tempID

																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																			
																	UPDATE #MainOutputtable_1_MonthWise 
																	SET prioritys=@prioritysId    
																	WHERE prioritys >= @prioritysId AND ID <> @tempID

																END
															

															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1_MonthWise)) 
															ELSE CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),1) FROM #MainOutputtable_1_MonthWise)) END)  
															
															IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1_MonthWise SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
																set @Balanceval=0;
															BREAK;
														END
													ELSE IF(@Balanceval  > 0 AND @tablerowscount = 0)
														BEGIN
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1_MonthWise WHERE Pkid = @Pkid)
															SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1_MonthWise) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1
															SET @prioritysId  = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1_MonthWise)

															INSERT INTO #MainOutputtable_1_MonthWise(Dup_pkid,ID,sr_no,Consultant_code,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
															VALUES(@Dup_pkid,@ID,@sr_no,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name)

															UPDATE #MainOutputtable_1_MonthWise 
															SET prioritys=@prioritysId+1  
															WHERE prioritys > @prioritysId AND ID<>@tempSaleID 

															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1_MonthWise)) END)  
														
															IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1_MonthWise 
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																	FROM Fn_split(@Pkid, ',') ) 
																END
														ENd
														ELSE IF(ISNULL(@Balanceval,0) =0)
																BEGIN
																	SET @Balanceval=0
																	BREAK;
																END
															SET @qty = @Balanceval
													END
													DROP TABLE #tempValExists
												END
											
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #MainOutputtable_1_MonthWise)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #MainOutputtable_1_MonthWise)
													INSERT INTO #MainOutputtable_1_MonthWise(Dup_pkid,ID,sr_no,Consultant_code,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No,ScriptCode , Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
													VALUES(@Dup_pkid,@ID,@sr_no,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No, @ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name)
												END
											SET @purchase_Op_Date	=	''
											SET @purchase_Op_Rate	=	''
											SET @purchase_Op_Qty	=	''
											SET @purchase_Op_Bill	=	''
										END
								END
							 
							FETCH NEXT FROM purchaseANDSaledatacursor 
							INTO @ID,@sr_no,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Strike_Price,@OptionType,
								 @MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name,@Consultant_code 
				
						END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 
				INSERT INTO #MainOutputtable_1_MonthWise_Final (OrderBy,id,sr_no,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No, prioritys,ScriptCode ,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss , closing_qty ,closing_rate ,closing_value ,
				short_term,
				long_term,
				speculation,
				gain_speculation,
				loss_speculation,
				consultant_name,nse_rate,bse_rate, sort,isintradaycol,Consultant_code )

				SELECT 
				ROW_NUMBER ( ) OVER (ORDER BY  Script_name,holding_type,dup_pkid, case when CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) else CONVERT(DATE,purchase_date,103) END,prioritys DESC, sold_date DESC ) AS NameId,
				id,sr_no,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No, prioritys,ScriptCode ,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,
				   Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) < 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				 closing_qty ,closing_rate ,closing_value ,
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365) --short term for purchase
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
						
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365) --short term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) = 0) 
							AND (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol ,Consultant_code
				FROM #MainOutputtable_1_MonthWise 
				order by NameId
		
		IF(@OUTPUT_Flag='Details')
			BEGIN
				IF(@ConsultantCode!='')
					BEGIN
						SELECT  ISNULL(opening_bill_no,' ') opening_bill_no ,id,prioritys,ScriptCode ,script_name 'Script Name',Holding_Type,
						CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',ISNULL(gain,0) 'Gain',ISNULL(loss,0) 'Loss',ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0) short_term,
						ISNULL(long_term,0) long_term,
						ISNULL(speculation,0) speculation,
						CASE WHEN isintradaycol=1 and gain!=0 THEN gain  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 and loss!=0  THEN loss  ELSE '' END loss_speculation,consultant_name,
						ISNULL(nse_rate,0) nse_rate,ISNULL(bse_rate,0) bse_rate,ISNULL(isintradaycol,0) isintradaycol,1 sort 
						FROM #MainOutputtable_1_MonthWise_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)
						ORDER BY  consultant_name,Holding_Type,script_name--,id
					END
				ELSE
					BEGIN
					
						UPDATE #MainOutputtable_1_MonthWise_Final SET prioritys=0
						DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #MainOutputtable_1_MonthWise_Final)
						UPDATE #MainOutputtable_1_MonthWise_Final
						SET prioritys  = @i , @i = @i + 1

						SELECT  isnull(opening_bill_no,' ') opening_bill_no , id,prioritys,ScriptCode ,script_name 'Script Name',Holding_Type,CONVERT(DATE, opening_date,103) 'Opening Date',
						ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',
						ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',
						ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,
						ISNULL(long_term,0)long_term,
						ISNULL(speculation,0)speculation,
				
						CASE WHEN ((isintradaycol=1) OR(isintradaycol=0)) AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN ((isintradaycol=1) OR(isintradaycol=0)) AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						consultant_name,nse_rate,bse_rate,isintradaycol,1 sort 
						FROM #MainOutputtable_1_MonthWise_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)
						--ORDER BY  script_name,id
					END
			END

		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
				SELECT  0 id ,  0 prioritys, '' opening_bill_no, '' ScriptCode , script_name 'Script Name', '' Holding_Type,'' AcType ,
				NULL 'Opening Date', SUM(ISNULL(opening_qty,0)) 'Opening Qty',  ISNULL((ISNULL(SUM(ISNULL(opening_amount,0)),0)  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate', SUM(ISNULL(opening_amount,0)) 'Opening Amount',
				NULL 'Purchase Date','' 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty',ISNULL((ISNULL(SUM(purchase_amount),0)  / SUM(NULLIF(purchase_qty,0))),0)  'Purchase Rate', SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
				NULL 'Sold Date', '' 'Sold BillNo', SUM(ISNULL(sold_qty,0)) 'Sold Qty', ISNULL((ISNULL(SUM(ISNULL(sold_amount,0)),0) / NULLIF (SUM(ISNULL(sold_qty,0)),0)),0)'Sold Rate', SUM(ISNULL(sold_amount,0)) 'Sold Amount',
				SUM(ISNULL(gain_loss ,0)) 'Gain/Loss', SUM(ISNULL(gain,0))  'Gain', SUM(ISNULL(loss,0))  'Loss',
				SUM(ISNULL(closing_qty,0))  'Closing Qty',  ISNULL((ISNULL(SUM(ISNULL(closing_value,0)),0) / NULLIF(SUM(ISNULL(closing_qty,0)),0)),0)   'Closing Rate', SUM(ISNULL(closing_value,0))  'Closing Value', SUM(ISNULL(short_term,0))  short_term, SUM(ISNULL(long_term,0))  long_term,
				SUM(ISNULL(speculation,0))speculation, SUM(ISNULL(gain_speculation,0))gain_speculation, SUM(ISNULL(loss_speculation,0))loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort 
				FROM
					(
						SELECT MAX(id+0)id ,MAX (prioritys + 0) prioritys, '' opening_bill_no, '' ScriptCode , script_name  ,'' Holding_Type,'' AcType ,
						'' 'Opening Date',SUM(opening_qty) 'Opening_Qty',sum(ISNULL(opening_rate,0)) opening_rate ,SUM(ISNULL(opening_amount,0)) 'Opening_Amount',
						'' 'Purchase Date','' purchase_bill_no,SUM(ISNULL(purchase_qty,0)) 'Purchase_Qty', SUM(ISNULL(purchase_rate,0)) purchase_rate,SUM(ISNULL(purchase_amount,0)) 'Purchase_Amount',
						'' 'Sold Date','' sold_bill_no ,SUM(ISNULL(sold_qty,0)) 'Sold_Qty', SUM(ISNULL(sold_rate,0))sold_rate  , SUM(ISNULL(sold_amount,0)) 'Sold_Amount',SUM(ISNULL(gain_loss,0)) 'Gain_Loss',SUM(ISNULL(gain,0)) 'Gain',SUM(ISNULL(loss,0)) 'Loss',
						SUM(ISNULL(closing_qty,0)) 'Closing_Qty',SUM(ISNULL(closing_rate,0)) 'Closing_Rate',SUM(ISNULL(closing_value,0)) 'Closing_Value',SUM(ISNULL(short_term,0)) short_term,SUM(ISNULL(long_term,0)) long_term,
						SUM(ISNULL(speculation,0)) speculation,SUM(ISNULL(gain_speculation,0)) gain_speculation,SUM(ISNULL(loss_speculation,0)) loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort 
						FROM #MainOutputtable_1_MonthWise_Final 
						GROUP BY script_name,Holding_Type,purchase_bill_no,sold_bill_no 
					)a
				GROUP BY  script_name  
				
				ORDER BY  Holding_Type,script_name,id
				
			END

		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN
				SELECT  prioritys ,Trans_No,id ,ScriptCode ,Broker_Code,dp_code,Consultant_code, script_name ,'Empty' Holding_Type, 
				flag_script_name,flag_Holding_Type,
				opening_date,ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),
				purchase_date,purchase_bill_no,ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount ,0),
				sold_date ,sold_bill_no ,ISNULL(sold_qty,0) ,ISNULL(sold_rate,0),ISNULL(sold_amount ,0),
				ISNULL(gain_loss,0) ,ISNULL(gain,0) ,ISNULL(loss,0),ISNULL(closing_qty,0) ,ISNULL(closing_rate,0) ,ISNULL(closing_value,0) ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,
				ISNULL(nse_rate,0),ISNULL(bse_rate,0),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,ISNULL(isintradaycol,0),Last_Date,ISNULL(Strike_Price,0),OptionType
				FROM #MainOutputtable_1_MonthWise_Final
			END


		ELSE IF(@OUTPUT_Flag='Summary')
			BEGIN

				INSERT INTO #mainoutputtable_1_Final_Summary
				SELECT  prioritys ,Trans_No,id ,ScriptCode ,Broker_Code,dp_code,Consultant_code, script_name ,'Empty' Holding_Type, 
				flag_script_name,flag_Holding_Type,
				opening_date,ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),
				purchase_date,purchase_bill_no,ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount ,0),
				sold_date ,sold_bill_no ,ISNULL(sold_qty,0) ,ISNULL(sold_rate,0),ISNULL(sold_amount ,0),
				ISNULL(gain_loss,0) ,ISNULL(gain,0) ,ISNULL(loss,0),ISNULL(closing_qty,0) ,ISNULL(closing_rate,0) ,ISNULL(closing_value,0) ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,
				ISNULL(nse_rate,0),ISNULL(bse_rate,0),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,ISNULL(isintradaycol,0),Last_Date,ISNULL(Strike_Price,0),OptionType
				FROM #MainOutputtable_1_MonthWise_Final

			
				SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
				T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
				T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
				T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
				T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
				T1.consultant_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,
				Isnull(Dr.Bse_FO_Rate,0) AS 'bse_rate', /**/
				Isnull(Dr.Nse_FO_Rate,0) AS 'nse_rate' /**/
				INTO #alldata_Summary 
				FROM #mainoutputtable_1_Final_Summary  T1
				LEFT JOIN BrokerBill T2  ON T1.Trans_No=T2.Trans_no
				LEFT JOIN DailyRate  DR  
				ON 
					DR.InvestmentType != 0 and Dr.InvestmentType != 2 AND
					DR.Script_Code = T1.ScriptCode 
					and dr.Trans_Dt =  Convert(datetime,@Todate,101) 
					AND 
					Convert(varchar,DR.Expir_Date ,101) =  Convert(varchar,T1.Last_Date,101) 
					AND
					ISNULL(Substring(RTRIM(LTRIM(T1.OptionType)),0,3),'') = ISNULL( DR.OptionType,'') 
					AND
					ISNULL(DR.Strike_Price,0) = ISNULL(T1.Strike_Price,'')
			
			
				TRUNCATE TABLE #mainoutputtable_1_Final_Summary
				INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
				opening_date,opening_qty,opening_rate,opening_amount,
				purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
				sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
				closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
				consultant_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt) 

				SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
				opening_date,opening_qty,opening_rate,opening_amount,
				purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
				sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
				closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
				consultant_name,
				Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
				sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 
		
				FROM #alldata_Summary  

				GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
				opening_date,opening_qty,opening_rate,opening_amount,
				purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
				sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
				closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
				consultant_name,sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 


		IF(@RecordOnlyhavingClosingbalanceZero = 0)
			BEGIN
				IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE 
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END  AS  'Closing Date',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0)>0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
											0 END 
											END AS 'Avg. Rate',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
											0 END 
											END AS 'Value After Profit/Loss',
										SUM(ISNULL(Other_amt,0))Other_amt, '' consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY script_name,holding_type,bse_rate,nse_rate,
										  CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END 
										HAVING SUM(closing_qty) != 0
							END
					END
				ELSE IF(@WithActualAvgRate = 1 OR @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								IF(@WithActualAvgRate=0 AND @DateWiseClosinStock=1)
									BEGIN
										SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END  AS  'Closing Date',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',
										SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
										SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
										SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY holding_type,script_name,bse_rate,nse_rate,
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END, consultant_name
										HAVING SUM(closing_qty) != 0
									END
								ELSE IF(@WithActualAvgRate=1 AND @DateWiseClosinStock=0)
									BEGIN
										SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
										'' 'Closing Date',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  AND NULLIF(SUM(closing_qty),0) > 0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0 AND NULLIF(SUM(closing_qty),0) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
											0 END 
											END AS 'Avg. Rate',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  AND NULLIF(SUM(closing_qty),0) > 0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0  AND NULLIF(SUM(closing_qty),0) > 0 THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
											0 END 
											END AS 'Value After Profit/Loss',
										SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY holding_type,script_name,bse_rate,nse_rate,
										 bse_rate,nse_rate,consultant_name
										HAVING SUM(closing_qty) != 0
									END
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN
								SELECT   MAX(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(NULLIF(closing_value,0)),2) AS 'Closing Value',SUM(NULLIF(closing_qty,0)) AS 'Closing Qty',
								NULLIF(ROUND( ABS(SUM(NULLIF(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date','' 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(ISNULL(closing_qty,0))  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE ISNULL(bse_rate,0) * ISNULL(SUM(NULLIF(closing_qty,0)),0) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(ISNULL(closing_qty,0)) AS  'NSE_Valuation',
								CASE WHEN ISNULL(nse_rate,0) = 0 THEN 0 ELSE  NULLIF(nse_rate,0) * SUM(NULLIF(closing_qty,0)) - SUM(NULLIF(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(NULLIF(gain_loss,0)) AS 'Profit/Loss',
								SUM(NULLIF(closing_value,0)) - SUM(NULLIF(gain_loss,0)) AS 'Value After Profit/Loss',
								SUM(NULLIF(closing_value,0)) - SUM(NULLIF(gain_loss,0)) / SUM(NULLIF(closing_qty,0)) as 'Avg. Rate',
								SUM(NULLIF(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',
								SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0)) / nullif(SUM(closing_qty),0)),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					END
			END
		ELSE IF(@RecordOnlyhavingClosingbalanceZero = 1)
			BEGIN
				IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE 
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0)>0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY script_name,holding_type,bse_rate,nse_rate,
									CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
							END 
										--HAVING SUM(closing_qty) != 0
						END
					END
				ELSE IF (@WithActualAvgRate = 1 OR @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  MAX(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE if(@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1)
								BEGIN
									IF(@ConsultantCode<>'')
										BEGIN
											SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
											bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
											bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
											CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
											nse_rate AS  'NSERATE',
											nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
											CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
											SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
											SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) AS 'Value After Profit/Loss',
											SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) / NULLIF(SUM(ISNULL(closing_qty,0)),0) AS 'Avg. Rate',
											SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
											FROM #mainoutputtable_1_Final_Summary
											GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
											HAVING SUM(closing_qty) != 0
											ORDER BY consultant_name

										END
									ELSE
										BEGIN
											SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
											CASE
												WHEN closing_qty < 0 THEN sold_date
												WHEN ISNULL(opening_date,'') != '' THEN opening_date
												WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
											END  AS  'Closing Date',
											bse_rate  AS  'BSERATE',
											bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
											CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
											nse_rate AS  'NSERATE',
											nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
											CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
											SUM(gain_loss) AS 'Profit/Loss',
											SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
											SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate'
											FROM #mainoutputtable_1_Final_Summary
											GROUP BY holding_type,script_name,bse_rate,nse_rate ,
											CASE
												WHEN closing_qty < 0 THEN sold_date
												WHEN ISNULL(opening_date,'') != '' THEN opening_date
												WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
											END
											HAVING SUM(closing_qty) = 0
									END
								END
						ELSE if(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0)
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0)>0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY script_name,holding_type,bse_rate,nse_rate
						 END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) AS 'Value After Profit/Loss',
								SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) / NULLIF(SUM(ISNULL(closing_qty,0)),0) AS 'Avg. Rate',
								SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name

							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / nullif(SUM(closing_qty),0) AS 'Avg. Rate',
								0 Other_amt,'' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) = 0
							END
					END
			END


		END
		
		ELSE IF(@OUTPUT_Flag='ClosingFNOWithProfitLoss')
		BEGIN
		 -- Select * from #MainOutputtable_1_MonthWise_Final
		      Select ISnull( Sum(gain),0) as'Gain',ISnull(Sum(loss),0) as'Loss',ISnull(Sum(closing_value),0) as'ClosingValue' from #MainOutputtable_1_MonthWise_Final
		END
		DROP TABLE #MainOutputtable_1_MonthWise 
	 
		DROP TABLE #alldata 
		--DROP TABLE #alldata_Summary
	 
  END  





































GO
/****** Object:  StoredProcedure [dbo].[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary] AS' 
END
GO


--Execute  proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary    0,1,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-02-01 03:50:37:50','','','','', '0' ,'0',0,0,0
--Execute  proc_Stockholdingposition_Equity_Summary    0,0,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0',1,1,1
ALTER PROCEDURE [dbo].[proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary]  --''
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate datetime,@Todate datetime, 
@ScriptCode VARCHAR(MAX),@ConsultantCode  VARCHAR(MAX),@BSE_NSE_Code VARCHAR(MAX),@Is_BFCF VARCHAR(MAX),@IsIntraDay VARCHAR(MAX),@short_Long_Term INT,
@RecordOnlyhavingClosingbalanceZero AS BIT,@WithActualAvgRate AS BIT, @DateWiseClosinStock AS BIT,
@Script_Name varchar(max) = '')

AS
BEGIN
SET NOCOUNT ON;
		CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
			prioritys INT,
			Trans_No VARCHAR(50),
			id INT,
			ScriptCode VARCHAR(50), 
			Broker_Code VARCHAR(100),
			dematcode VARCHAR(100),
			Consultant_code  VARCHAR(100),
			script_name  VARCHAR(500),
			holding_type VARCHAR(200),
			flag_script_name  VARCHAR(500),
			flag_holding_type VARCHAR(200),
			opening_date DATETIME,opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
			purchase_date DATETIME,purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
			sold_date DATETIME,sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
			gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
			closing_qty FLOAT DEFAULT 0, 
			closing_rate FLOAT DEFAULT 0,
			closing_value FLOAT DEFAULT 0,
			short_term FLOAT DEFAULT 0,
			long_term FLOAT DEFAULT 0, 
			speculation FLOAT DEFAULT 0, 
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			consultant_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			Other_amt FLOAT DEFAULT 0,
			ServTax_Amt FLOAT DEFAULT 0,
			Stt_amt FLOAT DEFAULT 0,
			sort   VARCHAR(5),
			isintradaycol  INT,
			Last_Date dateTime,
			Strike_Price float,
			OptionType varchar(max)
        ) 
				
		IF(@ConsultantCode = '0')	
			BEGIN
						
					SELECT DISTINCT p.member_code,p.year_code,
						STUFF((	SELECT distinct ',' + p1.Consultant_Code
								FROM Mst_Consultant p1
								FOR XML PATH(''), TYPE
								).value('.', 'NVARCHAR(MAX)')
						,1,1,'') ConsultantCode
					into #temoConsultant
					FROM Mst_Consultant p

					SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant WHERE member_code = @memcode AND year_code = @yearcode)
					DROP table #temoConsultant
			END

		INSERT INTO #mainoutputtable_1_Final_Summary
		EXEC proc_MonthWise_Stockholdingposition_F_And_O_AND_MCX_And_Currency   @status,@Investmenttype,@Ac_Type,@memcode,@yearcode,@Fromdate,@Todate,@ScriptCode,@ConsultantCode,@BSE_NSE_Code,@Is_BFCF,@IsIntraDay,@short_Long_Term,'ALLData',0,0,0,0,@Script_Name

		SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
		T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
		T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
		T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
		T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
		T1.consultant_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,
		Isnull(Dr.Bse_FO_Rate,0) AS 'bse_rate', /**/
		Isnull(Dr.Nse_FO_Rate,0) AS 'nse_rate' /**/
		INTO #alldata_Summary 
		FROM #mainoutputtable_1_Final_Summary  T1
		LEFT JOIN BrokerBill T2  ON T1.Trans_No=T2.Trans_no
		LEFT JOIN DailyRate  DR  
		ON 
			DR.InvestmentType != 0 and Dr.InvestmentType != 2 AND
			DR.Script_Code = T1.ScriptCode and  Convert(varchar,dr.Trans_Dt,101) =  Convert(varchar,@Todate,101) AND 
			Convert(varchar,DR.Expir_Date ,101) =  Convert(varchar,T1.Last_Date,101) AND
			ISNULL(Substring(RTRIM(LTRIM(T1.OptionType)),0,3),'') = ISNULL( DR.OptionType,'') AND
			ISNULL(DR.Strike_Price,0) = ISNULL(T1.Strike_Price,'')
					  
		TRUNCATE TABLE #mainoutputtable_1_Final_Summary
		INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt) 

		SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,nse_rate,bse_rate,sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 
		
		FROM #alldata_Summary  

		GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,nse_rate,bse_rate,sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 


		IF(@RecordOnlyhavingClosingbalanceZero = 0)
			BEGIn
				IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE 
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END  AS  'Closing Date',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0)>0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
											0 END 
											END AS 'Avg. Rate',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
											0 END 
											END AS 'Value After Profit/Loss',
										SUM(ISNULL(Other_amt,0))Other_amt, '' consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY script_name,holding_type,bse_rate,nse_rate,
										  CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END 
										HAVING SUM(closing_qty) != 0
							END
					END
				ELSE IF(@WithActualAvgRate = 1 OR @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								IF(@WithActualAvgRate=0 AND @DateWiseClosinStock=1)
									BEGIN
										SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END  AS  'Closing Date',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',
										SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
										SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
										SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY holding_type,script_name,bse_rate,nse_rate,
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END, consultant_name
										HAVING SUM(closing_qty) != 0
									END
								ELSE IF(@WithActualAvgRate=1 AND @DateWiseClosinStock=0)
									BEGIN
										SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
										'' 'Closing Date',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  AND NULLIF(SUM(closing_qty),0) > 0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0 AND NULLIF(SUM(closing_qty),0) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
											0 END 
											END AS 'Avg. Rate',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  AND NULLIF(SUM(closing_qty),0) > 0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0  AND NULLIF(SUM(closing_qty),0) > 0 THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
											0 END 
											END AS 'Value After Profit/Loss',
										SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY holding_type,script_name,bse_rate,nse_rate,
										 bse_rate,nse_rate,consultant_name
										HAVING SUM(closing_qty) != 0
									END
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN
								SELECT   MAX(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(NULLIF(closing_value,0)),2) AS 'Closing Value',SUM(NULLIF(closing_qty,0)) AS 'Closing Qty',
								NULLIF(ROUND( ABS(SUM(NULLIF(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date','' 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(ISNULL(closing_qty,0))  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE ISNULL(bse_rate,0) * ISNULL(SUM(NULLIF(closing_qty,0)),0) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(ISNULL(closing_qty,0)) AS  'NSE_Valuation',
								CASE WHEN ISNULL(nse_rate,0) = 0 THEN 0 ELSE  NULLIF(nse_rate,0) * SUM(NULLIF(closing_qty,0)) - SUM(NULLIF(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(NULLIF(gain_loss,0)) AS 'Profit/Loss',
								SUM(NULLIF(closing_value,0)) - SUM(NULLIF(gain_loss,0)) AS 'Value After Profit/Loss',
								SUM(NULLIF(closing_value,0)) - SUM(NULLIF(gain_loss,0)) / SUM(NULLIF(closing_qty,0)) as 'Avg. Rate',
								SUM(NULLIF(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',
								SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0)) / nullif(SUM(closing_qty),0)),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					END
			END
		ELSE IF(@RecordOnlyhavingClosingbalanceZero = 1)
			BEGIN
				IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE 
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0)>0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY script_name,holding_type,bse_rate,nse_rate,
									CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
							END 
										--HAVING SUM(closing_qty) != 0
						END
					END
				ELSE IF (@WithActualAvgRate = 1 OR @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  MAX(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE if(@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1)
								BEGIN
									IF(@ConsultantCode<>'')
										BEGIN
											SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
											bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
											bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
											CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
											nse_rate AS  'NSERATE',
											nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
											CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
											SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
											SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) AS 'Value After Profit/Loss',
											SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) / NULLIF(SUM(ISNULL(closing_qty,0)),0) AS 'Avg. Rate',
											SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
											FROM #mainoutputtable_1_Final_Summary
											GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
											HAVING SUM(closing_qty) != 0
											ORDER BY consultant_name

										END
									ELSE
										BEGIN
											SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
											CASE
												WHEN closing_qty < 0 THEN sold_date
												WHEN ISNULL(opening_date,'') != '' THEN opening_date
												WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
											END  AS  'Closing Date',
											bse_rate  AS  'BSERATE',
											bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
											CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
											nse_rate AS  'NSERATE',
											nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
											CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
											SUM(gain_loss) AS 'Profit/Loss',
											SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
											SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate'
											FROM #mainoutputtable_1_Final_Summary
											GROUP BY holding_type,script_name,bse_rate,nse_rate ,
											CASE
												WHEN closing_qty < 0 THEN sold_date
												WHEN ISNULL(opening_date,'') != '' THEN opening_date
												WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
											END
											HAVING SUM(closing_qty) = 0
									END
								END
						ELSE if(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0)
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0)>0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY script_name,holding_type,bse_rate,nse_rate
						 END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) AS 'Value After Profit/Loss',
								SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) / NULLIF(SUM(ISNULL(closing_qty,0)),0) AS 'Avg. Rate',
								SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name

							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / nullif(SUM(closing_qty),0) AS 'Avg. Rate',
								0 Other_amt,'' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) = 0
							END
					END
			END
			DROP TABLE #alldata_Summary
END





























GO
/****** Object:  StoredProcedure [dbo].[proc_Physical_Demate]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Physical_Demate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Physical_Demate] AS' 
END
GO



-- Select * from mst_Member
-- Select * from BrokerBill_DmatInfo Where Member_Code ='M0001'

 --Execute proc_Physical_Demate '30001','1120182019','2019-31-03','','30002','','','ScriptWiseAll',''

ALTER PROCEDURE [dbo].[proc_Physical_Demate]  --  'A0001' ,'1120172018','2018-02-02','110036','AllData'
@membercode varchar(max),
@yearcode varchar(20),
@tilldate varchar(50),
@Ac_Type varchar(max),
@Scriptcode varchar(max),
@familycode varchar(max),
@dematcode varchar(max),
@mode varchar(100),
@WithoutDetails bit,  
@IsBSEISIN bit =0,
@IvestmentType varchar(10)
AS
	BEGIN
	SET NOCOUNT ON;
		Create Table #Temp
		(
			TransDate varchar(100),
			DP_Name varchar(100),
			Script_Name varchar(100),
			Ac_Type varchar(100),
			transType varchar(100),
			[In Qty]  float,
			[Out Qty] float,
			Trans_No varchar(100),
			Family_Name varchar(100),
			Member_Name varchar(100),
			Member_Code varchar(50),
			Family_Code varchar(50),
			Scriptcode Varchar(50)
		)	

		IF(@mode='DemateWiseAllData')
			BEGIN
				
				Insert into #Temp
				SELECT  
					Convert(Varchar(10),BBD.Trans_Dt,103)  'TransDate',
					MD.DP_Name,				
					MS.Script_Name ,
					BBD.Ac_Type,
					CASE WHEN  BBD.Trans_Type = 'O'  THEN 'Sold' ELSE
					CASE WHEN  BBD.Trans_Type = 'I' AND BBt.Bill_no='Opening' THEN 'Opening' ELSE
					CASE WHEN  BBD.Trans_Type = 'I' AND BBt.Bill_no='Ipo' THEN 'Ipo' ELSE
					CASE WHEN  BBD.Trans_Type = 'I' AND BBt.Bill_no='Bonus' THEN 'Bonus' ELSE
					CASE WHEN  BBD.Trans_Type = 'I' AND BBt.Bill_no='Rights' THEN 'Rights' ELSE
					CASE WHEN  BBD.Trans_Type = 'I' AND BBt.Bill_no='Split' THEN 'Splits' ELSE
					CASE WHEN  BBD.Trans_Type = 'I' THEN 'Bought' 
					ELSE ''  END END END END END END END AS transType ,
					CASE  WHEN  BBD.Trans_Type = 'I' 
						  THEN  BBD.Qty
						  ELSE 0
					END AS 'In Qty' ,
					CASE  WHEN  BBD.Trans_Type = 'O' 
						  THEN  BBD.Qty
						  ELSE 0
				    END as 'Out Qty', 
					BBD.Trans_No,
					MF.Family_Name,
					MM.Member_Name,
					MM.Member_Code,
					MF.Family_Code,
					BBD.Script_Code
					FROM BrokerBill_DmatInfo BBD
					LEFT JOIN BrokerBill_Trans BBT ON BBD.Trans_No=BBT.Trans_No --AND BBT.Trans_Dt = BBD.Trans_Dt AND BBT.Script_Code = BBd.Script_Code AND BBT.Qty = BBd.Qty
					LEFT JOIN Mst_Script MS ON MS.Script_Code=BBD.Script_Code
					LEFT JOIN Mst_Demat MD ON MD.DP_Code = BBD.dp_code and MD.Member_Code=@membercode and MD.Year_Code=@yearcode
					LEFT JOIN Mst_Member MM on MM.Member_Code=BBD.Member_code
					LEFT JOIN Mst_Family MF ON MF.Family_Code=MM.Family_Code
				WHERE  
				BBD.YearCode=CASE WHEN @yearcode<>'' THEN @yearcode ELSE BBD.YearCode END 
				AND  BBD.Ac_Type=(CASE WHEN @Ac_Type ='' THEN BBD.Ac_Type ELSE @Ac_Type END)
				AND  BBD.Script_Code IN (SELECT Value FROM membercodestable(CASE WHEN @Scriptcode  <> '' THEN  @Scriptcode ELSE BBD.Script_Code END,','))  
				AND  BBD.dp_code     IN (SELECT Value FROM membercodestable(CASE WHEN @dematcode   <> '' THEN  @dematcode  ELSE BBD.dp_code END,',')) 
				AND  BBD.Member_code IN (SELECT Value FROM membercodestable(CASE WHEN @membercode  <> '' THEN  @membercode ELSE BBD.Member_code END,',')) 
				AND  MF.Family_Code IN (SELECT Value FROM membercodestable(CASE WHEN @familycode  <> '' THEN  @familycode ELSE MF.Family_Code END,',')) 
				AND (@IvestmentType=0 AND BBD.frmpg IN('BB','OP','BBK','ST','IPO')) OR( @IvestmentType=2 AND   BBD.frmpg IN('MF','MFOP','MFST') AND BBD.Member_Code IN (SELECT Value FROM membercodestable(CASE WHEN @membercode  <> '' THEN  @membercode ELSE BBD.Member_code END,',')) and BBD.YearCode=@yearcode)
				GROUP BY  BBD.Sr_No,MD.DP_Name,MS.Script_Name,MF.Family_Name,MM.Member_Name,MM.Member_Code, BBD.Trans_Type,
						  MF.Family_Code,BBD.Trans_Type,BBD.Qty,BBD.Trans_Dt,BBD.Ac_Type,BBD.Trans_No, BBt.Bill_no,BBD.Script_Code
				ORDER BY DP_Name,Script_Name
			END
		ELSE IF(@mode='ScriptWiseAll')
			BEGIN
				Insert into #Temp
				SELECT  
					Convert(Varchar(10),BBD.Trans_Dt,103)  'TransDate',
					MD.DP_Name,
					MS.Script_Name ,
					BBD.Ac_Type,
					CASE WHEN  BBD.Trans_Type = 'O'  THEN 'Sold' ELSE
					CASE WHEN  BBD.Trans_Type = 'I' AND BBt.Bill_no='Opening' THEN 'Opening' ELSE
					CASE WHEN  BBD.Trans_Type = 'I' AND BBt.Bill_no='Ipo' THEN 'Ipo' ELSE
					CASE WHEN  BBD.Trans_Type = 'I' AND BBt.Bill_no='Bonus' THEN 'Bonus' ELSE
					CASE WHEN  BBD.Trans_Type = 'I' AND BBt.Bill_no='Rights' THEN 'Rights' ELSE
					CASE WHEN  BBD.Trans_Type = 'I' AND BBt.Bill_no='Split' THEN 'Splits' ELSE
					CASE WHEN  BBD.Trans_Type = 'I' THEN 'Bought' 
					ELSE ''  END END END END END END END AS transType ,
					CASE  WHEN  BBD.Trans_Type = 'I' 
						  THEN  BBD.Qty
						  ELSE 0
					END AS 'In Qty' ,
					CASE  WHEN  BBD.Trans_Type = 'O' 
						  THEN  BBD.Qty
						  ELSE 0
				    END as 'Out Qty', 
					BBD.Trans_No,
					MF.Family_Name,
					MM.Member_Name,
					MM.Member_Code,
					MF.Family_Code,
					BBD.Script_Code
					FROM BrokerBill_DmatInfo BBD
					LEFT JOIN BrokerBill_Trans BBT 
						ON BBT.Trans_No=BBD.Trans_No 
					LEFT JOIN Mst_Script MS 
						ON MS.Script_Code=BBD.Script_Code
					LEFT JOIN Mst_Demat MD 
						ON MD.DP_Code = BBD.dp_code 
						and MD.Member_Code IN (SELECT Value FROM membercodestable(CASE WHEN @membercode  <> '' THEN  @membercode ELSE BBD.Member_code END,',')) 
						and MD.Year_Code=@yearcode
					LEFT JOIN Mst_Member MM on MM.Member_Code = BBD.Member_code
					LEFT JOIN Mst_Family MF ON MF.Family_Code = MM.Family_Code
				WHERE  
				BBD.YearCode = CASE WHEN @yearcode <> '' THEN @yearcode ELSE BBD.YearCode END 
				AND  BBD.Ac_Type= ( CASE WHEN @Ac_Type ='' THEN BBD.Ac_Type ELSE @Ac_Type END )
				AND  BBD.Script_Code IN (SELECT Value FROM membercodestable(CASE WHEN @Scriptcode  <> '' THEN  @Scriptcode ELSE BBD.Script_Code END,','))  
				AND  BBD.dp_code     IN (SELECT Value FROM membercodestable(CASE WHEN @dematcode   <> '' THEN  @dematcode  ELSE BBD.dp_code END,',')) 
				AND  BBD.Member_code IN (SELECT Value FROM membercodestable(CASE WHEN @membercode  <> '' THEN  @membercode ELSE BBD.Member_code END,',')) 
				AND  MF.Family_Code IN (SELECT Value FROM membercodestable(CASE WHEN @familycode  <> '' THEN  @familycode ELSE MF.Family_Code END,',')) 
				AND (@IvestmentType=0 AND BBD.frmpg IN('BB','OP','BBK','ST','IPO')) OR( @IvestmentType=2 AND   BBD.frmpg IN('MF','MFOP','MFST') AND BBD.Member_Code IN (SELECT Value FROM membercodestable(CASE WHEN @membercode  <> '' THEN  @membercode ELSE BBD.Member_code END,',')) and BBD.YearCode=@yearcode)
				GROUP BY  BBD.Sr_No,MD.DP_Name,MS.Script_Name,MF.Family_Name,MM.Member_Name,MM.Member_Code, BBD.Trans_Type,
						  MF.Family_Code,BBD.Trans_Type,BBD.Qty,BBD.Trans_Dt,BBD.Ac_Type,BBD.Trans_No,BBt.Bill_no,BBD.Script_Code
				ORDER BY Script_Name,DP_Name
			END

			IF(@IsBSEISIN=1)
			BEGIN
			Select #Temp.TransDate,#Temp.DP_Name,#Temp.Script_Name + '[' + Ms.BSE_Code + ']' + '[' +Ms.ISIN_No+ ']' As 'Script_Name',#Temp.Ac_Type,#Temp.transType ,#Temp.[In Qty],
			#Temp.[Out Qty],#Temp.Trans_No,#Temp.Family_Name ,#Temp.Member_Name ,#Temp.Member_Code ,#Temp.Family_Code ,#Temp.Scriptcode 
			from #Temp
			INNER JOIN Mst_Script Ms On  #Temp.Scriptcode=Ms.Script_Code
			GROUP BY #Temp.TransDate,#Temp.DP_Name,#Temp.Script_Name,Ms.BSE_Code,Ms.ISIN_No,#Temp.Ac_Type,#Temp.transType ,#Temp.[In Qty],
			#Temp.[Out Qty],#Temp.Trans_No,#Temp.Family_Name ,
			#Temp.Member_Name ,#Temp.Member_Code ,#Temp.Family_Code ,#Temp.Scriptcode
			Order by  #Temp.Script_Name,#Temp.TransDate
			END

			ELSE IF(@IsBSEISIN=0)
			BEGIN
			Select * from #Temp
			END

		IF(@IsBSEISIN=1)
			BEGIN
			IF(@WithoutDetails = 0) 
				--Select * from #Temp
			Select #Temp.TransDate,#Temp.DP_Name,#Temp.Script_Name + '[' +Ms.BSE_Code + ']' + '[' + Ms.ISIN_No+ ']' As 'Script_Name',#Temp.Ac_Type,#Temp.transType ,#Temp.[In Qty],
			#Temp.[Out Qty],#Temp.Trans_No,#Temp.Family_Name ,#Temp.Member_Name ,#Temp.Member_Code ,#Temp.Family_Code ,#Temp.Scriptcode 
			from #Temp
			INNER JOIN Mst_Script Ms On  #Temp.Scriptcode=Ms.Script_Code
			GROUP BY #Temp.TransDate,#Temp.DP_Name,#Temp.Script_Name,Ms.BSE_Code,Ms.ISIN_No,#Temp.Ac_Type,#Temp.transType ,#Temp.[In Qty],
			#Temp.[Out Qty],#Temp.Trans_No,#Temp.Family_Name ,
			#Temp.Member_Name ,#Temp.Member_Code ,#Temp.Family_Code ,#Temp.Scriptcode
			Order by  #Temp.Script_Name,#Temp.TransDate

			ELSE 
				BEGIN					
					IF(@familycode = '')
						Select  #Temp.DP_Name ,#Temp.Script_Name + '[' + Ms.BSE_Code + ']' + '[' + Ms.ISIN_No+ ']' As 'Script_Name',#Temp.Member_Name,#Temp.Member_Code, SUM([In Qty]) - SUM([Out Qty]) as 'Balance Qty' 
						From #Temp 	
						INNER JOIN Mst_Script Ms On  #Temp.Scriptcode=Ms.Script_Code				
						GRoup By  #Temp.DP_Name ,#Temp.Script_Name,#Temp.Member_Name,#Temp.Member_Code,Ms.BSE_Code,Ms.ISIN_No
						Order by #Temp.Script_Name,#Temp.Member_Name,#Temp.DP_Name			
					ELSE 				
						Select  #Temp.DP_Name,#Temp.Script_Name + '[' + Ms.BSE_Code + ']' + '[' + Ms.ISIN_No+ ']' As 'Script_Name',#Temp.Family_Name , #Temp.Family_Code,#Temp.Member_Name,#Temp.Member_Code, SUM([In Qty]) - SUM([Out Qty]) as 'Balance Qty' From #Temp 
						INNER JOIN Mst_Script Ms On  #Temp.Scriptcode=Ms.Script_Code
						GRoup By  #Temp.DP_Name ,#Temp.Script_Name,#Temp.Family_Name,#Temp.Family_Code,#Temp.Member_Name,#Temp.Member_Code,Ms.BSE_Code,Ms.ISIN_No
						Order by #Temp.Script_Name,#Temp.Family_Name,#Temp.DP_Name			  
				ENd		
		END	
		ELSE IF(@IsBSEISIN=0)
		BEGIN
		IF(@WithoutDetails = 0) 
				Select * from #Temp
			ELSE 
				BEGIN					
					IF(@familycode = '')
						Select  DP_Name ,Script_Name,Member_Name,Member_Code, SUM([In Qty]) - SUM([Out Qty]) as 'Balance Qty' 
						From #Temp 
						GRoup By  DP_Name ,Script_Name,Member_Name,Member_Code
						Order by Script_Name,Member_Name,DP_Name
					
					ELSE 				
						Select  DP_Name,Script_Name,Family_Name , Family_Code,Member_Name,Member_Code, SUM([In Qty]) - SUM([Out Qty]) as 'Balance Qty' From #Temp 
						GRoup By  DP_Name ,Script_Name,Family_Name,Family_Code,Member_Name,Member_Code 
						Order by Script_Name,Family_Name,DP_Name			  
				ENd		
		END			 
			DROP Table #Temp		
	END























GO
/****** Object:  StoredProcedure [dbo].[proc_Report_All]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Report_All]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Report_All] AS' 
END
GO
ALTER procedure [dbo].[proc_Report_All] 
@Membercode varchar(Max),
@Yearcode varchar(20),
@code varchar(Max),
@mode varchar(20)

as
BEGIN
	IF(@mode='family')
		BEGIN
		SET NOCOUNT ON;
			SELECT   MF.Family_Code as 'Family_Code' ,'Fam_Name:'+ space(1) + MF.Family_Name  AS Family_Name FROM Mst_Family MF 
			LEFT JOIN Mst_Member MM ON MF.Family_Code=MM.Family_Code 
			LEFt JOIN Mst_Year MY ON MY.Member_Code=MM.Member_Code 
			WHERE MM.Member_Code=@Membercode and MY.Year_Code=@Yearcode
		END
	ELSE IF(@mode='member')
		BEGIN
			SELECT MM.Member_Code,MM.Member_Name FROM Mst_Member MM LEFT JOIN Mst_Year MY ON MY.Member_Code=MM.Member_Code 
			WHERE MM.Family_Code=@code AND MM.Member_Code=@Membercode AND MY.Year_Code=@Yearcode
		END

	ELSE IF(@mode='memberDetails')
		BEGIN
			SELECT MM.Member_Name,MM.Member_Code,Gender FROM Mst_Member MM LEFT JOIN Mst_Year MY ON MY.Member_Code=MM.Member_Code 
			WHERE MM.Member_Code=@Membercode AND MY.Year_Code=@Yearcode
		END
	ELSE IF(@mode='memberPan_ST')
		BEGIN
			SELECT  MM.PanNo, MM.ServTax_No FROM Mst_Member MM  LEFT JOIN Mst_Year MY ON MY.Member_Code=MM.Member_Code 
			where  MM.panno    !='' and  MM.Member_Code=@code AND MY.Year_Code=@Yearcode
		END
		---pending
	ELSE IF(@mode='industry')
		BEGIN
			select * from Mst_Industry
		END
		---pending
	ELSE IF(@mode='industrydetails')
		BEGIN
 			SELECT  
			CASE WHEN  MS.Script_Code is null then '' else MS.Script_Code end as  Script_Code, 
			CASE WHEN  MS.Script_Name is null then '' else MS.Script_Name end as  Script_Name
			FROM Mst_Industry MI LEFT JOIN mst_script MS 
			ON MS.Industry_Code=MI.Industry_Code WHERE  MI.Industry_Code=@code ORDER BY MI.Industry_Name 
		END
	ELSE IF(@mode='consultant')
		BEGIN
 			 select Consultant_Code as 'Consultant Code' ,Consultant_Name as 'Consultant Name' from Mst_Consultant where member_code=@Membercode AND  Year_Code=@Yearcode
			 group by Consultant_Code,Consultant_Name
		END
		---pending
	ELSE IF(@mode='script_MutualFund')
		BEGIN
 			SELECT MS.Script_Code AS 'Script Code',MS.Script_Name AS 'Script Name',MS.BSE_Code AS 'BSE Code',MS.NSE_Code AS 'NSE Code',MS.Script_Group AS 'Group',
			MS.ISIN_No AS 'ISIN No.' , MI.Industry_Name AS 'Industry Name' FROM Mst_Script MS left outer join Mst_Industry MI ON MS.Industry_Code=MI.Industry_Code
		END

		---pending
	ELSE IF(@mode='narration')
		BEGIN
			SELECT Narration_Name  'Narration Name',Narration_Code 'Narration Code' FROM Mst_Narration
		END

	ELSE IF(@mode='investment')
		BEGIN
			SELECT DISTINCT Investment_Name  'Investment Name',Investment_Code 'Investment Code' FROM Mst_Investment where member_code=@Membercode AND  Year_Code=@Yearcode
		END
	 
	ELSE IF(@mode='accgroup')
		BEGIN
			SELECT  MAG.GRP_NAME  'Group Name' , MAG.hname  'Under Group' from Mst_AcGroup  MAG LEFT JOIN Mst_Account MA ON MA.Grp_Id=MAG.Grp_Id
			WHERE MA.Year_Code=@Yearcode and MA.Member_Code=@Membercode GROUP BY  MAG.GRP_NAME ,MAG.hname 
		END

	ELSE IF(@mode='demat')
		BEGIN
			SELECT DP_Code 'Code',DP_Name 'Name' FROM Mst_Demat where member_code=@Membercode AND  Year_Code=@Yearcode GROUP BY DP_Code,DP_Name
		END

	ELSE IF(@mode='MF_Family')
		BEGIN
			SELECT MFF_Code 'MF_Family Code',MFF_Name 'MF_Family Name' FROM Mst_MF_Family
		END
END

  
























GO
/****** Object:  StoredProcedure [dbo].[proc_Reports_All]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Reports_All]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Reports_All] AS' 
END
GO

-- EXEC [proc_Reports_All] '0','1'
ALTER PROCEDURE [dbo].[proc_Reports_All] 

@status int,
@chk int,
@code varchar(Max)

AS

BEGIN
SET NOCOUNT ON;
---------------------------------------------------Family Master Report---------------------------------------------------------------------------------------------------
	
		IF(@status=0 and @chk=1)
		BEGIN
		--select MF.Family_Name as 'Family Name', MF.Family_Code as 'Family Code',MM.Member_Code as 'Member Code',MM.Member_Name as 'Member Name'
		--from Mst_Family MF left outer join Mst_Member MM on MF.Family_Code=MM.Family_Code 
		--order by MF.Family_Code
			SELECT * FROM Mst_Family
		END

		else if(@status=0 and @chk=0)
		begin
		select distinct MF.Family_Name as 'Family Name',MF.Family_Code as 'Family Code' from Mst_Family MF left outer join Mst_Member MM on MF.Family_Code=MM.Family_Code 
        order by MF.Family_Code
		end

---------------------------------------------------Family Master Report---------------------------------------------------------------------------------------------------


---------------------------------------------------Member Master Report---------------------------------------------------------------------------------------------------

		else if(@status=1 and @chk=0)
		begin
		select MM.Member_Name as 'Member Name', MM.Member_Code as 'Member Code',MM.Gender as 'Gender' from Mst_Family MF right outer join Mst_Member MM on MF.Family_Code=MM.Family_Code 
        order by MF.Family_Code
		end

		else if(@status=1 and @chk=1)
		begin
		select MM.Member_Name as 'Member Name', MM.Member_Code as 'Member Code',MM.Gender as 'Gender',MM.PanNo as 'P.A.N',MM.ServTax_No as 'Service Tax No.' from Mst_Family MF right outer join Mst_Member MM on MF.Family_Code=MM.Family_Code 
        order by MF.Family_Code
		end

---------------------------------------------------Member Master Report---------------------------------------------------------------------------------------------------

---------------------------------------------------Consultant Master Report---------------------------------------------------------------------------------------------------

        else if(@status=2 and @chk=0)
		begin
		select MC.Consultant_Name,MC.Consultant_Code from Mst_Consultant MC inner join Mst_Member MM on MC.member_code=MM.Member_Code
		end

---------------------------------------------------Consultant Master Report---------------------------------------------------------------------------------------------------


---------------------------------------------------industry Master Report---------------------------------------------------------------------------------------------------
	
		else if(@status=3 and @chk=0)
		begin
		select Industry_Name as 'Industry Name',Industry_Code as 'Industry Code' from Mst_Industry
		end

		else if(@status=3 and @chk=1)
		begin
		select MI.Industry_Name as 'Industry Name',MI.Industry_Code as 'Industry Code',MS.Script_Name as 'Script Name' from Mst_Industry MI left outer join Mst_Script MS on MI.Industry_Code=MS.Industry_Code
		end

---------------------------------------------------industry Master Report---------------------------------------------------------------------------------------------------


---------------------------------------------------Script/Mutual Fund Master Report---------------------------------------------------------------------------------------------------		
  
       else if(@status=4 and @chk=0)
	   begin
	   select MS.Script_Code as 'Script Code',MS.Script_Name as 'Script Name',MS.BSE_Code as 'BSE Code',MS.NSE_Code as 'NSE Code',MS.Script_Group as 'Group',
       MS.ISIN_No as 'ISIN No.' , MI.Industry_Name as 'Industry Name' from Mst_Script MS left outer join Mst_Industry MI on MS.Industry_Code=MI.Industry_Code
	   end


---------------------------------------------------Script/Mutual Fund Master Report---------------------------------------------------------------------------------------------------


---------------------------------------------------Narration Master Report---------------------------------------------------------------------------------------------------
   
       else if(@status=5 and @chk=0)
	   begin
	   select Narration_Name as 'Narration Name' , Narration_Code as 'Narration Code' from Mst_Narration
	   end

---------------------------------------------------Narration Master Report---------------------------------------------------------------------------------------------------


---------------------------------------------------investment Master Report---------------------------------------------------------------------------------------------------
  
       else if(@status=6 and @chk=0)
	   begin
	   select distinct Investment_Name as 'Investment Name' , Investment_Code as 'Investment Code' from Mst_Investment 
	   end


---------------------------------------------------Narration Master Report---------------------------------------------------------------------------------------------------


---------------------------------------------------Group Master Report---------------------------------------------------------------------------------------------------
   
       else if(@status=7 and @chk=0)
	   begin
	   select  GRP_NAME as 'Group Name' , hname as 'Under Group' from Mst_AcGroup 
	   end


---------------------------------------------------Group Master Report---------------------------------------------------------------------------------------------------


END 























GO
/****** Object:  StoredProcedure [dbo].[proc_Script_Ledger]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Script_Ledger]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Script_Ledger] AS' 
END
GO


 --Select * from brokerbill_trans where isFNOBill = 1
 -- EXECUTE [dbo].[proc_Script_Ledger]  0,'0','J0001','1120172018','04-01-2017','03-31-2018','Y0008'
ALTER  PROCEDURE [dbo].[proc_Script_Ledger] 
(
	@Investmenttype  INT,
	@Ac_Type NVARCHAR(100), 
	@memcode VARCHAR(100), 
	@yearcode VARCHAR(100),
	@Fromdate datetime,
	@Todate datetime, 
	@ScriptCode VARCHAR(max),
	@Script_Name  VARCHAR(max) = '',
	@IsBSEISIN bit=0

)
AS 

BEGIN
SET NOCOUNT ON;
	CREATE TABLE #SCriptCodes
	(
		ScriptCode varchar(MAX)
	)

	If (@InvestmentType = 0 OR  @InvestmentType = 2)
		BEGIN
			IF(@ScriptCode != '')
				INSERT INTO #SCriptCodes SELECT value FROM Fn_split(@ScriptCode, ',') 
			ELSE 
				INSERT INTO #SCriptCodes select Script_Code from mst_script 
		END
	ELSE 
		BEGIN
				IF(@Script_Name  != '')
					INSERT INTO #SCriptCodes SELECT value FROM Fn_split(@Script_Name , ',') 
				ELSE 
					BEGIN
						INSERT INTO #SCriptCodes 
						Select distinct (Ms.script_name 
								+ '/' + CONVERT(VARCHAR(10),t.Last_Date,103) 
								+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
								+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' END) 
						from brokerbill_Trans t
						Left Join mst_Script ms on ms.script_Code = t.script_Code 
					END
		END

		CREATE TABLE #alldataledger 
        ( 
           Date DateTime,
		   Transaction_Type VARCHAR(100),
		   Script_Code VARCHAR(max),
		   Qty decimal(18,4),
		   Consultant_code VARCHAR(max),
		   script_name  VARCHAR(max),
		   Credit decimal(18,4),
		   Debit decimal(18,4),
           Flag_Type VARCHAR(100),
		   Consultant_Name  varchar(max)
        ) 

	 If (@InvestmentType = 0 OR  @InvestmentType = 2)
		BEGIN	
			INSERT INTO #alldataledger
			SELECT  t.Trans_Dt as 'Date',
			CASE WHEN t.Bill_no = 'Opening' THEN 'Opening' 
				 WHEN TransType='Sold' THEN 'Sold' 
				 ELSE  'Bought'
			END AS 'Transaction_Type',
			t.Script_Code,
			t.Qty as 'Quantity',
			t.Consultant_code,
			CASE WHEN  @InvestmentType = 0 OR  @InvestmentType = 2 
				 THEN  Ms.script_name 
				 ELSE 
				 	Ms.script_name 
							+ '/' + CONVERT(VARCHAR(10),t.Last_Date,103) 
							+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
							+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' 
							  END END script_name,
			CASE WHEN t.TransType = 'Sold' THEN ROUND(Amount,4) END as 'Credit',
			CASE WHEN t.TransType != 'Sold' THEN  ROUND(Amount,4) END as 'Debit',
			CASE 
			  	 WHEN TransType='Bought' AND Bill_no = 'Bonus' THEN 'Bonus' 
				 WHEN TransType='Bought' AND Bill_no ='Rights'THEN 'Rights' 
				 WHEN TransType='Bought' AND  t.Bill_no ='Split' THEN 'Split' 
				 WHEN TransType='Bought' AND Frmnm = 'IPO' THEN 'IPO'
				 ELSE ''  
			END AS 'Flag_Type',
			cm.Consultant_Name
			FROM brokerbill_trans t 
			LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
			LEFT JOIN mst_account ma ON t.ac_type = ma.ac_code AND ma.member_code = @memcode
			LEFT JOIN Mst_Consultant cm ON t.Consultant_code = cm.Consultant_code  
			WHERE  isfnobill = @Investmenttype 
					AND trans_dt <= @Todate 
					AND t.member_code = @memcode 
					AND yearcode = @yearcode 
					AND  MergedEntry !=1	 
					AND Ac_Type =(CASE WHEN  @Ac_Type='0' THEN Ac_Type  ELSE  @Ac_Type END)
					AND t.Script_Code IN (SELECT * FROM #SCriptCodes)
					Group By T.Sr_No,t.Trans_Dt,t.script_code,t.Bill_no,TransType,t.Consultant_code,t.Qty,t.Frmnm,
					cm.Consultant_Name,ma.member_code,Ac_Type,t.TransType,Ms.script_name,t.OptionType,Amount,t.Last_Date,t.Strike_Price,isFNOBill 
		END
	 ELSE 
		BEGIN	
			INSERT INTO #alldataledger
			SELECT  t.Trans_Dt as 'Date',
			CASE WHEN t.Bill_no = 'Opening' THEN 'Opening' 
				 WHEN TransType='Sold' THEN 'Sold' 
				 ELSE  'Bought'
			END AS 'Transaction_Type',
			t.Script_Code,
			t.Qty as 'Quantity',
			t.Consultant_code,
			CASE WHEN  @InvestmentType = 0 OR  @InvestmentType = 2 
				 THEN  Ms.script_name 
				 ELSE 
				 	Ms.script_name 
							+ '/' + CONVERT(VARCHAR(10),t.Last_Date,103) 
							+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
							+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' 
							  END END script_name,
			CASE WHEN t.TransType = 'Sold' THEN ROUND(Amount,4) END as 'Credit',
			CASE WHEN t.TransType != 'Sold' THEN  ROUND(Amount,4) END as 'Debit',
			CASE 
			  	 WHEN TransType='Bought' AND Bill_no = 'Bonus' THEN 'Bonus' 
				 WHEN TransType='Bought' AND Bill_no ='Rights'THEN 'Rights' 
				 WHEN TransType='Bought' AND  t.Bill_no ='Split' THEN 'Split' 
				 WHEN TransType='Bought' AND Frmnm = 'IPO' THEN 'IPO'
				 ELSE ''  
			END AS 'Flag_Type',
			cm.Consultant_Name
			FROM brokerbill_trans t 
			LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
			LEFT JOIN mst_account ma ON t.ac_type = ma.ac_code AND ma.member_code = @memcode
			LEFT JOIN Mst_Consultant cm ON t.Consultant_code = cm.Consultant_code  
			WHERE  isfnobill = @Investmenttype 
					AND trans_dt <= @Todate 
					AND t.member_code = @memcode 
					AND yearcode = @yearcode 
					AND  MergedEntry !=1	 
					AND Ac_Type =(CASE WHEN  @Ac_Type='0' THEN Ac_Type  ELSE  @Ac_Type END)
					AND 
					 ( Ms.script_name 
						+ '/' + CONVERT(varchar(20),t.Last_Date,103) 
						+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
						+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' 
						END ) IN (SELECT * FROM #SCriptCodes)
					Group By T.Sr_No,t.Trans_Dt,t.script_code,t.Bill_no,TransType,t.Consultant_code,t.Qty,t.Frmnm,
					cm.Consultant_Name,ma.member_code,Ac_Type,t.TransType,Ms.script_name,t.OptionType,Amount,t.Last_Date,t.Strike_Price,isFNOBill 
		END

			


---  Get Closing value

--Select * from #alldataledger

CREATE TABLE #mainoutputtable_1_Final_ledger 
        ( 
           id INT,
		   prioritys INT,
		   opening_bill_no VARCHAR(100),
		   script_code varchar(10),
		   AC_TYPE VARCHAR(100),
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200),
           opening_date VARCHAR(50),
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date VARCHAR(50),
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date VARCHAR(50),
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain FLOAT DEFAULT 0,
		   loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   sort   VARCHAR(5)
        ) 

	
		if(@Investmenttype = 0 OR @Investmenttype = 2)
			BEGIN
				Insert into #mainoutputtable_1_Final_ledger
				EXEC proc_Stockholdingposition_Equity   0, @Investmenttype ,@Ac_Type,@memcode,@yearcode,@Fromdate,@Todate,@ScriptCode,'','','','0','0','ScriptWiseTotal',0,0,0,0,@IsBSEISIN
			END

		ELSE 
			BEGIN
				Insert into #mainoutputtable_1_Final_ledger
				EXEC proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency   0, @Investmenttype ,'0',@memcode,@yearcode,@Fromdate,@Todate,@ScriptCode,'','','','0','0','ScriptWiseTotal',0,@Script_Name 
			END

			--EXEC proc_Stockholdingposition_Equity   0, 0,'110027','A0001','1120172018','02/01/2015','01/04/2018','','','','','0','0','ScriptWiseTotal'
			--EXEC proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency   0,1,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','ScriptWiseTotal'

     IF(@IsBSEISIN = 1)
		  BEGIN
		  Select #alldataledger.Date,#alldataledger.Transaction_Type ,#alldataledger.Script_Code ,#alldataledger.Qty, 
		  #alldataledger.Consultant_code ,#alldataledger.script_name + '[' +ms.BSE_Code + ']' + '[' +ms.ISIN_No+ ']' As 'script_name',#alldataledger.Credit ,#alldataledger.Debit,#alldataledger.Flag_Type, 
		  #alldataledger.Consultant_Name     
		  from #alldataledger 
		  INNER JOIN Mst_Script Ms On  #alldataledger.Script_Code=Ms.Script_Code
		  order by Script_Name,1
		  Select * from  #mainoutputtable_1_Final_ledger ORDER BY  3
		  END
	  
	  ELSE IF(@IsBSEISIN = 0)
		  BEGIN
		  Select  * from #alldataledger  order by Script_Name,1
		  Select * from  #mainoutputtable_1_Final_ledger ORDER BY  3
	  END

	Drop TABLE #alldataledger
	Drop TABLE #mainoutputtable_1_Final_ledger

END






















GO
/****** Object:  StoredProcedure [dbo].[proc_StockFilter_Equity]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockFilter_Equity]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_StockFilter_Equity] AS' 
END
GO

-- exec [proc_StockFilter_Equity]  0,0,0,'A0001','1120172018','2017-04-03 12:00:00:00','2018-12-18 03:50:37:50','','', 0,0,'Details','',''
ALTER PROCEDURE [dbo].[proc_StockFilter_Equity] 
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(MAX),@ConsultantCode  VARCHAR(MAX), @IsIntraDay VARCHAR(MAX),@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX),
@FamilyCode VARCHAR(MAX),@BSE_NSE_Code VARCHAR(50),@IsBSEISIN bit=0)
AS 
  BEGIN  
  SET NOCOUNT ON; 
		DECLARE @StartYearDate varchar(20) = '01/04/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101)

		CREATE TABLE #mainoutputtable_1
        ( 
		   Dup_pkid int,
		   pkid INT identity(1,1), 
           Family_Name VARCHAR(20),
		   Member_Name VARCHAR(20),
		   Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT,
		   Trans_Type  VARCHAR(50), 
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(10),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name  VARCHAR(500),
		   flag_holding_type VARCHAR(200), 
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(10),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount AS( [opening_qty] * [opening_rate] ), 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount AS( purchase_qty * purchase_rate ), 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount AS ( sold_qty * sold_rate ), 
		   gain_loss float,
           
		   closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 

           closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
		   closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
		   short_term FLOAT DEFAULT 0,
		   long_term  FLOAT DEFAULT 0,
           speculation  FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(20) ,
		   ScriptCode VARCHAR(50)
        ) 
		
		CREATE TABLE #mainouttable_1_BSEISINNO
		(
		   Dup_pkid int,
		   pkid INT, 
           Family_Name VARCHAR(20),
		   Member_Name VARCHAR(20),
		   Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT,
		   Trans_Type  VARCHAR(50), 
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(10),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name  VARCHAR(500),
		   flag_holding_type VARCHAR(200), 
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(10),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0,
		   purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0,
		   sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0,
		   gain_loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0,
		   closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term  FLOAT DEFAULT 0,
           speculation  FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(20) ,
		   ScriptCode VARCHAR(50)
		) 

		CREATE TABLE #mainoutputtable_1_Final
        ( 
		   Dup_pkid int,
		   OrderBy varchar(100),
           Family_Name VARCHAR(20),
		   Member_Name VARCHAR(20),
		   Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT   ,
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(10),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name  VARCHAR(500),
		   flag_holding_type VARCHAR(200), 
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(10),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(20),
		   sort   VARCHAR(5),
		   ScriptCode VARCHAR(50)
        ) 
		 
		CREATE TABLE #Members
		(
			Member_Code varchar(MAX)
		)
			
		CREATE TABLE #Family
		(
			Family_Code varchar(MAX)
		)

		DECLARE @tmp VARCHAR(MAX)
				
		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty INT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT  
		DECLARE @tablerowscount INT
      IF(@status = 0) 
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
				@openingDate DATETIME,@openingRate FLOAT,@openingQty INT,@openingAmount FLOAT,
				@purchaseDate DATETIME,@PurchaseBillNo  VARCHAR(50),@purchaseRate FLOAT,@purchaseQty INT,@purchaseAmount FLOAT,
				@soldDate DATETIME,@soldBillNo  VARCHAR(50),@soldRate FLOAT,@soldQty INT,@soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50),@Consultant_Name  VARCHAR(100), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(10),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,@PurchaseIntraFlag VARCHAR(100),@SaleIntraFlag VARCHAR(10) 
				DECLARE @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@ScriptId VARCHAR(50),@Dup_pkid int, @Pkid int,@idcount int 
				
				---- For Getting SCriptCodes
				CREATE TABLE #SCriptCodes
				(
					ScriptCode varchar(MAX)
				)

				IF(@ScriptCode != '')
					INSERT INTO #SCriptCodes SELECT value FROM Fn_split(@ScriptCode, ',') 
				ELSE 
					INSERT INTO #SCriptCodes select Script_Code from mst_script 
				---- Getting SCriptCodes END			
				---- For Getting Consultant Code
				
				CREATE TABLE #ConsultantCodes
				(
					ConsultantCodes varchar(MAX)
				)

				IF(@ConsultantCode = '0')	
					BEGIN
							SELECT DISTINCT p.member_code,p.year_code,
								STUFF((	SELECT distinct ',' + p1.Consultant_Code
										FROM Mst_Consultant p1
										--WHERE p.member_code = p1.member_code AND p.year_code = p1.year_code
										FOR XML PATH(''), TYPE
									  ).value('.', 'NVARCHAR(MAX)')
								,1,1,'') ConsultantCode
							into #temoConsultant
							FROM Mst_Consultant p

							SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant)-- WHERE member_code = @memcode AND year_code = @yearcode)
							DROP table #temoConsultant
						--	Select @ConsultantCode
					END
				 
				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes SELECT Consultant_Code from Mst_Consultant

				IF(@memcode = '' AND @familycode != '')
					BEGIN
						INSERT INTO #Members
						SELECT Member_Code 
						FROM Mst_Member WHERE Family_Code IN (SELECT Value FROM membercodestable(@familycode,','))
						SET @tmp = ''
						SELECT @tmp = @tmp + Member_Code + ',' FROM #Members
						SET @memcode = 	IsNULL((select SUBSTRING(@tmp, 0, LEN(@tmp))),'')
					END
				
				IF(@memcode != '' AND @familycode = '')
					BEGIN
						INSERT INTO #Family
						SELECT Family_Code 
						FROM Mst_Member WHERE Member_Code IN (SELECT Value FROM membercodestable(@memcode,','))
						SET @tmp = ''
						SELECT @tmp = @tmp + Family_Code + ',' FROM #Family
						SET @familycode = 	IsNULL((SELECT SUBSTRING(@tmp, 0, LEN(@tmp))),'')
					END
				
				SELECT	ROW_NUMBER ( ) OVER (ORDER BY t.script_code,t.Ac_Type,t.trans_dt ) AS NameId,t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,
						t.TransType,t.Ac_Type,t.Script_Code,t.Last_Date,t.Qty,t.Rate,
						t.Member_code,t.YearCode,t.Consultant_code,t.isFNOBill,t.isIntraDay,t.Exp_Rate,t.FrmNm,t.ID,
						Ms.bse_code,Ms.nse_code,Ms.script_name,ma.ac_name AS 'Holding Type',
							CASE	WHEN t.Bill_no = 'Opening' AND t.Frmnm != 'BB' THEN 'Opening' 
								WHEN t.TransType='Bought' AND  t.Bill_no <> 'Opening'  THEN 'Bought' 
								WHEN TransType='Bought' AND t.Bill_no = 'Bonus' THEN 'Bonus' 
								WHEN TransType='Bought' AND t.Bill_no ='Rights'THEN 'Rights' 
								WHEN TransType='Bought' AND  t.Bill_no ='Split' THEN 'Split' 
								WHEN TransType='Bought' AND  t.Bill_no ='Transfer' THEN 'Transfer' 
								WHEN TransType='Sold' THEN 'Sold' 
								WHEN TransType='Bought' AND Frmnm = 'IPO' THEN 'IPO'  
						END AS 'Flag_Type',
						cm.Consultant_Name,mm.Member_Name,MF.Family_Name
						INTO #alldata 
				FROM brokerbill_trans t 
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN mst_account ma ON t.ac_type = ma.ac_code AND ma.member_code =t .member_code
				--LEFT JOIN (SELECT * FROM Mst_Consultant WHERE member_code    IN (SELECT value FROM Fn_split(@memcode, ',') ) AND year_code = @yearcode)  cm ON t.Consultant_code = cm.Consultant_code  
				LEFT JOIN  Mst_Consultant  cm ON t.Consultant_code = cm.Consultant_code  
				LEFT JOIN Mst_Member MM ON mm.Member_Code=t.Member_code
				LEFT JOIN Mst_Family MF ON MF.Family_Code =MM.Family_Code
				
				WHERE  ISNULL(isfnobill,0) = @Investmenttype 
				AND trans_dt <= @Todate 
				AND t.member_code IN (SELECT value FROM Fn_split(@memcode, ',') )
				AND yearcode = @yearcode  
				AND Ac_Type =(CASE WHEN  @Ac_Type='0' THEN Ac_Type  ELSE  @Ac_Type END)
				AND t.script_code IN (SELECT * FROM #SCriptCodes)
				AND	t.Consultant_code IN (SELECT * FROM #ConsultantCodes)
				AND	t.Member_Code IN (SELECT value FROM Fn_split(@memcode, ',') )
				AND	MF.Family_Code IN (SELECT value FROM Fn_split(@FamilyCode, ',') )
				AND t.isIntraDay =(CASE WHEN @IsIntraDay=0 THEN  isIntraDay ELSE @IsIntraDay END) 
				AND t.MergedEntry = 0  AND ISNULL( t.Ref_SrNo,0) != 1
				GROUP BY ID,Trans_No,Sr_No,Ac_Type,ma.AC_Name,t.Script_Code,script_name, t.Consultant_code,cm.Consultant_Name,mm.Member_Name,MF.Family_Name,Bill_no,
				Trans_Dt,TransType,Last_Date ,Qty,Rate,Amount,t.Member_Code,YearCode,Ref_TransNo,MergedEntry,isFNOBill,isIntraDay,Exp_Rate,FrmNm,bse_code,nse_code
				ORDER  BY NameId
				DECLARE @isIntradayCol INT ,@Family_Name VARCHAR(20),@Member_Name VARCHAR(20) 
				
				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT id,Trans_No,script_name,Script_Code, Family_Name,Member_Name,[holding type],bill_no,CONVERT(DATETIME,trans_dt,103),qty,rate,ISNULL(qty, 0) * ISNULL(rate, 0),ISNULL(isintraday, 0),consultant_name   
				FROM #alldata
				WHERE #alldata.bill_no IN('Split','Opening') OR  CONVERT(date,trans_dt,101)  < CONVERT(date ,@StartYearDate,101)

				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId ,@Family_Name,@Member_Name,@holding_type, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
						-- Insert All Openings
						SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
						SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
						SET @Dup_pkid = ISNULL(@Dup_pkid,0)
						SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
						SET @Dup_pkid = @Dup_pkid + 1

						DECLARE @IDs INT=0
						DECLARE @Flag_Types VARCHAR(10)
						SET @Flag_Types = (SELECT CASE WHEN @billno = 'Opening' THEN 'Opening' ELSE 'Bought' END)
						IF(@Flag_Types='Opening'  OR (@billno IN('Split') AND CONVERT(date,@dates,101)  < CONVERT(date ,@StartYearDate,101)))
							BEGIN	
								INSERT INTO #mainoutputtable_1   (Dup_pkid, opening_bill_no ,id,ScriptCode ,Family_Name,Member_Name,  Trans_No,  Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,consultant_name) 
								SELECT @Dup_pkid,@billno ,@IDs,@ScriptId ,@Family_Name,@Member_Name,  @Trans_No, @Flag_Types,@scriptname,@holding_type,@dates,@qty,@rate,@isintradaycol ,@Consultant_Name
								
								IF(@idcount>0)
									BEGIN
										UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and ScriptCode<>@ScriptId
									END
							END
						 
			 			FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId ,@Family_Name,@Member_Name,@holding_type, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name
					END 

				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 
				
				DECLARE @salecount INT=0,@Boughtcount INT=0,@Flag_Type VARCHAR(20)
				DECLARE  @COUNT INT = 0


				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
				SELECT id,Family_Name,Member_Name, Bill_no,Flag_Type,TransType,Script_Code ,script_name,[holding type],Trans_No,CONVERT(DATETIME, trans_dt,103), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name
				FROM #alldata WHERE 
				--#alldata.bill_no NOT IN( 'Opening','Split') 
				(TransType in('Bought','Sold')  AND CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Family_Name,@Member_Name,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
				
				WHILE (@@FETCH_STATUS = 0) 
						BEGIN
						IF(@Investmenttype=2)
							SET @holding_type = 'Mutual Fund'
							
							SET @COUNT = 0
							DECLARE @IsOpening INT =0
							DECLARE @prioritysId INT=0
							DECLARE @str VARCHAR(MAX)=''	
							DECLARE @purchase_Op_Qty FLOAT =0
							DECLARE @purchase_Op_Bill VARCHAR(20)=''
							DECLARE @purchase_Op_Date datetime=''
							DECLARE @purchase_Op_Rate FLOAT=0
							DECLARE	@PurQTY FLOAT=0
							DECLARE	@BalPurQTY FLOAT=0
							DECLARE @BalSoldQTY FLOAT=0
							DECLARE @Balpurchase_Op_Qty FLOAT=0
							DECLARE @BalOpeningQTY FLOAT=0
							DECLARE	@Sold_Qty FLOAT=0
							DECLARE @tempID int = 0
							
							IF(@isIntradayCol=0)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold ='Sold'  and Flag_Type ='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=0 AND Consultant_Name=(CASE WHEN @ConsultantCode <> '' THEN  @Consultant_Name ELSE consultant_name END) AND Family_Name=(CASE WHEN @FamilyCode<>'' THEN @Family_Name ELSE Family_Name END) AND Member_Name=(CASE WHEN @memcode <> '' THEN @Member_Name ELSE Member_Name END))
											IF (@COUNT > 0)
												BEGIN
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode,holding_type, case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* INTO #tempSoldValExists 
													FROM
													#MainOutputtable_1 
													WHERE script_name=@scriptname AND holding_type=@holding_type  AND isintradaycol=0 AND consultant_name=@Consultant_Name
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold ='Sold'  and  Flag_Type ='Sold' AND isintradaycol=0
													DECLARE @R_Sold_COUNT INT=(SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty INT 
													SET @purchase_Op_Qty=@qty
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists  ORDER BY Dup_pkid)
															SET @str=@TransType
															SET @Temppurchase_Op_Qty=(SELECT TOP(1) sold_qty  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @soldDate=(SELECT TOP (1) sold_date  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @soldRate=(SELECT TOP (1) sold_rate  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @soldBillNo=(SELECT TOP (1) sold_bill_no  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @Sold_Qty= @purchase_Op_Qty
															IF(@TransType='Opening')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	
																	opening_date=@dates,
																	opening_rate=@rate,
																	opening_qty= CASE WHEN @Temppurchase_Op_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Temppurchase_Op_Qty END,
																	Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND pkid = @pkid
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	
																	purchase_date=@dates,
																	purchase_bill_no=@billno,
																	purchase_rate=@rate,
																	purchase_qty= CASE WHEN @Temppurchase_Op_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Temppurchase_Op_Qty END,
																	Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND pkid = @pkid
																END
															

															IF(@Temppurchase_Op_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  SET sold_qty=@purchase_Op_Qty WHERE Flag_Type_Sold='Sold' AND   id = @tempSaleID  AND pkid = @pkid
																END

															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND pkid = @pkid
															SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempSoldValExists )
															DECLARE @Balancedval   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Temppurchase_Op_Qty)

															IF(@Balancedval  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty=ABS(@Balancedval) 
																	SET @prioritysId  =(SELECT MAX(ISNULL(@prioritysId,0)+1) FROM #MainOutputtable_1) 
																 
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode ,Family_Name,Member_Name, Trans_No, Flag_Type,Flag_Type_Sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name)
																	VALUES(@Dup_pkid,@tempSaleID ,@ScriptId ,@Family_Name,@Member_Name,@Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name)
																	
																	UPDATE #MainOutputtable_1 SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and ScriptCode<>@ScriptId
																		END
																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
															
																	IF(@TransType='Opening')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode ,Family_Name,Member_Name,Trans_No, Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@ScriptId ,@Family_Name,@Member_Name,@Trans_No, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name)
																		END
																	ELSE if(@TransType='Bought')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode ,Family_Name,Member_Name,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@ScriptId ,@Family_Name,@Member_Name,@Trans_No, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name)
																		END
																	IF(@idcount > 0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and ScriptCode<>@ScriptId
																		END
																ENd
															
															SET @qty=@Balancedval
														END
													

													DROP TABLE #tempSoldValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(SELECT MAX(Dup_pkid+1) FROM #mainoutputtable_1)
													INSERT INTO #mainoutputtable_1 (Dup_pkid,id,ScriptCode ,Family_Name,Member_Name,Trans_No, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name) 
													VALUES (@Dup_pkid,@ID,@ScriptId ,@Family_Name,@Member_Name,@Trans_No, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name) 
												END
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */

											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening') AND ISNULL(sold_qty,0)=0  AND isintradaycol=0  AND Consultant_Name=(CASE WHEN @ConsultantCode <> '' THEN  @Consultant_Name ELSE consultant_name END) AND Family_Name=(CASE WHEN @FamilyCode <> '' THEN @Family_Name ELSE Family_Name END) AND Member_Name=(CASE WHEN @memcode <> '' THEN @Member_Name ELSE Member_Name END))
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode,holding_type,  CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,
													* INTO #tempValExists 
													FROM
													#MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Transfer') 
													AND consultant_name= @Consultant_Name AND ISNULL(sold_qty,0)=0  AND isintradaycol=0 

													
													DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty int 
													SET @Sold_Qty= @qty
													
													WHILE(@RCOUNT > 0)
														BEGIN 
															SET @tempID = (Select top(1) id from #tempValExists ORDER BY pkid)
															SET @str = (Select top(1) Flag_Type From #tempValExists Where id  = @tempID)
														
															IF(@str='Opening')
																BEGIN
																	SET @TempSoldQty=(SELECT TOP(1) opening_qty  FROM #tempValExists WHERE id  = @tempID)
																	SET @openingDate=(SELECT TOP(1) opening_date FROM #tempValExists WHERE id  = @tempID)
																	SET @openingrate=(SELECT TOP(1) opening_rate FROM #tempValExists WHERE id  = @tempID)
																	SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempValExists WHERE id  = @tempID )
																END
															ELSE IF(@str='Bought')
																BEGIN
																	SET @TempSoldQty=(SELECT TOP(1) purchase_qty FROM #tempValExists WHERE id  = @tempID)
																	SET @PurchaseDate=(SELECT TOP(1) purchase_date FROM #tempValExists WHERE id  = @tempID)
																	SET @Purchaserate=(SELECT TOP(1) purchase_rate FROM #tempValExists WHERE id  = @tempID)
																	SET @PurchaseBillNo=(SELECT TOP(1) purchase_bill_no FROM #tempValExists WHERE id  = @tempID)
																	SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempValExists WHERE id  = @tempID )
																END
															    
															IF(@Sold_Qty > 0)
																BEGIN
																	UPDATE #MainOutputtable_1  
																		SET	
																			opening_qty = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							END,
																			purchase_qty  = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							END,
																			sold_date=@dates,
																			sold_bill_no=@billno,
																			sold_rate=@rate,
																			sold_qty= CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold='Sold'
																	WHERE  id = @tempID and ISNULL(sold_qty,0)=0  AND pkid = @pkid
																	SET @Balanceval = ABS(@Sold_Qty) - ABS(@TempSoldQty)
																END
															
															DELETE FROM #tempValExists WHERE id = @tempID AND pkid = @pkid
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempValExists )
															SET @RCOUNT = @RCOUNT - 1
															SET @qty = @Balanceval
															SET @Sold_Qty = @qty
													 
															IF(@Balanceval  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  =(SELECT MAX(ISNULL(@prioritysId,0)+1) FROM #MainOutputtable_1)

																	IF(@str='Opening')
																		BEGIN
																			SET @openingQty=ABS(@Balanceval) 
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode ,Family_Name,Member_Name,Trans_No,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@tempID,@ScriptId ,@Family_Name,@Member_Name,@Trans_No, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name)
																			UPDATE #MainOutputtable_1 SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempID
																		END
																	ELSE 
																		BEGIN
																			SET @PurchaseQty=ABS(@Sold_Qty) 
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode ,Family_Name,Member_Name,Trans_No,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@tempID,@ScriptId ,@Family_Name,@Member_Name,@Trans_No, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name)
																			UPDATE #MainOutputtable_1 SET prioritys=@prioritysId  WHERE prioritys > @prioritysId AND ID<>@tempID
																		END
															
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and ScriptCode<>@ScriptId
																		END
																	BREAK;

																END
															ELSE IF (@Balanceval  > 0 AND @tablerowscount=0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode ,Family_Name,Member_Name,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name)
															
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and ScriptCode<>@ScriptId
																		END
																ENd
														END
													DROP TABLE #tempValExists
											END
											
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
													INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode ,Family_Name,Member_Name,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
													VALUES(@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Trans_No,  'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name)
												END
											SET @purchase_Op_Date=''
											SET @purchase_Op_Rate=''
											SET @purchase_Op_Qty=''
											SET @purchase_Op_Bill=''
										END
								END
							ELSE IF(@isIntradayCol=1)
								 BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold ='Sold'   and Flag_Type ='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=1  AND Consultant_Name=(CASE WHEN @ConsultantCode <> '' THEN  @Consultant_Name ELSE consultant_name END) AND Family_Name=(CASE WHEN @FamilyCode<>'' THEN @Family_Name ELSE Family_Name END) AND Member_Name=(CASE WHEN @memcode <> '' THEN @Member_Name ELSE Member_Name END))
											IF (@COUNT > 0)
												BEGIN
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, holding_type,case when opening_date <> NULL then opening_date ELSE purchase_date END  ) AS NameId,
													* INTO #tempSoldValExists_intra_Bought 
													FROM #MainOutputtable_1 
													WHERE script_name=@scriptname AND holding_type=@holding_type  AND isintradaycol=1
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold IN('Sold')  and Flag_Type ='Sold'   AND consultant_name=@Consultant_Name
													
													DECLARE @R_Sold_COUNT_intra INT=(SELECT COUNT(*) FROM #tempSoldValExists_intra_Bought )
													DECLARE @Temppurchase_Op_Qty_intra int 
													SET @purchase_Op_Qty=@qty
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID_intra int = (Select top(1) id from #tempSoldValExists_intra_Bought ORDER BY Dup_pkid)
															 
															SET @str=@TransType
															SET @Temppurchase_Op_Qty_intra=(SELECT TOP(1) sold_qty  FROM #tempSoldValExists_intra_Bought WHERE id  = @tempSaleID_intra )
															SET @soldDate=(SELECT TOP(1) sold_date  FROM #tempSoldValExists_intra_Bought WHERE id  = @tempSaleID_intra )
															SET @soldRate=(SELECT TOP(1) sold_rate  FROM #tempSoldValExists_intra_Bought WHERE id  = @tempSaleID_intra )
															SET @soldBillNo=(SELECT TOP(1) sold_bill_no  FROM #tempSoldValExists_intra_Bought WHERE id  = @tempSaleID_intra )
															SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempSoldValExists WHERE id  = @tempSaleID_intra )
															SET @Sold_Qty= @purchase_Op_Qty
																IF(@TransType='Bought')
																	BEGIN
																		UPDATE #MainOutputtable_1  
																		SET	
																		purchase_date=@dates,
																		purchase_bill_no=@billno,
																		purchase_rate=@rate,
																		purchase_qty= CASE WHEN @Temppurchase_Op_Qty_intra > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Temppurchase_Op_Qty_intra END,
																		Flag_Type='Bought'
																		WHERE  id = @tempSaleID_intra  AND Pkid = @Pkid
																	END
																ELSE
																	BEGIN
																		UPDATE #MainOutputtable_1  
																		SET	
																		opening_date=@dates,
																		opening_rate=@rate,
																		opening_qty= CASE WHEN @Temppurchase_Op_Qty_intra > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Temppurchase_Op_Qty_intra END,
																		Flag_Type='Bought'
																		WHERE  id = @tempSaleID_intra  AND Pkid = @Pkid
																	END

															IF(@Temppurchase_Op_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  SET sold_qty=@purchase_Op_Qty WHERE Flag_Type_Sold='Sold' AND   id = @tempSaleID_intra  AND Pkid = @Pkid
																END
															DELETE FROM #tempSoldValExists_intra_Bought  WHERE id = @tempSaleID_intra  AND Pkid = @Pkid
															SET @R_Sold_COUNT_intra  = @R_Sold_COUNT_intra  - 1
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempSoldValExists_intra_Bought )
															DECLARE @Balancedval_intra   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Temppurchase_Op_Qty_intra)
												
															IF(@Balancedval_intra  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty=ABS(@Balancedval_intra  ) 
																	SET @prioritysId  =(SELECT MAX(ISNULL(@prioritysId,0)+1) FROM #MainOutputtable_1)-- WHERE id=@tempSaleID_intra )
																	 
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode ,Family_Name,Member_Name, Trans_No, Flag_Type, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@tempSaleID_intra ,@ScriptId, @Family_Name,@Member_Name,@Trans_No, 'Opening',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval_intra),@soldRate,@isIntradayCol,@Consultant_Name)
																	UPDATE #MainOutputtable_1 SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempSaleID_intra 
																	
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and ScriptCode<>@ScriptId
																		END
																	BREAK;
																END
															ELSE IF(@Balancedval_intra  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																	if(@TransType='Opening')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode ,Family_Name,Member_Name,Trans_No,  Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Trans_No, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval_intra),@rate,@isIntradayCol,@Consultant_Name)
																		END
																	ELSE if(@TransType='Bought')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode ,Family_Name,Member_Name,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Trans_No, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval_intra)  ,@rate,@isIntradayCol,@Consultant_Name)
																		END
																	
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and ScriptCode<>@ScriptId
																		END
																ENd
																
																SET @qty=@Balancedval_intra
															END
														--select @Sold_Qty
													

													DROP TABLE #tempSoldValExists_intra_Bought
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(SELECT MAX(Dup_pkid+1) FROM #mainoutputtable_1)
												 
													INSERT INTO #mainoutputtable_1 (Dup_pkid,id,ScriptCode ,Family_Name,Member_Name,Trans_No, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name) 
													VALUES (@Dup_pkid,@ID,@ScriptId ,@Family_Name,@Member_Name,@Trans_No, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name) 
												END
										END	

									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Enry Already if Purchase or Opening Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening') AND ISNULL(sold_qty,0)=0  AND isintradaycol=1 AND Consultant_Name=(CASE WHEN @ConsultantCode <> '' THEN  @Consultant_Name ELSE consultant_name END) AND Family_Name = (CASE WHEN @FamilyCode <> '' THEN @Family_Name ELSE Family_Name END) AND Member_Name = (CASE WHEN @memcode <> '' THEN @Member_Name ELSE Member_Name END))
											IF (@COUNT > 0)
												BEGIN
													SET @Sold_Qty=0
											
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode,holding_type,  case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* INTO #tempValExists_intraBought 
													FROM
													#MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening') AND Consultant_Name=@Consultant_Name
													AND ISNULL(sold_qty,0)=0  AND isintradaycol=1 
													DECLARE @RCOUNT_intraBought INT=(SELECT COUNT(*) FROM #tempValExists_intraBought)
													DECLARE @TempSoldQty_intra int 
													SET @Sold_Qty=@qty
													WHILE(@RCOUNT_intraBought > 0)
														BEGIN 
															DECLARE @tempID_intraBought int = (Select top(1) id from #tempValExists_intraBought where isintradaycol=1 ORDER BY Dup_pkid)
															SET @str = (Select top(1) Flag_Type From #tempValExists_intraBought Where id  = @tempID_intraBought)
															 
																SET @TempSoldQty_intra = (SELECT TOP(1) purchase_qty FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought)
																SET @PurchaseDate = (SELECT TOP(1) purchase_date FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought)
																SET @Purchaserate = (SELECT TOP(1) purchase_rate FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought)
																SET @PurchaseBillNo = (SELECT TOP(1) purchase_bill_no FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought)
																SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought )
																SET @Sold_Qty= @qty
																
																
																UPDATE #MainOutputtable_1  
																	SET	
																		sold_date=@dates,
																		sold_bill_no=@billno,
																		sold_rate=@rate,
																		sold_qty= CASE WHEN @TempSoldQty_intra > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty_intra END,
																		Flag_Type_Sold='Sold' 
																WHERE  id = @tempID_intraBought and isnull(sold_qty,0)=0
																IF(@TempSoldQty_intra > @Sold_Qty )
																	BEGIN
																		UPDATE #MainOutputtable_1  SET purchase_qty=@Sold_Qty WHERE Flag_Type='Bought' AND  id = @tempID_intraBought AND Pkid = @Pkid
																	END

															DELETE FROM #tempValExists_intraBought WHERE id = @tempID_intraBought AND Pkid = @Pkid
															SET @RCOUNT_intraBought = @RCOUNT_intraBought - 1
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempValExists_intraBought )
															declare @Balanceval_intraBought FLOAT = ABS(@Sold_Qty) - ABS(@TempSoldQty_intra)
															IF(@Balanceval_intraBought  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @PurchaseQty = ABS(@Sold_Qty) 
																	SET @prioritysId  = (SELECT MAX(ISNULL(@prioritysId,0)+1) FROM #MainOutputtable_1)-- WHERE id=@tempID_intraBought)
																	 
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode ,Family_Name,Member_Name,Trans_No,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@tempID_intraBought,@ScriptId ,@Family_Name,@Member_Name,@Trans_No, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval_intraBought)  ,@Purchaserate,@isIntradayCol,@Consultant_Name)
																	UPDATE #MainOutputtable_1 SET prioritys=@prioritysId  WHERE prioritys > @prioritysId AND ID<>@tempID_intraBought
																	
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and ScriptCode<>@ScriptId
																		END
																	BREAK;
																END
															
															ELSE IF(@Balanceval_intraBought  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @prioritysId  =(SELECT MAX(prioritys + 1) FROM #MainOutputtable_1)
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode ,Family_Name,Member_Name,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@ID,@ScriptId ,@Family_Name,@Member_Name,@Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval_intraBought)  ,@rate,@isIntradayCol,@Consultant_Name)
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and ScriptCode <> @ScriptId
																		END
																ENd
															
															SET @qty = @Balanceval_intraBought
														END
													DROP TABLE #tempValExists_intraBought
												END
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)

													INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode ,Family_Name,Member_Name,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
													VALUES(@Dup_pkid,@ID,@ScriptId ,@Family_Name,@Member_Name, @Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name)
												END
													SET @purchase_Op_Date=''
													SET @purchase_Op_Rate=''
													SET @purchase_Op_Qty=''
													SET @purchase_Op_Bill=''
										END
								END
							FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Family_Name,@Member_Name,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
						END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 
	 if(@IsBSEISIN=1)
		BEGIN
				INSERT INTO #mainouttable_1_BSEISINNO 				
				SELECT ma.Dup_pkid,ma.pkid,ma.Family_Name,ma.Member_Name,ma.Trans_No,ma.id,ma.prioritys,ma.Trans_Type, ma.Split_Type, ma.Flag_Type, ma.Flag_Type_Sold,ma.flag_script_name,
				ma.flag_holding_type,  
				ma.script_name + '[' +ms.BSE_Code + ']' + '[' +ms.ISIN_No+ ']',ma.holding_type,ma.opening_bill_no ,ma.opening_date ,ma.opening_qty,ma.opening_rate ,ma.opening_amount ,ma.purchase_date ,ma.purchase_bill_no ,
				ma.purchase_qty,ma.purchase_rate,ma.purchase_amount ,ma.sold_date ,ma.sold_bill_no ,ma.sold_qty,ma.sold_rate,ma.sold_amount ,ma.gain_loss ,ma.closing_qty,
				ma.closing_rate,ma.closing_value,ma.short_term ,ma.long_term ,ma.speculation ,ma.gain_speculation ,ma.loss_speculation ,ma.consultant_name ,ma.nse_rate ,ma.bse_rate, 
				ma.dayscount, ma.isintradaycol,ma.[type],ma.ScriptCode
				from #mainoutputtable_1 ma 
				INNER JOIN Mst_Script Ms On  ma.ScriptCode=Ms.Script_Code
		END
		ELSE if(@IsBSEISIN=0)
			BEGIN		   
				INSERT INTO #mainouttable_1_BSEISINNO 				
				SELECT ma.Dup_pkid,ma.pkid,ma.Family_Name,ma.Member_Name,ma.Trans_No,ma.id,ma.prioritys,ma.Trans_Type, ma.Split_Type, ma.Flag_Type, ma.Flag_Type_Sold,ma.flag_script_name,
				ma.flag_holding_type,ma.script_name,ma.holding_type,ma.opening_bill_no ,ma.opening_date ,ma.opening_qty,ma.opening_rate ,ma.opening_amount ,ma.purchase_date ,ma.purchase_bill_no ,
				ma.purchase_qty,ma.purchase_rate,ma.purchase_amount ,ma.sold_date ,ma.sold_bill_no ,ma.sold_qty,ma.sold_rate,ma.sold_amount ,ma.gain_loss ,ma.closing_qty,
				ma.closing_rate,ma.closing_value,ma.short_term ,ma.long_term ,ma.speculation ,ma.gain_speculation ,ma.loss_speculation ,ma.consultant_name ,ma.nse_rate ,ma.bse_rate, 
				ma.dayscount, ma.isintradaycol,ma.[type],ma.ScriptCode
				from #mainoutputtable_1 ma 		
		END

		IF(@IsIntraDay = 0 AND @short_Long_Term != 0  )
			BEGIN
				IF(@short_Long_Term = 1)  -- Long Term
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,ScriptCode ,Family_Name,Member_Name,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN   CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
							 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId, opening_bill_no,id,ScriptCode ,Family_Name,Member_Name,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4)
						as gain_loss,
						
						closing_qty ,closing_rate ,closing_value ,
						0,
						Round(ISNULL( CASE	WHEN isintradaycol = 0 and opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
											WHEN isintradaycol = 0 and purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4),
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort ,isintradaycol
						FROM #mainouttable_1_BSEISINNO 
						WHERE ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
									(
										DATEDIFF(DAY,CONVERT(DATETIME,opening_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) > 365 
									)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									(
										DATEDIFF(DAY,CONVERT(DATETIME, purchase_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) > 365
									)
								)
							)
						order by NameId
					END

				ELSE If(@short_Long_Term = 2)  
					BEGIN

						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,ScriptCode ,Family_Name,Member_Name,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,id,ScriptCode ,Family_Name,Member_Name,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4) as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						Round(ISNULL(
								CASE	WHEN  isintradaycol = 0 and opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN  isintradaycol = 0 and purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4),
						0,
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol 
						FROM #mainouttable_1_BSEISINNO 
						WHERE  ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
										(		
											DATEDIFF(DAY,CONVERT(DATETIME,opening_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) < 365 
										)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									  (		
										DATEDIFF(DAY,CONVERT(DATETIME, purchase_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) < 365
									  )
								)
							)
						order by NameId
					END

				ELSE If(@short_Long_Term = 4)  -- Short Term + Long Term
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,ScriptCode ,Family_Name,Member_Name,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,id,ScriptCode ,Family_Name,Member_Name,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) < 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) < 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						(CASE  WHEN isintradaycol = 0 and ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
								    (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
							  THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						(CASE WHEN isintradaycol = 0 and ( (ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365) OR
								   (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365))  
							  THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol 
						FROM #mainouttable_1_BSEISINNO 
						WHERE  ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						order by NameId
					END
			END

		ELSE If(@short_Long_Term = 3 AND @IsIntraDay = 1 )  -- Only Speculation
			BEGIN
				INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,ScriptCode ,Family_Name,Member_Name,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

				SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,id,ScriptCode ,Family_Name,Member_Name,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
				ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),purchase_date,ISNULL(purchase_bill_no,0),
				ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,sold_date ,sold_bill_no ,isnull(sold_qty,0) ,
				ISNULL(sold_rate,0),ISNULL(sold_amount,0) , 
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4) as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				0,
				0,
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4),
				gain_speculation,
				loss_speculation,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol 
				FROM #mainouttable_1_BSEISINNO 
				WHERE  (ISNULL(closing_qty,0) = 0)  AND (ISNULL(isintradaycol,0)=1) AND (ISNULL(purchase_qty,0)! = 0 AND  ISNULL(sold_qty,0) ! = 0) 
				order by NameId
			END

		ELSE
			BEGIN
				INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,  id,ScriptCode ,Family_Name,Member_Name,Trans_No, prioritys,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

				SELECT 
				ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,
				--ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,case when CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) else CONVERT(DATE,purchase_date,103) END,prioritys DESC, sold_date DESC ) AS NameId,
				id,ScriptCode ,Family_Name,Member_Name,Trans_No, prioritys,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,
			 
					    Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) < 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN  isintradaycol = 0 and ((opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365)) --short term for purchase
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				CASE WHEN  isintradaycol = 0 and ((opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365)) --short term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  isintradaycol = 1 and (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol 
				FROM #mainouttable_1_BSEISINNO 
				order by NameId
			END
	  			UPDATE #mainoutputtable_1_Final SET prioritys=0
				DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
				UPDATE #mainoutputtable_1_Final
				SET prioritys  = @i , @i = @i + 1
		IF(@OUTPUT_Flag='Details')
			BEGIN
				IF(@Investmenttype !=2)
					BEGIN
						UPDATE #mainoutputtable_1_Final SET prioritys=0
						DECLARE @ii INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
						UPDATE #mainoutputtable_1_Final
						SET prioritys  = @ii , @ii = @ii + 1

								 
						SELECT prioritys, ScriptCode ,script_name 'Script Name',Family_Name 'Family Name',Member_Name 'Member Name',consultant_name 'Consultant Name',
						CONVERT(VARCHAR(10), opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty', ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(VARCHAR(10), purchase_date,103) 'Purchase Date',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(VARCHAR(10), sold_date,103) 'Sold Date',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',ISNULL(short_term,0) AS 'Short Term',ISNULL(long_term,0) AS 'Long Term',ISNULL(speculation,0) AS speculation,
						CASE
							WHEN ISNULL(closing_qty,0) != 0 AND ISNULL(sold_date,'') != '' AND ((ISNULL(opening_date,'') = '') OR (ISNULL(purchase_date,'') = '')) THEN CONVERT(VARCHAR(10),  sold_date,103)
							WHEN ISNULL(closing_qty,0) != 0 AND ISNULL(opening_date,'') != '' AND (ISNULL(sold_date,'') = '') THEN CONVERT(VARCHAR(10), opening_date,103)
							WHEN ISNULL(closing_qty,0) != 0 AND ISNULL(purchase_date,'') != ''  AND (ISNULL(sold_date,'') = '') THEN CONVERT(VARCHAR(10),  purchase_date,103)
						END 
							AS  'Closing Date',
						ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',1 sort 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  

						ORDER BY holding_type,script_name
					 END
				ELSE
					BEGIN
						SELECT  ScriptCode ,script_name 'Script Name',Family_Name 'Family Name',Member_Name 'Member Name',consultant_name 'Consultant Name',
						CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(DATE, purchase_date,103) 'Purchase Date',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(DATE, sold_date,103) 'Sold Date',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',ISNULL(short_term ,0) 'Short Term',ISNULL(long_term,0) AS 'Long Term',ISNULL(speculation,0) AS speculation,
						CASE
							WHEN ISNULL(closing_qty,0) != 0 AND ISNULL(sold_date,'') != '' AND ((ISNULL(opening_date,'') = '') OR(ISNULL(purchase_date,'') = '')) THEN sold_date
							WHEN ISNULL(closing_qty,0) != 0 AND ISNULL(opening_date,'') != '' AND (ISNULL(sold_date,'') = '') THEN opening_date
							WHEN ISNULL(closing_qty,0) != 0 AND ISNULL(purchase_date,'') != ''  AND (ISNULL(sold_date,'') = '') THEN purchase_date
						END  AS  'Closing Date',
						ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',1 sort 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
						ORDER BY  script_name 
				END	 
			END

		DROP TABLE #mainoutputtable_1 
		DROP TABLE #mainouttable_1_BSEISINNO
		DROP TABLE #alldata 
		DROP TABLE #Family
		DROP TABLE #Members

  END  






































GO
/****** Object:  StoredProcedure [dbo].[proc_StockFilter_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockFilter_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_StockFilter_F_And_O_AND_MCX_And_Currency] AS' 
END
GO
 --proc_StockFilter_F_And_O_AND_MCX_And_Currency  0,1,0,'A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','', 0,0,'Details','',''
ALTER PROCEDURE [dbo].[proc_StockFilter_F_And_O_AND_MCX_And_Currency]  
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(MAX),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(MAX),@ConsultantCode  VARCHAR(MAX), @IsIntraDay VARCHAR(MAX),@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX),@FamilyCode VARCHAR(MAX),@BSE_NSE_Code VARCHAR(50))
AS 
  BEGIN 
  SET NOCOUNT ON;
		DECLARE @StartYearDate varchar(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate = CONVERT(VARCHAR(10),@StartYearDate,101)
		CREATE TABLE #mainoutputtable_1
        ( 
		   Dup_pkid int, 
		   pkid INT identity(1,1), 
           Family_Name VARCHAR(500),
		   Member_Name VARCHAR(500),
		   Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT,
		   Trans_Type  VARCHAR(50), 
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(10),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name  VARCHAR(500),
		   flag_holding_type VARCHAR(200), 
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(10),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount AS( [opening_qty] * [opening_rate] ), 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount AS( purchase_qty * purchase_rate ), 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount AS ( sold_qty * sold_rate ), 
		   gain_loss float,
           
		   closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 

           closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
		   closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
		   short_term FLOAT DEFAULT 0,
		   long_term  FLOAT DEFAULT 0,
           speculation  FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(20) ,
		   ScriptCode VARCHAR(50) 
        )  

		CREATE TABLE #mainoutputtable_1_Final
        ( 
		   Dup_pkid int, 
		   OrderBy varchar(100),
           Family_Name VARCHAR(500),
		   Member_Name VARCHAR(500),
		   Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT   ,
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(10),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name  VARCHAR(500),
		   flag_holding_type VARCHAR(200), 
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(10),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(20),
		   sort   VARCHAR(5),
		   ScriptCode VARCHAR(50) 
		) 
		 
		CREATE TABLE #Members
		(
			Member_Code varchar(MAX)
		)
			
		CREATE TABLE #Family
		(
			Family_Code varchar(MAX)
		)

		DECLARE @tmp VARCHAR(MAX)
				
		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty INT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT  
		DECLARE @tablerowscount INT
      IF(@status = 0) 
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
				@openingDate VARCHAR(50),@openingRate FLOAT,@openingQty INT,@openingAmount FLOAT,
				@purchaseDate VARCHAR(50),@PurchaseBillNo  VARCHAR(50),@purchaseRate FLOAT,@purchaseQty INT,@purchaseAmount FLOAT,
				@soldDate VARCHAR(50),@soldBillNo  VARCHAR(50),@soldRate FLOAT,@soldQty INT,@soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50),@Consultant_Name  VARCHAR(100), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(10),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,@PurchaseIntraFlag VARCHAR(100),@SaleIntraFlag VARCHAR(10) 
				DECLARE @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@ScriptId VARCHAR(50),@Dup_pkid int, @Pkid int,@idcount int  
				DECLARE  @COUNT INT = 0
				CREATE TABLE #SCriptCodes
				(
					ScriptCode varchar(MAX)
				)

				IF(@ScriptCode != '')
					INSERT INTO #SCriptCodes SELECT value FROM Fn_split(@ScriptCode, ',') 
				ELSE 
					INSERT INTO #SCriptCodes select Script_Code from mst_script 
				CREATE TABLE #ConsultantCodes
				(
					ConsultantCodes varchar(MAX)
				)

				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes select Consultant_Code from Mst_Consultant

				
				IF(@memcode = '' AND @familycode != '')
					BEGIN
						INSERT INTO #Members
						SELECT Member_Code 
						FROM Mst_Member WHERE Family_Code IN (SELECT Value FROM membercodestable(@familycode,','))
						SET @tmp = ''
						SELECT @tmp = @tmp + Member_Code + ',' FROM #Members
						SET @memcode = 	IsNULL((select SUBSTRING(@tmp, 0, LEN(@tmp))),'')
					END
				
				IF(@memcode != '' AND @familycode = '')
					BEGIN
						INSERT INTO #Family
						SELECT Family_Code 
						FROM Mst_Member WHERE Member_Code IN (SELECT Value FROM membercodestable(@memcode,','))
						SET @tmp = ''
						SELECT @tmp = @tmp + Family_Code + ',' FROM #Family
						SET @familycode = 	IsNULL((SELECT SUBSTRING(@tmp, 0, LEN(@tmp))),'')
					END
				
				SELECT	 ROW_NUMBER ( ) OVER (ORDER BY t.script_code,t.Ac_Type,t.trans_dt ) AS NameId,t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,t.TransType,t.Ac_Type,t.Script_Code,t.Last_Date,t.Qty,t.Rate,
						t.Member_code,t.YearCode,t.Consultant_code,t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,t.Exp_Rate,t.FrmNm,t.ID,
						Ms.bse_code,Ms.nse_code,
						CASE WHEN @Investmenttype=2 then  ms.script_name 
							ELSE
						Ms.script_name 
						+ '/' +   CONVERT(VARCHAR(10),t.Last_Date,101) 
						+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
						+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' 
						END	END script_name,
						'' AS 'Holding Type',

						CASE	WHEN (t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101) THEN 'Opening'
								WHEN t.TransType='Bought' AND  t.Bill_no != 'Opening'   THEN 'Bought' 
						 
						END AS 'Flag_Type',
						cm.Consultant_Name,mm.Member_Name,MF.Family_Name
						INTO #alldata 
				FROM brokerbill_trans t 
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				 
				LEFT JOIN Mst_Consultant cm ON t.Consultant_code = cm.Consultant_code  
				LEFT JOIN Mst_Member MM ON mm.Member_Code=t.Member_code
				LEFT JOIN Mst_Family MF ON MF.Family_Code =MM.Family_Code
				
				WHERE  ISNULL(isfnobill,0) = @Investmenttype 
				AND trans_dt <= @Todate 
				AND t.member_code IN (SELECT value FROM Fn_split(@memcode, ',') )
				AND yearcode = @yearcode  
				AND Ac_Type =(CASE WHEN  @Ac_Type='0' THEN Ac_Type  ELSE  @Ac_Type END)
				AND t.script_code IN (SELECT * FROM #SCriptCodes)
				AND	t.Consultant_code IN (SELECT * FROM #ConsultantCodes)
				AND	t.Member_Code IN (SELECT value FROM Fn_split(@memcode, ',') )
				AND	MF.Family_Code IN (SELECT value FROM Fn_split(@FamilyCode, ',') )
				AND ISNULL(t.isIntraDay,0) =(CASE WHEN @IsIntraDay=0 THEN  ISNULL(isIntraDay,0) ELSE @IsIntraDay END) 
				GROUP BY Trans_No,Sr_No,Bill_no,Trans_Dt,TransType,Ac_Type,t.Script_Code,MonthYear,Last_Date,LotSize,Qty,LotQty,Disp_qty,
				Bal_qty,G_Rate,Brok_Amt,ServTax_Amount,Rate,Amount,Stt_Amount,t.Member_Code,YearCode,t.Consultant_code,
				EntrySource,Ref_TransNo,Ref_SrNo,MergedEntry,isFNOBill,Strike_Price,OptionType,isIntraDay,Brok_PerUnit,lockedbymerger,
				frac_Qty,Org_Trans_No,Org_SrNo,isDeleteMerger,isstock,ScripwiseExpense,isClient_code,isClient_Brokrage,c_Qty,C_Gross_Rate,
				C_Net_Rate,C_Amount,C_STT,C_STax,C_MisChg,TransactionChg,C_StampDuty,Exp_Rate,PerExp_Unit,FrmNm,ID,bse_code,nse_code,script_name,cm.Consultant_Name,mm.Member_Name,MF.Family_Name
			 
		
				DECLARE @isIntradayCol INT ,@Family_Name VARCHAR(500),@Member_Name VARCHAR(500)
				
				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT id,Trans_No,script_name,Script_Code,Family_Name,Member_Name, [holding type],bill_no,CONVERT(VARCHAR(10),trans_dt,101),qty,rate,
				ISNULL(qty, 0) * ISNULL(rate, 0),ISNULL(isintraday, 0),consultant_name   
				FROM #alldata
				--WHERE --#alldata.bill_no = 'Opening' 
				WHERE #alldata.bill_no IN('Split','Opening') OR  CONVERT(date,trans_dt,101)  < CONVERT(date ,@StartYearDate,101)
				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId , @Family_Name,@Member_Name, @holding_type, @billno,      @dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
						IF(@Investmenttype=2)
							SET @holding_type='Mutual Fund'
						SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
						SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
						SET @Dup_pkid = ISNULL(@Dup_pkid,0)
						SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
						SET @Dup_pkid = @Dup_pkid + 1
						
						INSERT INTO #mainoutputtable_1   
						(
							Dup_pkid,id,ScriptCode  ,Family_Name,Member_Name, Trans_No,  Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,consultant_name
						) 
						SELECT @Dup_pkid,@ID,@ScriptId  , @Family_Name,@Member_Name, @Trans_No, 'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Consultant_Name
					
						IF(@idcount>0)
							BEGIN
								UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
							END
					END 
				
				FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId , @Family_Name,@Member_Name,@holding_type,@billno,@dates,@qty,@rate,@amount,@isIntradayCol, @Consultant_Name

				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 
				
				 
				DECLARE @salecount INT=0,@Boughtcount INT=0,@Flag_Type VARCHAR(20) 
				
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
				SELECT id,Family_Name,Member_Name, Bill_no,Flag_Type,TransType,Script_Code,script_name,[holding type],Trans_No,CONVERT(VARCHAR(10), trans_dt,101), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name
				FROM #alldata WHERE   
				(TransType in('Bought','Sold')  AND CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
				--#alldata.Bill_no <> 'Opening'
				GROUP BY  id,Family_Name,Member_Name,Bill_no,Flag_Type,TransType,script_name,Script_Code,[holding type],Trans_No,  trans_dt , qty,rate , isIntraDay,Consultant_Name	
				ORDER BY trans_dt ,script_name,[holding type]  asc
				
				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Family_Name,@Member_Name,@billno,@Flag_Type , @TransType,@ScriptId,@scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
				
				WHILE (@@FETCH_STATUS = 0) 
						BEGIN
							SET @COUNT = 0
							DECLARE @IsOpening INT =0
							DECLARE @prioritysId INT=0
							DECLARE @str VARCHAR(MAX)=''	
							DECLARE @purchase_Op_Qty FLOAT =0
							DECLARE @purchase_Op_Bill VARCHAR(20)=''
							DECLARE @purchase_Op_Date VARCHAR(20)=''
							DECLARE @purchase_Op_Rate FLOAT=0
							DECLARE	@PurQTY FLOAT=0
							DECLARE	@BalPurQTY FLOAT=0
							DECLARE @BalSoldQTY FLOAT=0
							DECLARE @Balpurchase_Op_Qty FLOAT=0
							DECLARE @BalOpeningQTY FLOAT=0
							DECLARE	@Sold_Qty FLOAT=0
							DECLARE @tempID int = 0
							
							IF(@isIntradayCol=0)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and isnull(Flag_Type,'')='' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=0 AND Consultant_Name = (CASE WHEN @ConsultantCode <> '' THEN @Consultant_Name ELSE consultant_name END) AND Family_Name = (CASE WHEN @FamilyCode <> '' THEN @Family_Name ELSE Family_Name END) AND Member_Name = (CASE WHEN @memcode <> '' THEN @Member_Name ELSE Member_Name END))
											IF (@COUNT > 0)
												BEGIN
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* INTO #tempSoldValExists 
													FROM
													#MainOutputtable_1 
													WHERE script_name=@scriptname AND holding_type=@holding_type  AND isintradaycol=0 AND consultant_name=@Consultant_Name
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold IN('Sold')  and isnull(Flag_Type,'')='' AND isintradaycol=0
													GROUP BY prioritys,script_name,holding_type,sold_qty
													DECLARE @R_Sold_COUNT INT=(SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty INT 
													SET @purchase_Op_Qty=@qty
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists ORDER BY Dup_pkid)
															SET @str=@TransType
															SET @Temppurchase_Op_Qty=(SELECT TOP(1) sold_qty  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @soldDate=(SELECT TOP (1) sold_date  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @soldRate=(SELECT TOP (1) sold_rate  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @soldBillNo=(SELECT TOP (1) sold_bill_no  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempSoldValExists WHERE id  = @tempSaleID )

															SET @Sold_Qty= @purchase_Op_Qty
															IF(@TransType='Opening')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	
																	opening_date=@dates,
																	opening_rate=@rate,
																	opening_qty= CASE WHEN @Temppurchase_Op_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Temppurchase_Op_Qty END,
																	Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND pkid = @pkid
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	
																	purchase_date=@dates,
																	purchase_bill_no=@billno,
																	purchase_rate=@rate,
																	purchase_qty= CASE WHEN @Temppurchase_Op_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Temppurchase_Op_Qty END,
																	Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND pkid = @pkid
																END
															

															IF(@Temppurchase_Op_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET sold_qty=@purchase_Op_Qty 
																	WHERE Flag_Type_Sold='Sold' AND   id = @tempSaleID  AND pkid = @pkid
																END

															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND pkid = @pkid
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempSoldValExists )
															DECLARE @Balancedval   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Temppurchase_Op_Qty)

															IF(@Balancedval  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty = ABS(@Balancedval) 
																	SET @prioritysId  = (SELECT MAX(ISNULL(@prioritysId,0)+1) FROM #MainOutputtable_1)-- WHERE id=@tempSaleID )
																	 
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode  ,Family_Name,Member_Name, Trans_No, Flag_Type, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name)
																	VALUES(@Dup_pkid,@tempSaleID ,@ScriptId  ,@Family_Name,@Member_Name,@Trans_No, 'Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name)
																	
																	UPDATE #MainOutputtable_1 SET prioritys=@prioritysId+1  WHERE prioritys = @prioritysId AND ID<>@tempSaleID 
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																		END
																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
															
																	IF(@TransType='Opening')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Trans_No, Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Trans_No, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name)
																		END
																	ELSE if(@TransType='Bought')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Trans_No, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name)
																		END
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																		END
																ENd
															SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
															SET @qty=@Balancedval
														END
												

													DROP TABLE #tempValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
													INSERT INTO #mainoutputtable_1 (Dup_pkid,id,ScriptCode,Family_Name,Member_Name,Trans_No, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name) 
													VALUES (@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Trans_No, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name) 
												END
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */

											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening') AND ISNULL(sold_qty,0)=0  AND isintradaycol=0  AND  Consultant_Name = (CASE WHEN @ConsultantCode <> '' THEN @Consultant_Name ELSE consultant_name END) AND Family_Name = (CASE WHEN @FamilyCode <> '' THEN @Family_Name ELSE Family_Name END) AND Member_Name = (CASE WHEN @memcode <> '' THEN @Member_Name ELSE Member_Name END))
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* INTO #tempValExists 
													FROM
													#MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening') 
													AND consultant_name= @Consultant_Name AND ISNULL(sold_qty,0)=0  AND isintradaycol=0 

													
													DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty int 
													SET @Sold_Qty= @qty
													
													WHILE(@RCOUNT > 0)
														BEGIN 
															SET @tempID = (Select top(1) id from #tempValExists)
															SET @str = (Select top(1) Flag_Type From #tempValExists Where id  = @tempID ORDER BY Dup_pkid)
														
															IF(@str='Opening')
																BEGIN
																	SET @TempSoldQty=(SELECT TOP(1) opening_qty  FROM #tempValExists WHERE id  = @tempID)
																	SET @openingDate=(SELECT TOP(1) opening_date FROM #tempValExists WHERE id  = @tempID)
																	SET @openingrate=(SELECT TOP(1) opening_rate FROM #tempValExists WHERE id  = @tempID)
																	SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempSoldValExists WHERE id  = @tempID )
																END
															ELSE IF(@str='Bought')
																BEGIN
																	SET @TempSoldQty=(SELECT TOP(1) purchase_qty FROM #tempValExists WHERE id  = @tempID)
																	SET @PurchaseDate=(SELECT TOP(1) purchase_date FROM #tempValExists WHERE id  = @tempID)
																	SET @Purchaserate=(SELECT TOP(1) purchase_rate FROM #tempValExists WHERE id  = @tempID)
																	SET @PurchaseBillNo=(SELECT TOP(1) purchase_bill_no FROM #tempValExists WHERE id  = @tempID)
																	SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempSoldValExists WHERE id  = @tempID )
																END
															    
															IF(@Sold_Qty > 0)
																BEGIN
																	UPDATE #MainOutputtable_1  
																		SET	
																			opening_qty = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							END,
																			purchase_qty  = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							END,
																			sold_date=@dates,
																			sold_bill_no=@billno,
																			sold_rate=@rate,
																			sold_qty= CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold='Sold'
																	WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND  pkid = @pkid
																	SET @Balanceval = ABS(@Sold_Qty) - ABS(@TempSoldQty)
																END
															
															DELETE FROM #tempValExists WHERE id = @tempID AND pkid = @pkid
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempValExists )
															SET @RCOUNT = @RCOUNT - 1
															SET @qty = @Balanceval
															SET @Sold_Qty = @qty
													
													
													
															IF(@Balanceval  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  =(SELECT MAX(ISNULL(@prioritysId,0)+1) FROM #MainOutputtable_1)-- WHERE id=@tempID)

																	IF(@str='Opening')
																		BEGIN
																			SET @openingQty=ABS(@Balanceval) 
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Trans_No,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@tempID,@ScriptId,@Family_Name,@Member_Name,@Trans_No, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name)
																			UPDATE #MainOutputtable_1 SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempID
																		END
																	ELSE 
																		BEGIN
																			SET @PurchaseQty=ABS(@Sold_Qty) 
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Trans_No,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Trans_No, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name)
																			UPDATE #MainOutputtable_1 SET prioritys=@prioritysId  WHERE prioritys > @prioritysId AND ID<>@tempID
																		END
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																		END
																	BREAK;
																END
															ELSE IF(@Balanceval  < 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name)
														
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																		END
																ENd
														END
													DROP TABLE #tempValExists
											END
											
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1) 
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
													INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
													VALUES(@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Trans_No,  'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name)
												END
											SET @purchase_Op_Date=''
											SET @purchase_Op_Rate=''
											SET @purchase_Op_Qty=''
											SET @purchase_Op_Bill=''
										END
								END
							ELSE IF(@isIntradayCol=1)
								 BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and Flag_Type='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=1  AND  Consultant_Name = (CASE WHEN @ConsultantCode <> '' THEN @Consultant_Name ELSE consultant_name END) AND Family_Name = (CASE WHEN @FamilyCode <> '' THEN @Family_Name ELSE Family_Name END) AND Member_Name = (CASE WHEN @memcode <> '' THEN @Member_Name ELSE Member_Name END))
											IF (@COUNT > 0)
												BEGIN
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* INTO #tempSoldValExists_intra_Bought 
													FROM
													#MainOutputtable_1 
													WHERE script_name=@scriptname AND holding_type=@holding_type  AND isintradaycol=1
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold IN('Sold')  and  Flag_Type='Sold'   AND consultant_name=@Consultant_Name
													GROUP BY prioritys,script_name,holding_type,sold_qty
													DECLARE @R_Sold_COUNT_intra INT=(SELECT COUNT(*) FROM #tempSoldValExists_intra_Bought )
													DECLARE @Temppurchase_Op_Qty_intra int 
													--SET @purchase_Op_Qty=@qty
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID_intra int = (Select top(1) id from #tempSoldValExists_intra_Bought ORDER BY Dup_pkid)
															SET @str=@TransType
															SET @Sold_Qty=(SELECT TOP(1) sold_qty  FROM #tempSoldValExists_intra_Bought WHERE id  = @tempSaleID_intra )
															SET @soldDate=(SELECT TOP(1) sold_date  FROM #tempSoldValExists_intra_Bought WHERE id  = @tempSaleID_intra )
															SET @soldRate=(SELECT TOP(1) sold_rate  FROM #tempSoldValExists_intra_Bought WHERE id  = @tempSaleID_intra )
															SET @soldBillNo=(SELECT TOP(1) sold_bill_no  FROM #tempSoldValExists_intra_Bought WHERE id  = @tempSaleID_intra )
															SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempSoldValExists WHERE id  = @tempSaleID_intra )
															--SET @Sold_Qty= @purchase_Op_Qty
															SET @purchase_Op_Qty= @qty
															IF(@TransType='Bought')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	
																	purchase_date=@dates,
																	purchase_bill_no=@billno,
																	purchase_rate=@rate,
																	purchase_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																	Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND pkid = @pkid 
																END
															ELSE
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	
																	opening_date=@dates,
																	opening_rate=@rate,
																	opening_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																	Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND pkid = @pkid
																END

															IF(@Sold_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  SET sold_qty=@purchase_Op_Qty WHERE Flag_Type_Sold='Sold' AND   id = @tempSaleID_intra  AND pkid = @pkid
																END
															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID_intra  AND pkid = @pkid
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempSoldValExists )
															declare @Balancedval_intra   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)
															IF(@Balancedval_intra  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty=ABS(@Balancedval_intra  ) 
																	SET @prioritysId  =(SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempSaleID_intra )
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode,Family_Name,Member_Name, Trans_No, Flag_Type, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@tempSaleID_intra ,@ScriptId,@Family_Name,@Member_Name,@Trans_No, 'Opening',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval_intra),@soldRate,@isIntradayCol,@Consultant_Name)
																	UPDATE #MainOutputtable_1 SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempSaleID_intra 

																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																		END
																	BREAK;
																END
															ELSE IF(@Balancedval_intra  > 0 AND @tablerowscount = 0 )
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																	if(@TransType='Opening')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Trans_No,  Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Trans_No, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval_intra),@rate,@isIntradayCol,@Consultant_Name)
																		END
																	ELSE if(@TransType='Bought')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Trans_No, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval_intra)  ,@rate,@isIntradayCol,@Consultant_Name)
																		END
																
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																		END
																ENd
																SET @R_Sold_COUNT_intra  = @R_Sold_COUNT_intra  - 1
																SET @qty=@Balancedval_intra
														END
									
													DROP TABLE #tempValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
												 
													INSERT INTO #mainoutputtable_1 (Dup_pkid,id,ScriptCode,Family_Name,Member_Name,Trans_No, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name) 
													VALUES (@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Trans_No, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name) 
												END
										END	

									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Enry Already if Purchase or Opening Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening') AND ISNULL(sold_qty,0)=0  AND isintradaycol=1 AND  Consultant_Name = (CASE WHEN @ConsultantCode <> '' THEN @Consultant_Name ELSE consultant_name END) AND Family_Name = (CASE WHEN @FamilyCode <> '' THEN @Family_Name ELSE Family_Name END) AND Member_Name = (CASE WHEN @memcode <> '' THEN @Member_Name ELSE Member_Name END))
											IF (@COUNT > 0)
												BEGIN
													SET @Sold_Qty=0
													--select 1 'sold',@qty
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* INTO #tempValExists_intraBought 
													FROM
													#MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening') AND Consultant_Name=@Consultant_Name
													AND ISNULL(sold_qty,0)=0  AND isintradaycol=1 
													DECLARE @RCOUNT_intraBought INT=(SELECT COUNT(*) FROM #tempValExists_intraBought)
													DECLARE @TempSoldQty_intra int 
													SET @Sold_Qty=@qty
													WHILE(@RCOUNT_intraBought > 0)
														BEGIN 
															DECLARE @tempID_intraBought int = (Select top(1) id from #tempValExists_intraBought where isintradaycol=1 ORDER BY Dup_pkid)
															SET @str = (Select top(1) Flag_Type From #tempValExists_intraBought Where id  = @tempID_intraBought)
															 
															SET @TempSoldQty_intra=(SELECT TOP(1) purchase_qty FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought)
															SET @PurchaseDate=(SELECT TOP(1) purchase_date FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought)
															SET @Purchaserate=(SELECT TOP(1) purchase_rate FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought)
															SET @PurchaseBillNo=(SELECT TOP(1) purchase_bill_no FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought)
															SET @Sold_Qty= @qty
															SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempSoldValExists WHERE id  = @tempID_intraBought )	
															
															UPDATE #MainOutputtable_1  
																SET	
																	sold_date=@dates,
																	sold_bill_no=@billno,
																	sold_rate=@rate,
																	sold_qty= CASE WHEN @TempSoldQty_intra > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty_intra END,
																	Flag_Type_Sold='Sold' 
																	WHERE  id = @tempID_intraBought and isnull(sold_qty,0)=0 AND pkid = @pkid

																
															IF(@TempSoldQty_intra > @Sold_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  SET purchase_qty=@Sold_Qty WHERE Flag_Type='Bought' AND   id = @tempID_intraBought AND pkid = @pkid
																END

															DELETE FROM #tempValExists_intraBought WHERE id = @tempID  AND pkid = @pkid
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempValExists_intraBought )
															declare @Balanceval_intraBought FLOAT = ABS(@Sold_Qty) - ABS(@TempSoldQty_intra)
															IF(@Balanceval_intraBought  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @PurchaseQty=ABS(@Sold_Qty) 
																	SET @prioritysId  = (SELECT MAX(ISNULL(@prioritysId,0)+1) FROM #MainOutputtable_1)-- WHERE id=@tempID_intraBought)
																	 
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Trans_No,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@tempID_intraBought,@ScriptId,@Family_Name,@Member_Name,@Trans_No, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval_intraBought)  ,@Purchaserate,@isIntradayCol,@Consultant_Name)
																	UPDATE #MainOutputtable_1 SET prioritys=@prioritysId  WHERE prioritys > @prioritysId AND ID <> @tempID
																		
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																		END
																	BREAK;
																END
															ELSE IF(@Balanceval_intraBought  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval_intraBought)  ,@rate,@isIntradayCol,@Consultant_Name)
																
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																		END
																ENd
															SET @RCOUNT_intraBought = @RCOUNT_intraBought - 1
															SET @qty=@Balanceval_intraBought
														END

													DROP TABLE #tempValExists_intraBought
												END
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
													INSERT INTO #MainOutputtable_1(Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
													VALUES(@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name, @Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name)
												END
													SET @purchase_Op_Date=''
													SET @purchase_Op_Rate=''
													SET @purchase_Op_Qty=''
													SET @purchase_Op_Bill=''
										END
								END
							FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Family_Name,@Member_Name,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
						END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 
		IF(@IsIntraDay = 0 AND @short_Long_Term != 0  )
			BEGIN
				IF(@short_Long_Term = 1)  -- Long Term
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Trans_No, prioritys,script_name ,'Empty',opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						 Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate,1 sort ,isintradaycol
						FROM #mainoutputtable_1 
						WHERE ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
									(
										DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101)) > 365 
									)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									(
										DATEDIFF(DAY,CONVERT(DATETIME, purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101)) > 365
									)
								)
							)
						order by NameId
					END

				ELSE If(@short_Long_Term = 2)  -- Short Term
					BEGIN

						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Trans_No, prioritys,script_name ,'Empty',opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4) as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate,1 sort,isintradaycol 
						FROM #mainoutputtable_1 
						WHERE  ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
										(		
											DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101)) < 365 
										)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									  (		
										DATEDIFF(DAY,CONVERT(DATETIME, purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101)) < 365
									  )
								)
							)
						order by NameId
					END

				ELSE If(@short_Long_Term = 4)  -- Short Term + Long Term
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Trans_No, prioritys,script_name ,'Empty',opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						 Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate,1 sort,isintradaycol 
						FROM #mainoutputtable_1 
						WHERE  ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
					END
			END

		ELSE If(@short_Long_Term = 3 AND @IsIntraDay = 1 )  -- Only Speculation
			BEGIN
				INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

				SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Trans_No, prioritys,script_name ,'Empty',opening_date,
				ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),purchase_date,ISNULL(purchase_bill_no,0),
				ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,sold_date ,sold_bill_no ,isnull(sold_qty,0) ,
				ISNULL(sold_rate,0),ISNULL(sold_amount,0) , 
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4) as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate,1 sort,isintradaycol 
				FROM #mainoutputtable_1 
				WHERE  (ISNULL(closing_qty,0) = 0)  AND (ISNULL(isintradaycol,0)=1) AND (ISNULL(purchase_qty,0)! = 0 AND  ISNULL(sold_qty,0) ! = 0) 
			END

		ELSE
			BEGIN
				INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Trans_No, prioritys,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

				SELECT 
				ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,case when CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) else CONVERT(DATE,purchase_date,103) END,prioritys DESC, sold_date DESC ) AS NameId,
				opening_bill_no,
				id,ScriptCode,Family_Name,Member_Name,Trans_No, prioritys,script_name ,'Empty', flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,
				  Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate,1 sort,isintradaycol 
				FROM #mainoutputtable_1 
			END
	  
		UPDATE #mainoutputtable_1_Final SET prioritys=0
		DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
		UPDATE #mainoutputtable_1_Final
		SET prioritys  = @i , @i = @i + 1

		IF(@OUTPUT_Flag='Details')
			BEGIN
				SELECT  prioritys,id,ScriptCode,script_name 'Script Name',Family_Name 'Family Name',Member_Name 'Member Name', consultant_name 'Consultant Name' ,
				CONVERT(DATE, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
				CONVERT(DATE, purchase_date,101) 'Purchase Date',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
				CONVERT(DATE, sold_date,101) 'Sold Date',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',ISNULL(gain_loss,0) 'Gain/Loss',
				(
					CASE WHEN (ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) THEN gain_loss 
						ELSE 
							CASE WHEN (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 ) THEN gain_loss 
								ELSE
									0 
								END 
						END
				) AS 'Short Term',
						
				(
					CASE WHEN (ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365) THEN gain_loss 
						ELSE 
							CASE WHEN (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >
							= 365) THEN gain_loss 
								ELSE
									0 
								END 
						END
				) AS 'Long Term',
				
				(
					CASE WHEN (((ISNULL(purchase_date,'') !='') AND ((ISNULL(sold_date,''))  !=''))  AND (purchase_date = sold_date ) AND (purchase_bill_no=sold_bill_no) AND (isintradaycol=1)) THEN gain_loss 
						ELSE
							0 
						END
				) AS speculation,
				CASE
					WHEN ISNULL(closing_qty,0) != 0 AND ISNULL(sold_date,'') != '' AND ((ISNULL(opening_date,'') = '') OR(ISNULL(purchase_date,'') = '')) THEN sold_date
					WHEN ISNULL(closing_qty,0) != 0 AND ISNULL(opening_date,'') != '' AND (ISNULL(sold_date,'') = '') THEN opening_date
					WHEN ISNULL(closing_qty,0) != 0 AND ISNULL(purchase_date,'') != ''  AND (ISNULL(sold_date,'') = '') THEN purchase_date
				END 
					AS  'Closing Date',
				ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',1 sort 
				FROM #mainoutputtable_1_Final
				WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)
		
				ORDER BY   prioritys	
			END

		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
				SELECT  0 id ,  0 prioritys,Family_Name,Member_Name, script_name 'Script Name', '' Holding_Type,
				NULL 'Opening Date', SUM(ISNULL(opening_qty,0)) 'Opening Qty', SUM(ISNULL(opening_rate,0)) 'Opening Rate', SUM(ISNULL(opening_amount,0)) 'Opening Amount',
				NULL 'Purchase Date',MAX(purchase_bill_no) 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty', SUM(ISNULL(purchase_rate,0)) 'Purchase Rate', SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
				NULL 'Sold Date', MAX(sold_bill_no) 'Sold BillNo', SUM(ISNULL(sold_qty,0)) 'Sold Qty', SUM(ISNULL(sold_rate,0)) 'Sold Rate', SUM(ISNULL(sold_amount,0)) 'Sold Amount', SUM(ISNULL(gain_loss ,0)) 'Gain/Loss', SUM(ISNULL(gain,0))  'Gain', SUM(ISNULL(loss,0))  'Loss',
				SUM(ISNULL(closing_qty,0))  'Closing Qty', SUM(ISNULL(closing_rate,0))  'Closing Rate', SUM(ISNULL(closing_value,0))  'Closing Value', SUM(ISNULL(short_term,0))  short_term, SUM(ISNULL(long_term,0))  long_term,
				SUM(ISNULL(speculation,0)) speculation, SUM(ISNULL(gain_speculation,0)) gain_speculation, SUM(ISNULL(loss_speculation,0)) loss_speculation,'' consultant_name, 0 nse_rate, 0 bse_rate, 1 sort 
				FROM
					(
						SELECT MAX(id + 0)id ,MAX (prioritys+0) prioritys,Family_Name,Member_Name, script_name  ,'' Holding_Type,
						NULL 'Opening Date',SUM(opening_qty) 'Opening_Qty',sum(opening_rate) opening_rate ,SUM(ISNULL(opening_amount,0)) 'Opening_Amount',
						NULL 'Purchase Date',purchase_bill_no,SUM(ISNULL(purchase_qty,0)) 'Purchase_Qty', SUM(ISNULL(purchase_rate,0)) purchase_rate,SUM(ISNULL(purchase_amount,0)) 'Purchase_Amount',
						NULL 'Sold Date',sold_bill_no ,SUM(ISNULL(sold_qty,0)) 'Sold_Qty', SUM(ISNULL(sold_rate,0))sold_rate  , SUM(ISNULL(sold_amount,0)) 'Sold_Amount',SUM(ISNULL(gain_loss,0)) 'Gain_Loss',SUM(ISNULL(gain,0)) 'Gain',SUM(ISNULL(loss,0)) 'Loss',
						SUM(ISNULL(closing_qty,0)) 'Closing_Qty',SUM(ISNULL(closing_rate,0)) 'Closing_Rate',SUM(ISNULL(closing_value,0)) 'Closing_Value',SUM(ISNULL(short_term,0)) short_term,SUM(ISNULL(long_term,0)) long_term,
						SUM(ISNULL(speculation,0)) speculation,SUM(ISNULL(gain_speculation,0)) gain_speculation,SUM(ISNULL(loss_speculation,0)) loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort 
						FROM #mainoutputtable_1_Final 
						GROUP BY  Family_Name,Member_Name,script_name,Holding_Type,purchase_bill_no,sold_bill_no 
					)a
				GROUP BY   Family_Name,Member_Name,script_name  
				ORDER BY  prioritys 
			END

		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN
			
				SELECT  prioritys ,Trans_No,id ,ScriptCode,Family_Name,Member_Name, script_name ,Holding_Type, flag_script_name,flag_Holding_Type,
				CONVERT(DATE, opening_date,101) opening_date,ISNULL(opening_qty,0) opening_qty,ISNULL(opening_Rate,0) opening_Rate,ISNULL(opening_amount,0) opening_amount,
				CONVERT(DATE, purchase_date,101) purchase_date,purchase_bill_no,ISNULL(purchase_qty ,0) purchase_qty,ISNULL(purchase_rate ,0) purchase_rate,ISNULL(purchase_amount ,0) purchase_amount,
				CONVERT(DATE, sold_date,101),sold_bill_no ,ISNULL(sold_qty ,0)sold_qty,ISNULL(sold_rate,0)sold_rate,ISNULL(sold_amount,0) sold_amount,
				ISNULL(gain_loss,0) gain_loss,ISNULL(gain,0) gain,ISNULL(loss,0)loss,ISNULL(closing_qty,0) closing_qty,ISNULL(closing_rate,0) closing_rate,ISNULL(closing_value,0) closing_value,
				ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,ISNULL(gain_speculation,0)gain_speculation,ISNULL(loss_speculation,0)loss_speculation,
				consultant_name,ISNULL(nse_rate,0) nse_rate,ISNULL(bse_rate,0) bse_rate,0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,ISNULL(isintradaycol,0) isintradaycol
				FROM #mainoutputtable_1_Final
				ORDER BY  Family_Name,Member_Name,script_name  
			END

		DROP TABLE #mainoutputtable_1 
		
		DROP TABLE #alldata 
		 
		DROP TABLE #Family
		DROP TABLE #Members

  END  





































GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_BrokerWise_Equity]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_BrokerWise_Equity]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_StockholdingPosition_BrokerWise_Equity] AS' 
END
GO

--proc_StockholdingPosition_BrokerWise_Equity 0,0,'0','30001','1120182019','2018-04-01','2019-03-31','','','','0', '0' ,'0','Details'	
-- Select * from mst_Member
--proc_StockholdingPosition_BrokerWise_Equity 0,0,'0','A0001','1120182019','2018-04-01','2019-03-31','B0017','','','0', '0' ,'0','AllData'					    
--0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','ScriptWiseTotal'
ALTER PROCEDURE [dbo].[proc_StockholdingPosition_BrokerWise_Equity] 
(	@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
	@ScriptCode VARCHAR(max),@BrokerCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),
	@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX),@IsWithTax bit = 0,@IsFromMonthWise bit = 0)
AS 
  BEGIN 
  SET NOCOUNT ON;
		DECLARE @StartYearDate varchar(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101)

		CREATE TABLE #mainoutputtable_1
        ( 
			pkid INT identity(1,1), 
			Dup_pkid int, 
			Broker_name VARCHAR(MAX),
			Trans_No VARCHAR(20),
			id INT,
			prioritys INT,
			Trans_Type  VARCHAR(500), 
			Split_Type VARCHAR(500), 
			Flag_Type VARCHAR(100),
			Flag_Type_Sold VARCHAR(100),
			flag_script_name  VARCHAR(Max),
			flag_holding_type VARCHAR(Max), 
			script_name  VARCHAR(Max),
			holding_type VARCHAR(Max), 
		    opening_bill_no VARCHAR(100),		    
			opening_date DATETIME,
			opening_qty  FLOAT DEFAULT 0,
			opening_rate  FLOAT DEFAULT 0,
			opening_amount AS( [opening_qty] * [opening_rate] ), 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount AS( purchase_qty * purchase_rate ), 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount AS ( sold_qty * sold_rate ), 
			gain_loss float,
			closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 
			closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
			closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
			short_term FLOAT DEFAULT 0,
			long_term  FLOAT DEFAULT 0,
			speculation  FLOAT DEFAULT 0,
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
	 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			dayscount FLOAT DEFAULT 0,
			isintradaycol INT,[type] VARCHAR(50) ,
			ScriptCode VARCHAR(50),
			MemberCode VARCHAR(50),
			MemberName VARCHAR(max)
        )  

		CREATE TABLE #mainoutputtable_1_Final
        ( 
		   Dup_pkid int, 
		   OrderBy varchar(100),
           Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT   ,
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(50),
		   Flag_Type_Sold VARCHAR(100),
		   flag_script_name  VARCHAR(Max),
		   flag_holding_type VARCHAR(Max), 
		   script_name  VARCHAR(Max),
		   holding_type VARCHAR(Max), 
		   opening_bill_no VARCHAR(100),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   Broker_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(50),
		   sort   VARCHAR(5),
		   ScriptCode VARCHAR(50),
		   MemberCode VARCHAR(50),
		   MemberName VARCHAR(max)
        ) 

		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates DATETIME,@qty FLOAT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT  
		DECLARE @tablerowscount INT
		IF(@status = 0) 
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
				@openingDate DATETIME,@openingRate FLOAT,@openingQty FLOAT,@openingAmount FLOAT,
				@purchaseDate DATETIME,@PurchaseBillNo  VARCHAR(50),@purchaseRate FLOAT,@purchaseQty FLOAT,@purchaseAmount FLOAT,
				@soldDate DATETIME,@soldBillNo  VARCHAR(50),@soldRate FLOAT,@soldQty FLOAT,@soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50),@Broker_name  VARCHAR(100), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(10),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,
				@PurchaseIntraFlag VARCHAR(100),@SaleIntraFlag VARCHAR(10), @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@ScriptId VARCHAR(50),@Dup_pkid int, 
				@Pkid varchar(200),@idcount int, @Member_Code varchar(50), @Member_Name varchar(max) 

				CREATE TABLE #SCriptCodes
				(
					ScriptCode varchar(MAX)
				)

				IF(@ScriptCode != '')
					INSERT INTO #SCriptCodes SELECT value FROM Fn_split(@ScriptCode, ',') 
				ELSE 
					INSERT INTO #SCriptCodes select MS.Script_Code from mst_script MS join Brokerbill_trans bbt on bbt.Script_Code=MS.Script_code group by MS.Script_Code

				CREATE TABLE #BrokerCodes
				(
					BrokerCodes varchar(MAX)
				)
				 
				IF(@BrokerCode != '')
					INSERT INTO #BrokerCodes SELECT value FROM Fn_split(@BrokerCode, ',') 
				ELSE 
					INSERT INTO #BrokerCodes 
					SELECT BB .Broker_Code 
					FROM brokerbill BB 
					left join BrokerBill_Trans BBT ON BBT.Trans_No=BBT.Trans_No AND BBT.Member_code = bb.Member_Code and bbt.YearCode=bb.YearCode
					WHERE BBT.Member_Code in (SELECT Value FROM membercodestable(@memcode,','))  AND BBT.YearCode=@yearcode
					group by  BB .Broker_Code

					
				SELECT	ROW_NUMBER ( ) OVER (ORDER BY mm.Member_Code,mm.Member_Name, t.script_code,t.Ac_Type,t.trans_dt ) AS NameId,
						t.Trans_No,t.Sr_No,t.Bill_no,ma1.AC_Name,t.Trans_Dt,t.TransType,t.Ac_Type,t.Script_Code,t.Last_Date,t.Qty,
						Case When @IsWithTax=0 Then t.Rate Else t.Exp_Rate END As 'Rate',--t.Rate,
						t.YearCode, t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,t.Exp_Rate,t.FrmNm,t.ID,
						Ms.bse_code,Ms.nse_code,Ms.script_name,ma.ac_name  AS 'Holding Type',
						CASE	WHEN TransType='Sold' THEN 'Sold' 
						        WHEN (((t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101))AND t.TransType='Bought') THEN 'Opening' 								
								WHEN TransType='Bought' AND t.Bill_no = 'Bonus' THEN 'Bonus' 
								WHEN TransType='Bought' AND t.Bill_no ='Rights'THEN 'Rights' 
								WHEN TransType='Bought' AND  t.Bill_no ='Split' THEN 'Split' 
								WHEN TransType='Bought' AND  t.Bill_no ='Transfer' THEN 'Transfer' 
								WHEN TransType='Bought' AND Frmnm = 'IPO' THEN 'IPO'  
								WHEN TransType='Bought' AND Frmnm='MFDRI' THEN 'Devidend Re-Investment'
								WHEN t.TransType='Bought' AND  t.Bill_no <> 'Opening'  THEN 'Bought' 								
								END AS 'Flag_Type',
						ma1.AC_Name as 'Broker_Name',
						mm.Member_Code,
						mm.Member_Name
				INTO #alldata 
				FROM brokerbill_trans t 
				LEFT JOIN mst_script ms		ON t.script_code = Ms.script_code 
				LEFT JOIN mst_account ma	ON t.ac_type = ma.ac_code AND ma.member_code = t.Member_code and ma.Year_Code=t.YearCode
				LEFT JOIN BrokerBill BB		ON BB.Member_Code = t.Member_code AND BB.Trans_no=t.Trans_No AND BB.YearCode = t.yearcode
				LEFT JOIN mst_account ma1	ON ma1.AC_Code = BB.Broker_Code AND ma1.Member_Code = BB.Member_code and ma1.Year_Code = BB.YearCode  and bb.Trans_no=t.Trans_No
				LEFT JOIN Mst_Member mm		ON t.member_code = mm.Member_code 
				WHERE  ISNULL(t.isfnobill,0) = @Investmenttype AND  t.trans_dt <= @Todate 
				AND  t.member_code IN (SELECT Value FROM membercodestable(@memcode,','))   
				AND  t.yearcode = @yearcode  
				AND  t.Ac_Type =(CASE WHEN  @Ac_Type='0' THEN  t.Ac_Type  ELSE  @Ac_Type END)
				AND  t.script_code IN (SELECT * FROM #SCriptCodes)
				AND	 BB.Broker_code IN (SELECT * FROM #BrokerCodes)
				AND  ISNULL(t.isIntraDay,0) = (CASE WHEN @IsIntraDay=0 THEN  ISNULL(isIntraDay,0) ELSE ISNULL(@IsIntraDay,0) END) 
				AND t.MergedEntry = 0  AND ISNULL( t.Ref_SrNo,0) != 1
				AND (IsSLBS=0 OR IsSLBS IS NUll) 
				GROUP BY mm.Member_Code,mm.Member_Name,	t.Trans_Dt, t.Trans_No, t.Sr_No,t.Bill_no,
				ma1.AC_Code,ma1.AC_Name , ma.ac_name,t.Ac_Type,
				t.ID,
				Ms.script_name,							
				t.TransType,
				t.Script_Code,
				t.Last_Date,
				t.Qty,t.Rate,
				t.YearCode, 
				t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,
				t.Exp_Rate,t.FrmNm,Ms.bse_code,Ms.nse_code,Frmnm
				order by NameId
								
			--	select * from #alldata
				DECLARE @isIntradayCol INT ,  @COUNT INT = 0	 
				
				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT id,Trans_No,script_name,Script_Code, [holding type],bill_no,CONVERT(DATE,trans_dt,103),qty,rate,ISNULL(qty, 0) * ISNULL(rate, 0),ISNULL(isintraday, 0),Broker_name, Member_Code,Member_Name
				FROM #alldata
				WHERE ((TransType != 'Sold' AND #alldata.bill_no IN('Split','Opening')) OR  CONVERT(date,trans_dt,101)  < CONVERT(date ,@StartYearDate,101)AND #alldata.TransType='Bought')

				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type, @billno,      @dates, @qty, @rate, @amount, @isIntradayCol ,@Broker_name,@Member_Code,@Member_Name 
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
						IF(@Investmenttype=2)
							SET @holding_type='Mutual Fund'
						-- Insert All Openings
						SET @Pkid = (SELECT (MAX(ISNULL(pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId and MemberCode = @Member_Code and  Broker_name = @Broker_name)
						SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
						SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
						SET @Dup_pkid = ISNULL(@Dup_pkid,0)
						SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
						SET @Dup_pkid = @Dup_pkid + 1
	
						DECLARE @IDs INT=0
						
						INSERT INTO #mainoutputtable_1  
						(Dup_pkid, opening_bill_no ,id, Trans_No,ScriptCode, Trans_Type, Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,Broker_name,MemberCode,MemberName) 
						SELECT 
						@Dup_pkid,@billno,@ID, @Trans_No,@ScriptId,'Opening', 'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Broker_name,@Member_Code,@Member_Name
						
						SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),0) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
						IF(@idcount>0)
							BEGIN
								UPDATE #MainOutputtable_1 
								SET Dup_pkid = Dup_pkid + 1 
								WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
							END
			 			FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type, @billno,      @dates, @qty, @rate, @amount, @isIntradayCol ,@Broker_name,@Member_Code,@Member_Name
					END 
				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 
				
				DECLARE @salecount INT=0,@Boughtcount INT=0,@Flag_Type VARCHAR(50)
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
				SELECT id,Bill_no,Flag_Type,TransType,Script_Code, script_name,[holding type],Trans_No,CONVERT(DATETIME, trans_dt,103), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Broker_name, Member_Code,Member_Name
				FROM #alldata  	WHERE  
				(TransType in('Bought','Sold')  OR CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 

				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Broker_name,@Member_Code,@Member_Name
				WHILE (@@FETCH_STATUS = 0) 
					BEGIN
						SET @COUNT = 0
						DECLARE @IsOpening INT							=	0,
						@prioritysId INT								=	0,
						@str VARCHAR(MAX)								=	'',	
						@purchase_Op_Qty FLOAT							=	0,
						@purchase_Op_Bill VARCHAR(20)					=	'',
						@purchase_Op_Date VARCHAR(20)					=	'',
						@purchase_Op_Rate FLOAT							=	0,
						@PurQTY FLOAT									=	0,
						@BalPurQTY FLOAT								=	0,
						@BalSoldQTY FLOAT								=	0,
						@Balpurchase_Op_Qty FLOAT						=	0,
						@BalOpeningQTY FLOAT							=	0,
						@Sold_Qty FLOAT									=	0,
						@tempID int										=	0
						

					IF(@isIntradayCol=0)
						BEGIN
							IF(@Investmenttype = 2)
								SET @holding_type='Mutual Fund'

							IF(@TransType LIKE '%Bought%')
								BEGIN
									/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
									SET @COUNT = (	SELECT Count(*) 
													FROM #MainOutputtable_1 
													WHERE holding_type=@holding_type AND script_name=@scriptname 
													AND Flag_Type_Sold IN('Sold')  and  Flag_Type='Sold'
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) 
													AND isintradaycol=0 
													AND Broker_name = @Broker_name AND MemberName = @Member_Name)
									IF (@COUNT > 0)
										BEGIN
											SELECT  ROW_NUMBER ( ) OVER (ORDER BY MemberName,Broker_name,scriptcode, holding_type,CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,
											* INTO #tempSoldValExists 
											FROM
											#MainOutputtable_1 
											WHERE script_name=@scriptname AND holding_type=@holding_type  
											AND Broker_name = @Broker_name
											AND MemberName = @Member_Name
											AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
											AND Flag_Type_Sold ='Sold'  and  Flag_Type = 'Sold' AND isintradaycol=0
											ORDER BY NameId								
													 
											DECLARE @R_Sold_COUNT FLOAT=(SELECT COUNT(*) FROM #tempSoldValExists )
											DECLARE @Temppurchase_Op_Qty FLOAT 
													 
											WHILE(@R_Sold_COUNT  > 0)
												BEGIN 
													DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists ORDER BY Dup_pkid,NameId)
													SET @str = @TransType

													SELECT TOP 1	@Sold_Qty		= sold_qty,
																	@soldDate		= sold_date,
																	@soldRate		= sold_Rate,
																	@soldBillNo		= sold_bill_no,
																	@Pkid			= Pkid
													FROM #tempSoldValExists
													WHERE id  = @tempSaleID 

													SET @purchase_Op_Qty = @qty
															
													IF(@TransType='Opening')
														BEGIN
															UPDATE #MainOutputtable_1  
															SET	opening_date=@dates,
																opening_rate=@rate,
																opening_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
															Flag_Type = 'Bought'
															WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid
														END
													ELSE IF(@TransType='Bought')
														BEGIN
															UPDATE #MainOutputtable_1  
															SET	purchase_date=@dates,
																purchase_bill_no=@billno,
																purchase_rate=@rate,
																purchase_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																Flag_Type = 'Bought'
															WHERE  id = @tempSaleID  AND ISNULL(purchase_qty,0)=0 AND pkid = @pkid
														END
													if(@Sold_Qty > @purchase_Op_Qty )
														BEGIN
															UPDATE #MainOutputtable_1  
															SET	sold_qty = @purchase_Op_Qty 
															WHERE  id  = @tempSaleID AND Flag_Type_Sold='Sold' AND pkid = @pkid
														END

													DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND pkid = @pkid
													DECLARE @Balancedval   FLOAT = Round((ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)),6)
													SET @tablerowscount = (SELECT COUNT(*) FROM  #tempSoldValExists )
															 
													IF(@Balancedval  < 0)
														BEGIN
														--	SET @Pkid = (SELECT (MAX(ISNULL(pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId AND Broker_name = @Broker_name AND MemberName = @Member_Name)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															SET @soldQty=ABS(@Balancedval) 
															SET @prioritysId = (SELECT MAX(prioritys) FROM #MainOutputtable_1) 
															SET @prioritysId = ISNULL(@prioritysId,0) + 1
																	
															INSERT INTO #MainOutputtable_1(Dup_pkid, ID,Trans_No,ScriptCode, Flag_Type,Flag_Type_Sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,Broker_name,MemberCode,MemberName)
															VALUES(@Dup_pkid, @tempSaleID ,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Broker_name,@Member_Code,@Member_Name)
																	
															UPDATE #MainOutputtable_1 
															SET prioritys=@prioritysId+1  
															WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
															
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	
															IF(@idcount>0)
															BEGIN
																UPDATE #MainOutputtable_1 
																SET Dup_pkid = Dup_pkid + 1 
																WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																FROM Fn_split(@Pkid, ',') ) 
															END
															SET @Balancedval = 0

														BREAK;
														END
													ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
															BEGIN
																SET @Pkid = (SELECT (MAX(ISNULL(pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId AND Broker_name = @Broker_name AND MemberName = @Member_Name)
																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1
																SET @prioritysId = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
															
																IF(@TransType='Opening')
																	BEGIN
																		INSERT INTO #MainOutputtable_1(Dup_pkid, ID,Trans_No,ScriptCode, Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,Broker_name,MemberCode,MemberName)
																		VALUES(@Dup_pkid, @ID,@Trans_No,@ScriptId, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Broker_name,@Member_Code,@Member_Name)

																		UPDATE #MainOutputtable_1 
																		SET prioritys=@prioritysId+1  
																		WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	END
																ELSE IF(@TransType='Bought')
																	BEGIN
																		INSERT INTO #MainOutputtable_1(Dup_pkid, ID,Trans_No, ScriptCode, Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,Broker_name,MemberCode,MemberName)
																		VALUES(@Dup_pkid, @ID,@Trans_No,@ScriptId, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Broker_name,@Member_Code,@Member_Name)

																		UPDATE #MainOutputtable_1 
																		SET prioritys=@prioritysId+1  
																		WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	END
																		
																SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																IF(@idcount>0)
																	BEGIN
																		UPDATE #MainOutputtable_1 
																		SET Dup_pkid = Dup_pkid + 1 
																		WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																		FROM Fn_split(@Pkid, ',') ) 
																	END
																	ENd
														ELSE IF(@Balancedval=0)
															BEGIN
																break;
															END
													SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
													SET @qty = @Balancedval
												END
													

											DROP TABLE #tempSoldValExists
										END
									/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
									ELSE
										BEGIN
											
											
											SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
											SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)

											INSERT INTO #mainoutputtable_1 (Dup_pkid,id,Trans_No,ScriptCode, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,Broker_name,MemberCode,MemberName)
											VALUES ( ISNULL(@Dup_pkid,0),@ID,@Trans_No,@ScriptId, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Broker_name,@Member_Code,@Member_Name) 
										END
								END	
							ELSE IF(@TransType LIKE '%Sold%')
								BEGIN
								  
									/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
									SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Other') AND ISNULL(sold_qty,0)=0  AND isintradaycol=0  AND Broker_name=@Broker_name AND MemberName = @Member_Name)
									IF (@COUNT > 0)
									 	BEGIN
											DECLARE @Balanceval FLOAT
											SELECT  ROW_NUMBER ( ) OVER (ORDER BY  MemberName,Broker_name,scriptcode, holding_type,CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,
											* INTO #tempValExists 
											FROM
											#MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Other') 
											AND Broker_name= @Broker_name  
											AND MemberName = @Member_Name
											AND ISNULL(sold_qty,0)=0  AND isintradaycol=0 
											ORDER BY NameId
													
													
											DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
											DECLARE @TempSoldQty FLOAT 
											DECLARE @brokerName varchar(200)
										
											WHILE(@RCOUNT > 0 )
												BEGIN
													SET @Sold_Qty = @qty

													SET @tempID = (SELECT TOP(1) id FROM #tempValExists   ORDER BY Dup_pkid)
													SET @str = (SELECT TOP(1) Flag_Type FROM #tempValExists WHERE id  = @tempID)  
 													IF(@str='Opening')
														BEGIN
															SELECT	TOP(1)	@TempSoldQty	= opening_qty,
																			@openingDate	= opening_date,
																			@openingrate	= opening_rate,
																			@Pkid			= Pkid
															FROM #tempValExists 
															WHERE id  = @tempID
														END
													ELSE IF(@str='Bought')
														BEGIN
															SELECT	TOP(1)	@TempSoldQty	= purchase_qty,
																			@PurchaseDate	= purchase_date,
																			@Purchaserate	= purchase_rate,
																			@PurchaseBillNo = purchase_bill_no,
																			@Pkid			= Pkid
															FROM #tempValExists 
															WHERE id  = @tempID
														END

													IF(@Sold_Qty > 0)
														BEGIN
															SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
															SET @prioritysId = ISNULL(@prioritysId,0)+1
															UPDATE #MainOutputtable_1  
																SET	
																	opening_qty     = CASE WHEN @str ='Opening'
																						THEN 
																							CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																						ELSE 0
																						END,
																	purchase_qty    = CASE WHEN @str ='Bought'
																						THEN 
																							CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																						END,
																	sold_date       = @dates,
																	sold_bill_no    = @billno,
																	sold_rate       = @rate,
																	sold_qty        = CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																	Flag_Type_Sold  = 'Sold',
																	prioritys       = @prioritysId
															WHERE  id = @tempID AND ISNULL(sold_qty,0)=0 AND pkid = @Pkid
															SET @Balanceval = Round((ABS(@Sold_Qty) - ABS(@TempSoldQty)),6)
														END
														
												DELETE FROM #tempValExists WHERE id = @tempID AND Pkid=@Pkid
												SET @tablerowscount = (SELECT COUNT(*) FROM  #tempValExists )
												SET @RCOUNT = @RCOUNT - 1
															
												IF(@Balanceval  < 0)
													BEGIN
														--SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
														SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
														SET @Dup_pkid = ISNULL(@Dup_pkid,0)
														SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
														SET @Dup_pkid = @Dup_pkid + 1
																	 
																
														IF(@str='Opening')
															BEGIN
																SET @openingQty = ABS(@Balanceval) 
																SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																SET @prioritysId = ISNULL(@prioritysId,0)+1
																
																INSERT INTO #MainOutputtable_1(Dup_pkid,opening_bill_no, ID,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,Broker_name,MemberName,MemberCode)
																VALUES(@Dup_pkid,'Opening',@tempID,@Trans_No,@ScriptId, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Broker_name,@Member_Name,@Member_Code)

																SET @prioritysId = ISNULL(@prioritysId,0)+1
														
																UPDATE #MainOutputtable_1 
																SET prioritys=@prioritysId   
																WHERE prioritys >= @prioritysId AND ID <> @tempID
															END
														ELSE 
															BEGIN
																SET @PurchaseQty = ABS(@Sold_Qty) 
																SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																SET @prioritysId = ISNULL(@prioritysId,0)+1


																INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,Broker_name,MemberName,MemberCode)
																VALUES(@Dup_pkid,@tempID,@Trans_No,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Broker_name,@Member_Name,@Member_Code)
																
																SET @prioritysId = ISNULL(@prioritysId,0)+1
																			
																UPDATE #MainOutputtable_1 
																SET prioritys=@prioritysId    
																WHERE prioritys >= @prioritysId AND ID <> @tempID
															END
																	
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),1) FROM #MainOutputtable_1)) END)  
															IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
																SET @Balanceval = 0
														BREAK;
													END
												ELSE  IF(ISNULL(@Balanceval,0) > 0 and @tablerowscount=0)
													BEGIN	
														SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
														SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
														SET @Dup_pkid = ISNULL(@Dup_pkid,0)
														SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
														SET @Dup_pkid = @Dup_pkid + 1
														SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)

														INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,Broker_name,MemberName,MemberCode)
														VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Broker_name,@Member_Name,@Member_Code)
																
														UPDATE #MainOutputtable_1 
														SET prioritys=@prioritysId+1  
														WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
														SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	
														IF(@idcount>0)
															BEGIN
																UPDATE #MainOutputtable_1 
																SET Dup_pkid = Dup_pkid + 1 
																WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																FROM Fn_split(@Pkid, ',') ) 
															END
													END
													ELSE IF(ISNULL(@Balanceval,0) =0)
														BEGIN
															SET @Balanceval=0
															BREAK;
														END
													SET @qty = @Balanceval
							 				END
											DROP TABLE #tempValExists
										END
											
									/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
									ELSE
										BEGIN
											
											SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #MainOutputtable_1)
											SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0)+1 from #MainOutputtable_1)

											INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,Broker_name,MemberName,MemberCode)
											VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId,  'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Broker_name,@Member_Name,@Member_Code)
										END
									SET @purchase_Op_Date  = ''
									SET @purchase_Op_Rate  = ''
									SET @purchase_Op_Qty   = ''
									SET @purchase_Op_Bill  = ''
								END
						END
					IF(@isIntradayCol=1)
						BEGIN
							IF(@TransType LIKE '%Bought%')
								BEGIN
									/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
									--SELECT * FROM #MainOutputtable_1 --WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and ISNULL(Flag_Type,'')='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=1  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
										SET @COUNT = (	SELECT Count(*) 
													FROM #MainOutputtable_1 
													WHERE holding_type=@holding_type AND script_name=@scriptname 
													AND Flag_Type_Sold IN('Sold')  and  Flag_Type='Sold'
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) 
													AND isintradaycol=1 
													AND Broker_name = @Broker_name AND MemberName = @Member_Name)
									IF (@COUNT > 0)
										BEGIN
											SELECT  ROW_NUMBER ( ) OVER (ORDER BY MemberName,Broker_name,scriptcode, holding_type,CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,
											* INTO #tempBought 
											FROM
											#MainOutputtable_1 
											WHERE script_name=@scriptname AND holding_type=@holding_type  
											AND Broker_name = @Broker_name
											AND MemberName = @Member_Name
											AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
											AND Flag_Type_Sold ='Sold'  and  Flag_Type = 'Sold' AND isintradaycol=1
											ORDER BY NameId	
													 
											DECLARE @Bought_COUNT INT = ( SELECT COUNT(*) FROM #tempBought )
											DECLARE @Temppurchase_Qty FLOAT 
											SET @purchase_Op_Qty = @qty
											DECLARE @Balance_val FLOAT
											WHILE(@Bought_COUNT  > 0)
												BEGIN 
													DECLARE @tempSale_ID INT = (SELECT TOP(1) id FROM #tempBought ORDER BY Dup_pkid)
													SET @str=@TransType

													SELECT	@Temppurchase_Qty		= sold_qty,
															@soldDate				= sold_date,
															@soldRate				= sold_rate,
															@soldBillNo				= sold_bill_no,
															@pkid					= pkid
													FROM #tempBought 
													WHERE id  = @tempSale_ID 

													SET @Sold_Qty= ABS(@Temppurchase_Qty)
															 
													IF(@TransType='Bought')
														BEGIN
															UPDATE #MainOutputtable_1  
															SET	purchase_date=@dates,
																purchase_bill_no=@billno,
																purchase_rate=@rate,
																purchase_qty= CASE	WHEN @Temppurchase_Qty > @purchase_Op_Qty 
																					THEN ABS(@purchase_Op_Qty) 
																					ELSE ABS(@Temppurchase_Qty) 
																				END,
																Flag_Type='Bought'
															WHERE  id = @tempSale_ID  and pkid=@pkid
														END
													IF(@Temppurchase_Qty > @purchase_Op_Qty )
														BEGIN
															UPDATE #MainOutputtable_1  
															SET sold_qty = ABS(@purchase_Op_Qty) 
															WHERE Flag_Type_Sold = 'Sold' 
															AND   id = @tempSale_ID   and pkid=@pkid
														END
															
													DELETE FROM #tempBought  WHERE id = @tempSale_ID 
													SET @Balance_val = Round((isnull(@purchase_Op_Qty,0) - (@Sold_Qty)),6)
													SET @tablerowscount = (SELECT COUNT(*) FROM  #tempBought)
															
													SET @Bought_COUNT  = @Bought_COUNT  - 1
													SET @qty = @Balance_val

													IF(@Balance_val  < 0)
														BEGIN
															--SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId AND Broker_Name = @Broker_Name AND MemberName = @Member_Name)-- AND ID = @ID)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															SET @soldQty = ABS(@Balance_val) 
															SET @prioritysId  =(SELECT MAX(prioritys) FROM #MainOutputtable_1 )--WHERE id=@tempSale_ID )
															SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
															INSERT INTO #MainOutputtable_1(Dup_pkid,ID, Trans_No,ScriptCode, Flag_Type,Flag_Type_Sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,Broker_Name,MemberName,MemberCode)
															VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Sold', 'Sold', @prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balance_val),@soldRate,@isIntradayCol,@Broker_Name,@Member_Name,@Member_Code)
																	
															UPDATE #MainOutputtable_1 
															SET prioritys=@prioritysId+1  
															WHERE prioritys >= @prioritysId AND ID<>@tempSale_ID 
																
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	
															IF(@idcount>0)
																BEGIN
 																	UPDATE #MainOutputtable_1
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																	FROM Fn_split(@Pkid, ',') ) 
																END

															BREAK;
														END
													ELSE IF(@Balance_val  > 0 and @tablerowscount = 0)
														BEGIN
															IF(@TransType='Bought')
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId AND Broker_Name = @Broker_Name AND MemberName = @Member_Name)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																			
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type,Flag_Type_Sold,  prioritys,  script_name,holding_type,purchase_bill_no, purchase_date,purchase_qty,purchase_rate,isintradaycol,Broker_Name,MemberName,MemberCode)
																	VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Bought','Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balance_val),@rate,@isIntradayCol,@Broker_Name,@Member_Name,@Member_Code)
																			
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																			
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   
																			CONVERT(VARCHAR(200),pkid) NOT IN ( SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																END
														ENd
													SET @purchase_Op_Qty= (@Balance_val)
												END

													
											DROP TABLE #tempBought
										END
									/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
									ELSE
										BEGIN
											
											SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
											SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0) + 1 from #mainoutputtable_1)

											INSERT INTO #mainoutputtable_1 (Dup_pkid,id,Trans_No,ScriptCode, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,Broker_name,MemberName,MemberCode) 
										VALUES ( @Dup_pkid,@ID,@Trans_No,@ScriptId, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Broker_name,@Member_Name,@Member_Code) 
										END
								END	
							ELSE IF(@TransType LIKE '%Sold%')
								BEGIN
									/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
									SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split') AND ISNULL(sold_qty,0)=0  AND isintradaycol=1 
													AND Broker_name= @Broker_name--(CASE WHEN @BrokerCode <>'' THEN @Broker_name ELSE Broker_name END)
													AND MemberName = @Member_Name)
									IF (@COUNT > 0)
									 	BEGIN
											DECLARE @Balanceval_sold FLOAT
											SELECT  ROW_NUMBER ( ) OVER (ORDER BY  Broker_name,scriptcode, holding_type,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
											* INTO #tempSold 
											FROM #MainOutputtable_1 
											WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split') AND 
											Broker_name= @Broker_name--(CASE WHEN @BrokerCode <>'' THEN @Broker_name ELSE Broker_name END)
											AND MemberName = @Member_Name
											AND ISNULL(sold_qty,0)=0  AND isintradaycol=1 
											ORDER BY NameId
													
											DECLARE @RSoldCOUNT INT = (SELECT COUNT(*) FROM #tempSold)
											DECLARE @TempQty_Sold FLOAT 
												    
											WHILE(@RSoldCOUNT > 0 )
												BEGIN 
													SET @Sold_Qty = @qty
													SET @tempID  =   (SELECT TOP(1) id FROM #tempSold)
													SET @str     =   (SELECT TOP(1) Flag_Type FROM #tempSold WHERE id = @tempID  ORDER BY Dup_pkid,NameId)
													SET @pkid    =   (SELECT TOP(1) pkid  FROM #tempSold WHERE id  = @tempID )
															
													IF(@str='Bought')
														BEGIN
															SELECT	@TempQty_Sold	=	purchase_qty,
																	@PurchaseDate	=	purchase_date,
																	@Purchaserate	=	purchase_rate,
																	@PurchaseBillNo	=	purchase_bill_no
															FROM #tempSold 
															WHERE id  = @tempID 
														END
													IF(@Sold_Qty > 0)
														BEGIN
															SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
															SET @prioritysId = ISNULL(@prioritysId,0)+1
															UPDATE #MainOutputtable_1  
																SET	
																	purchase_qty  = CASE WHEN @str ='Bought'
																							THEN CASE	WHEN  @TempQty_Sold >= @Sold_Qty 
																									THEN @Sold_Qty 
																									ELSE @TempQty_Sold 
																								END
																						END,
																	sold_date      = @dates,
																	sold_bill_no   = @billno,
																	sold_rate      = @rate,
																	sold_qty       = CASE WHEN @TempQty_Sold > @Sold_Qty THEN @Sold_Qty ELSE @TempQty_Sold END,
																	Flag_Type_Sold = 'Sold',
																	prioritys      = @prioritysId
															WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND pkid = @pkid
															SET @Balanceval_sold = Round((ABS(@Sold_Qty) - ABS(@TempQty_Sold)),6)
														END
															
													DELETE FROM #tempSold WHERE id = @tempID
													SET @RSoldCOUNT = @RSoldCOUNT - 1
													SET @tablerowscount = (SELECT COUNT(*) FROM  #tempSold)
														
													IF(@Balanceval_sold < 0)
														BEGIN
														--	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId AND Broker_Name = @Broker_Name AND MemberName = @Member_Name)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															SET @PurchaseQty=ABS(@Sold_Qty) 
															SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
															SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
															INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,Broker_name,MemberCode,MemberName)
															VALUES(@Dup_pkid,@tempID,@Trans_No,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval_sold)  ,@Purchaserate,@isIntradayCol,@Broker_name,@Member_Code,@Member_Name)
																	
															SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
															UPDATE #MainOutputtable_1 
															SET prioritys=@prioritysId    
															WHERE prioritys >= @prioritysId AND ID <> @tempID
																	
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
															IF(@idcount>0)
																BEGIN
																		UPDATE #MainOutputtable_1 
																		SET Dup_pkid = Dup_pkid + 1 
																		WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
															BREAK;
														END
													ELSE IF(ISNULL(@Balanceval_sold,0) > 0 AND @tablerowscount=0)
														BEGIN
															SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId AND Broker_Name = @Broker_Name AND MemberName = @Member_Name)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)

															INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No, ScriptCode, Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,Broker_name,MemberCode,MemberName)
															VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval_sold)  ,@rate,@isIntradayCol,@Broker_name,@Member_Code,@Member_Name)

															UPDATE #MainOutputtable_1 
															SET prioritys=@prioritysId+1  
															WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
															IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1 
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
														END
													SET @qty = @Balanceval_sold
												END	
											DROP TABLE #tempSold
										END
											
									/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
									ELSE
										BEGIN
										
											SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
											SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0) +1 from #mainoutputtable_1)


											INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,Broker_name,MemberCode,MemberName)
											VALUES(ISNULL(@Dup_pkid,0),@ID, @Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Broker_name,@Member_Code,@Member_Name)
										END
											
									SET @purchase_Op_Date	=	''
									SET @purchase_Op_Rate	=	''
									SET @purchase_Op_Qty	=	''
									SET @purchase_Op_Bill	=	''
								END

						END
					FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Broker_name,@Member_Code,@Member_Name
				END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 
		--select * from #mainoutputtable_1 --order by Dup_pkid
		IF(@IsIntraDay = 0 AND @short_Long_Term != 0  )
			BEGIN
				IF(@short_Long_Term = 1)  -- Long Term
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate, sort,isintradaycol,MemberCode,MemberName )

						SELECT  ROW_NUMBER ( ) OVER (ORDER BY  MemberName,broker_name, ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN   CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
							 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId, opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						0,
						Round(ISNULL( CASE 	WHEN  isintradaycol = 0 AND opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
											WHEN  isintradaycol = 0 AND purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4),
						0,
						0,
						0,
						Broker_name,nse_rate,bse_rate,1 sort ,isintradaycol,
						MemberCode,MemberName 
						FROM #mainoutputtable_1 
						WHERE (@IsFromMonthWise = 1 OR ISNULL(closing_qty,0) = 0)  
						AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
									(
										DATEDIFF(DAY,CONVERT(DATETIME,opening_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) > 365 
									)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									(
										DATEDIFF(DAY,CONVERT(DATETIME, purchase_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) > 365
									)
								)
							)
						order by NameId
					END

				ELSE If(@short_Long_Term = 2)  -- Short Term
					BEGIN

						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no, id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss , closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate, sort,isintradaycol,MemberCode,MemberName  )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  MemberName , broker_name,ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4) as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						Round(ISNULL(
								CASE	WHEN  isintradaycol = 0 AND opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN  isintradaycol = 0 AND purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4),
						0,
						0,
						0,
						0,Broker_name,nse_rate,bse_rate,1 sort,isintradaycol ,
						MemberCode,MemberName 
						FROM #mainoutputtable_1 
						WHERE  (@IsFromMonthWise = 1 OR ISNULL(closing_qty,0) = 0)  
						 AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
										(		
											DATEDIFF(DAY,CONVERT(DATETIME,opening_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) <= 365 
										)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									  (		
										DATEDIFF(DAY,CONVERT(DATETIME, purchase_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) <= 365
									  )
								)
							)
						order by NameId
					END

				ELSE If(@short_Long_Term = 4)  -- Short Term + Long Term
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate, sort,isintradaycol,MemberCode,MemberName  )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  MemberName, broker_name,ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						
						opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						 Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) <= 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) <= 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						(CASE   WHEN  isintradaycol = 0 AND ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
								    (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
							  THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						
						(CASE WHEN  isintradaycol = 0 AND ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365) OR
								   (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365))  
							  THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,Broker_name,nse_rate,bse_rate,1 sort,isintradaycol
						,MemberCode,MemberName  
						FROM #mainoutputtable_1 
						WHERE  (@IsFromMonthWise = 1 OR ISNULL(closing_qty,0) = 0)  
						 AND ISNULL(isintradaycol,0)=0
						order by NameId
					END
                ELSE If(@short_Long_Term = 5)  -- Without Sepeculation
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate, sort,isintradaycol,MemberCode,MemberName  )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  MemberName, broker_name,ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						
						opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						 Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) <= 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) <= 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						(CASE   WHEN  isintradaycol = 0 AND ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
								    (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
							  THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						
						(CASE WHEN  isintradaycol = 0 AND ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365) OR
								   (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365))  
							  THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,Broker_name,nse_rate,bse_rate,1 sort,isintradaycol
						,MemberCode,MemberName  
						FROM #mainoutputtable_1 
						WHERE  ISNULL(isintradaycol,0)=0
						order by NameId
					END
			END

		ELSE If(@short_Long_Term = 3 AND @IsIntraDay = 1 )  -- Only Speculation
			BEGIN
				INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate, sort,isintradaycol,MemberCode,MemberName   )

				SELECT  ROW_NUMBER ( ) OVER (ORDER BY  MemberName,broker_name,ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						
						opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
				ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),purchase_date,ISNULL(purchase_bill_no,0),
				ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,sold_date ,sold_bill_no ,isnull(sold_qty,0) ,
				ISNULL(sold_rate,0),ISNULL(sold_amount,0) ,
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4) as gain_loss,
				
				closing_qty ,closing_rate ,closing_value ,
				0,
				0,
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4) ,
				0,
				0,Broker_name,nse_rate,bse_rate,1 sort,isintradaycol 
				,MemberCode,MemberName  
				FROM #mainoutputtable_1 
				WHERE  (ISNULL(closing_qty,0) = 0)  AND (ISNULL(isintradaycol,0)=1) AND (ISNULL(purchase_qty,0)! = 0 AND  ISNULL(sold_qty,0) ! = 0) 
				order by NameId
			END

		ELSE
			BEGIN			
				INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate, sort,isintradaycol,MemberCode,MemberName   )

				SELECT  
				ROW_NUMBER ( ) OVER (ORDER BY  MemberName, broker_name,holding_type,ScriptCode,--pkid,
				 case  WHEN  Dup_pkid is Null Then Pkid
				       WHEN  Dup_pkid is NOt Null then Dup_pkid 
				       ELSE Dup_pkid end,prioritys,			
                 Case  WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					   WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					   ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,

				opening_bill_no,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,opening_date,
				ISNULL(opening_qty ,0),ISNULL(opening_Rate,0),ISNULL(opening_amount,0),purchase_date,purchase_bill_no,
				ISNULL(purchase_qty,0) ,ISNULL(purchase_rate ,0),ISNULL(purchase_amount ,0),sold_date ,sold_bill_no ,ISNULL(sold_qty ,0),
				ISNULL(sold_rate,0),ISNULL(sold_amount ,0),
				    Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) > 365   --short term for openings
									THEN  ISNULL(sold_rate,0) * ISNULL(sold_qty,0) - ISNULL(opening_rate,0) * ISNULL(opening_qty,0)
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) <= 365 --short term for purchase
									THEN  ISNULL(sold_rate ,0)* ISNULL(sold_qty,0) - ISNULL(purchase_rate,0) * ISNULL(purchase_qty  ,0)--long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, opening_rate, ISNULL(sold_rate,0), CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), ISNULL(opening_qty,0), ISNULL(sold_qty,0))) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,script_name, @BSE_NSE_Code, purchase_rate, ISNULL(sold_rate,0), CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), ISNULL(purchase_qty,0), ISNULL(sold_qty,0))) 
				
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				  ISNULL(closing_qty,0) ,ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
				CASE WHEN isintradaycol = 0 AND  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365)     -- short term for openings
						THEN  ISNULL(sold_rate ,0)* ISNULL(sold_qty ,0)- ISNULL(opening_rate,0)*ISNULL(opening_qty ,0)
					 WHEN isintradaycol = 0 AND (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365)  -- short term for purchase
						THEN  ISNULL(sold_rate ,0)* ISNULL(sold_qty ,0)- ISNULL(purchase_rate,0)*ISNULL(purchase_qty ,0)
					 ELSE 0.0 END,

						
				CASE WHEN  isintradaycol = 0 AND ((opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)     --long term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365))  --long term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, ISNULL(opening_rate,0), ISNULL(sold_rate,0), CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, ISNULL(purchase_rate,0),ISNULL( sold_rate,0), CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  isintradaycol = 1 AND (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				Broker_name,nse_rate,bse_rate,1 sort,isintradaycol
				,MemberCode,MemberName    
				FROM #mainoutputtable_1 
				order by NameId
			END
				UPDATE #mainoutputtable_1_Final SET prioritys=0
				DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
				UPDATE #mainoutputtable_1_Final
				SET prioritys  = @i , @i = @i + 1

				--Select * from #mainoutputtable_1
		IF(@OUTPUT_Flag='Details')
			BEGIN
				IF(@Investmenttype != 2)
					BEGIN
						SELECT id,prioritys,ScriptCode,script_name 'Script Name',Holding_Type,Holding_Type as flag_Holding_Type,Broker_name,opening_bill_no, CONVERT(DATETIME, opening_date,101) 'Opening Date',
						ISNULL(opening_qty,2) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(DATETIME, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(DATETIME, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',ISNULL(gain,0) 'Gain',ISNULL(loss,0) 'Loss',ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND gain!=0 THEN gain  ELSE 0 END gain_speculation,CASE WHEN isintradaycol=1 AND loss!=0  THEN loss  ELSE 0 END loss_speculation,
						ISNULL(nse_rate,0) nse_rate , ISNULL(bse_rate,0)bse_rate ,isintradaycol ,1 sort 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  OR purchase_qty != 0  or sold_qty != 0)  
						order by Broker_name,script_name,Holding_Type
						
					END
				ELSE
					BEGIN
						SELECT id,prioritys,ScriptCode,script_name 'Script Name',Holding_Type,opening_bill_no,CONVERT(DATE, opening_date,103) 'Opening Date',
						ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',
						ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',
						ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',ISNULL(gain,0) 'Gain',ISNULL(loss,0) 'Loss',ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0)!=0 THEN gain  ELSE '0' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0)!=0  THEN loss  ELSE '0' END loss_speculation,Broker_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),ISNULL(isintradaycol,0),1 sort 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  OR purchase_qty != 0  or sold_qty != 0)  
						ORDER BY  id,Broker_name,script_name,Holding_Type
					END
			END
		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
				SELECT  0 id ,  0 prioritys,'' opening_bill_no, '' ScriptCode,script_name 'Script Name',  Holding_Type,
				NULL 'Opening Date', SUM(opening_qty) 'Opening Qty', 
				CASE WHEN SUM(opening_qty) != 0
					 THEN SUM(opening_amount)/ NULLIF(SUM(opening_qty),0)  
					 ELSE 0
				END  'Opening Rate', 
				SUM(opening_amount) 'Opening Amount',
				NULL 'Purchase Date','' AS 'Purchase BillNo', SUM(purchase_qty)  'Purchase Qty', 
				SUM(ISNULL(purchase_amount,0))  / nullif(SUM(ISNULL(purchase_qty,0)),0) 'Purchase Rate', SUM(purchase_amount)  'Purchase Amount',
				NULL 'Sold Date', '' AS 'Sold BillNo', SUM(sold_qty) 'Sold Qty', 
				CASE WHEN SUM(sold_qty) != 0
					 THEN SUM(sold_amount)/nullif(SUM(sold_qty),0)   
					 ELSE 0
				END  'Sold Rate',
				SUM(sold_amount) 'Sold Amount', SUM(gain_loss ) 'Gain/Loss', SUM(gain)  'Gain', SUM(loss)  'Loss',
				SUM(closing_qty)  'Closing Qty', 

				CASE WHEN SUM(closing_qty) != 0
					 THEN (SUM(closing_value) / SUM(NULLIF(closing_qty,0))) 
					 ELSE 0
				END  'Closing Rate',
				SUM(closing_value)  'Closing Value', SUM(short_term)  as short_term, SUM(long_term) as long_term,
				SUM(speculation) as speculation, SUM(gain_speculation)gain_speculation, SUM(loss_speculation)loss_speculation,   Broker_name,0 nse_rate,0 bse_rate,1 sort --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
				FROM
					(
						SELECT MAX(id+0)id ,MAX (prioritys+0) prioritys,'' opening_bill_no,'' ScriptCode, script_name,   Holding_Type,'' 'Opening Date',SUM(opening_qty) 'Opening_Qty',sum(opening_rate) opening_rate ,SUM(opening_amount) 'Opening_Amount',
						'' 'Purchase Date','' purchase_bill_no,SUM(ISNULL(purchase_qty,0)) 'Purchase_Qty', SUM(ISNULL(purchase_rate,0)) purchase_rate,SUM(ISNULL(purchase_amount,0)) 'Purchase_Amount',
						'' 'Sold Date',sold_bill_no ,SUM(sold_qty) 'Sold_Qty', SUM(sold_rate)sold_rate  , SUM(sold_amount) 'Sold_Amount',SUM(gain_loss) 'Gain_Loss',SUM(gain) 'Gain',SUM(loss) 'Loss',
						SUM(ISNULL(closing_qty,0)) 'Closing_Qty',SUM(ISNULL(closing_rate,0)) 'Closing_Rate',SUM(ISNULL(closing_value,0)) 'Closing_Value',
						sum(ISNULL(short_term,0)) as short_term,
						sum(ISNULL(long_term,0)) as long_term,
						sum(ISNULL(speculation,0)) as speculation,
						SUM(ISNULL(gain_speculation,0)) gain_speculation,SUM(ISNULL(loss_speculation,0)) loss_speculation,  Broker_name,0 nse_rate,0 bse_rate,1 sort --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
						FROM #mainoutputtable_1_Final 
						GROUP BY Broker_name,script_name, Holding_Type,purchase_bill_no,sold_bill_no ,opening_date,purchase_date,sold_date,isintradaycol
					)a
					GROUP BY  Broker_name,script_name ,Holding_Type 						 
					ORDER BY  Broker_name,Holding_Type ,script_name,sort
			 END

		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN		
				SELECT  ISNULL(prioritys,0)As'prioritys' ,Trans_No,ScriptCode,0 id ,MemberCode as'MemberCode',@yearcode As'yearcode', script_name ,Holding_Type,script_name flag_script_name,
				Holding_Type flag_Holding_Type,
				CONVERT(date, opening_date,103)As 'opening_date',ISNULL(opening_qty ,0) As'opening_qty',ISNULL(opening_Rate,0)As'opening_Rate',ISNULL(opening_amount,0)As'opening_amount',
				CONVERT(date, purchase_date,103)As'purchase_date',purchase_bill_no as'purchase_bill_no',ISNULL(purchase_qty ,0)As'purchase_qty',ISNULL(purchase_rate ,0)As'purchase_rate',ISNULL(purchase_amount ,0)As'purchase_amount',
				CONVERT(date, sold_date,103)As'sold_date' ,sold_bill_no as'sold_bill_no' ,ISNULL(sold_qty ,0)As'sold_qty',
				ISNULL(sold_rate,0)As'sold_rate',ISNULL(sold_amount ,0)As'sold_amount',ISNULL(gain_loss ,0)As'gain_loss',ISNULL(gain ,0)As'gain',ISNULL(loss,0)As'loss',ISNULL(closing_qty ,0)As'closing_qty',
				ISNULL(closing_rate ,0)As'closing_rate',ISNULL(closing_value ,0)As'closing_value',
				ISNULL(short_term,0)As'short_term',ISNULL(long_term,0)As'long_term',ISNULL(speculation,0)As'speculation',ISNULL(gain_speculation,0)As'gain_speculation',ISNULL(loss_speculation,0)As'loss_speculation',Broker_name as'Broker_name',
				ISNULL(nse_rate,0)As'nse_rate',
				ISNULL(bse_rate,0)As'bse_rate',0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol
				
				FROM #mainoutputtable_1_Final
				ORDER BY MemberCode,Broker_name,script_name,CONVERT(date, purchase_date,103)--,holding_type
			END
		ELSE IF(@OUTPUT_Flag='Annexture')
			BEGIN
				SELECT	'' opening_bill_no,
						0 id,
						0 prioritys,
						ScriptCode,
						'' 'Family_Name',
						MemberName 'Member_Name',
						'' 'Family_Code',
						MemberCode 'Member_Code',
						script_name 'Script Name',  
						Holding_Type,
						NULL 'Opening Date', 
						SUM(opening_qty) 'Opening Qty', 
						CASE WHEN SUM(opening_qty) != 0
							 THEN SUM(opening_amount)/ NULLIF(SUM(opening_qty),0)  
							 ELSE 0
						END  'Opening Rate', 
						SUM(opening_amount) 'Opening Amount',
						NULL 'Purchase Date',
						'' AS 'Purchase BillNo', 
						SUM(purchase_qty)  'Purchase Qty', 
						SUM(ISNULL(purchase_amount,0))  / nullif(SUM(ISNULL(purchase_qty,0)),0) 'Purchase Rate', 
						SUM(purchase_amount)  'Purchase Amount',
						NULL 'Sold Date', 
						'' AS 'Sold BillNo', 
						SUM(sold_qty) 'Sold Qty', 
						CASE	WHEN SUM(sold_qty) != 0
								THEN SUM(sold_amount)/nullif(SUM(sold_qty),0)   
								ELSE 0
						END  'Sold Rate',
						SUM(sold_amount) 'Sold Amount', 
						SUM(gain_loss ) 'Gain/Loss', 
						SUM(gain)  'Gain', 
						SUM(loss)  'Loss',
						SUM(closing_qty)  'Closing Qty', 
						CASE  WHEN SUM(closing_qty) != 0
							  THEN (SUM(closing_value) / SUM(NULLIF(closing_qty,0))) 
							  ELSE 0
						END  'Closing Rate',
						SUM(closing_value)  'Closing Value', 
						SUM(short_term)  as short_term, 
						SUM(long_term) as long_term,
						SUM(speculation) as speculation, 
						SUM(gain_speculation)gain_speculation, 
						SUM(loss_speculation)loss_speculation,   
						'' consultant_name, 
						0 nse_rate,
						0 bse_rate,
						1 sort,
						broker_code 
						
				FROM
					(
						SELECT MAX(id+0)id ,MAX (prioritys+0) prioritys,'' opening_bill_no,ScriptCode, script_name,   Holding_Type,'' 'Opening Date',SUM(opening_qty) 'Opening_Qty',sum(opening_rate) opening_rate ,SUM(opening_amount) 'Opening_Amount',
						'' 'Purchase Date','' purchase_bill_no,SUM(ISNULL(purchase_qty,0)) 'Purchase_Qty', SUM(ISNULL(purchase_rate,0)) purchase_rate,SUM(ISNULL(purchase_amount,0)) 'Purchase_Amount',
						'' 'Sold Date',sold_bill_no ,SUM(sold_qty) 'Sold_Qty', SUM(sold_rate)sold_rate  , SUM(sold_amount) 'Sold_Amount',SUM(gain_loss) 'Gain_Loss',SUM(gain) 'Gain',SUM(loss) 'Loss',
						SUM(ISNULL(closing_qty,0)) 'Closing_Qty',SUM(ISNULL(closing_rate,0)) 'Closing_Rate',SUM(ISNULL(closing_value,0)) 'Closing_Value',
						sum(ISNULL(short_term,0)) as short_term,
						sum(ISNULL(long_term,0)) as long_term,
						sum(ISNULL(speculation,0)) as speculation,
						SUM(ISNULL(gain_speculation,0)) gain_speculation,SUM(ISNULL(loss_speculation,0)) loss_speculation,  Broker_name,0 nse_rate,0 bse_rate,1 sort,MemberCode,MemberName,
						MA.AC_Code as 'broker_code'
						FROM #mainoutputtable_1_Final F
						LEFT JOIN MST_Account MA ON MA.AC_Name = F.Broker_name AND MA.Member_Code in (SELECT Value FROM membercodestable(@memcode,','))  AND MA.Year_Code = @yearcode
						GROUP BY MemberCode,MemberName,Broker_name,ScriptCode,script_name, Holding_Type,purchase_bill_no,sold_bill_no ,opening_date,purchase_date,sold_date,isintradaycol,MA.AC_Code,MA.AC_Name
					)a
					GROUP BY  a.MemberCode,a.MemberName,a.broker_code,Broker_name,a.ScriptCode,script_name ,Holding_Type
					ORDER BY  MemberName,Broker_name,Holding_Type ,script_name,sort
			END
		ELSE IF(@OUTPUT_Flag='ClosingStocks')
			BEGIN
				SELECT  id,
						Trans_No ,
						script_name,
						ScriptCode,
						Holding_Type,
						CASE
							WHEN ISNULL(closing_qty,0) < 0		 THEN sold_bill_no
							WHEN ISNULL(opening_date,'') != ''   THEN 'Opening'
							WHEN ISNULL(purchase_date,'') != ''  THEN  purchase_bill_no
							ELSE ''
						END  AS  'bill_no',
						CASE
							WHEN ISNULL(closing_qty,0) < 0		THEN CONVERT(DATE,sold_date,101)
							WHEN ISNULL(opening_date,'') != ''	THEN  CONVERT(DATE,opening_date,101)
							WHEN ISNULL(purchase_date,'') != '' THEN CONVERT(DATE,purchase_date,101)
						END  AS  'trans_dt',
						ABS(ISNULL(closing_qty,0)) 'Qty',
						ISNULL(closing_rate,0) 'rate',
						ISNULL(closing_value,0) 'amount',
						isintradaycol,
						Broker_Name,
						MemberCode,
						MemberName,
						CASE
							WHEN ISNULL(closing_qty,0)    < 0		THEN 'Sold'
							WHEN ISNULL(opening_date,'')  != ''		THEN 'Opening'
							WHEN ISNULL(purchase_date,'') != ''		THEN 'Bought'
							ELSE ''
						END  AS  'Type'
				from #mainoutputtable_1_Final 
				WHERE ISNULL(closing_qty,0) <> 0
				ORDER BY  trans_dt,Trans_No			
			
			END

		DROP TABLE #mainoutputtable_1 
		 
		DROP TABLE #alldata 
 
  END  











































GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_BrokerWise_Equity_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_BrokerWise_Equity_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_StockholdingPosition_BrokerWise_Equity_Summary] AS' 
END
GO





--Execute  proc_StockholdingPosition_BrokerWise_Equity_Summary    0,0,'0','Y0001','1120172018','2015-02-01 12:00:00:00','2018-03-28 03:50:37:50','','','0','', '0' ,'0',0,0,0,0,1
--Execute  proc_Stockholdingposition_Equity_Summary    0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0',1,1,1
ALTER PROCEDURE [dbo].[proc_StockholdingPosition_BrokerWise_Equity_Summary]  --''
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(MAX),@BrokerCode  VARCHAR(MAX),@BSE_NSE_Code VARCHAR(MAX),@Is_BFCF VARCHAR(MAX),@IsIntraDay VARCHAR(MAX),@short_Long_Term INT,
@RecordOnlyhavingClosingbalanceZero AS BIT,@WithActualAvgRate AS BIT, @DateWiseClosinStock AS BIT,@IsWithTax bit = 0,@IsAdvisory bit=0)
AS
BEGIN
SET NOCOUNT ON;
		Declare @Invested_Amount Float

	    SELECT MA.Ac_Code,MA.AC_Name,Sum(At.Amount) as 'Amount'
		into #BrokerTotal
		FROM Ac_Trans AT
		Inner Join  Mst_Account MA
		ON AT.Dr_Code =MA.Ac_Code And MA.Member_Code=At.Member_Code and Ma.Year_Code=At.Year_Code and Ma.Grp_Name='BROKER'
		WHERE At.Member_Code=@memcode and AT.Year_Code=@yearcode and At.Book_Type1='BK' and At.Sub_Type2='P'  
		and At.Dr_Code=MA.Ac_Code
		Group By At.Dr_Code,MA.Ac_Code,MA.AC_Name

		Select @Invested_Amount = sum(Amount) from #BrokerTotal

		--Select * from #BrokerTotal

		

		CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
           prioritys INT,Trans_No VARCHAR(50),ScriptCode  VARCHAR(50),id INT,MemberCode varchar(20),yearcode varchar(50), script_name  VARCHAR(500),holding_type VARCHAR(200),flag_script_name  VARCHAR(500),flag_holding_type VARCHAR(200),
           opening_date VARCHAR(50),opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
           purchase_date VARCHAR(50),purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
           sold_date VARCHAR(50),sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   Broker_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   Other_amt FLOAT DEFAULT 0,
		   ServTax_Amt FLOAT DEFAULT 0,
		   Stt_amt FLOAT DEFAULT 0,
		   sort   VARCHAR(5),
		   isintradaycol  INT 
        ) 

		INSERT INTO #mainoutputtable_1_Final_Summary
		EXEC proc_StockholdingPosition_BrokerWise_Equity   @status,@Investmenttype,@Ac_Type,@memcode,@yearcode,@Fromdate,@Todate,@ScriptCode,@BrokerCode,@BSE_NSE_Code,@Is_BFCF,@IsIntraDay,@short_Long_Term,'ALLData',@IsWithTax
		
		

		SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
		T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
		T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
		T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
		T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
		T1.Broker_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,   

		ISNULL( Dr.BSE_Rate ,0) AS 'bse_rate', /**/
		ISNULL(Dr.BSE_Rate,0)  AS 'nse_rate' /**/
		
		INTO #alldata_Summary 
		FROM #mainoutputtable_1_Final_Summary  T1
		LEFT JOIN BrokerBill T2 ON T2.Trans_No=T1.Trans_no AND T2.Member_Code=T1.MemberCode AND T2.YearCode=T1.MemberCode
		LEFT JOIN DailyRate DR ON DR.Script_Code = T1.ScriptCode  and Dr.Trans_Dt = @Todate /**/
		ORDER BY Broker_name
		
		--Select * from #alldata_Summary
		TRUNCATE TABLE #mainoutputtable_1_Final_Summary

		INSERT INTO #mainoutputtable_1_Final_Summary ( id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		Broker_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt) 

		SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,ISNULL(opening_qty,0),ISNULL(opening_rate,0),ISNULL(opening_amount,0),
		purchase_date,purchase_bill_no,ISNULL(purchase_qty,0),ISNULL(purchase_rate,0),ISNULL(purchase_amount,0),
		sold_date,sold_bill_no,ISNULL(sold_qty,0),ISNULL(sold_rate,0),ISNULL(sold_amount,0),ISNULL(gain_loss,0),ISNULL(gain,0),ISNULL(loss,0),
		ISNULL(closing_qty,0),ISNULL(closing_rate,0),ISNULL(closing_value,0),ISNULL(short_term,0),ISNULL(long_term,0),ISNULL(speculation,0),ISNULL(gain_speculation,0),ISNULL(loss_speculation,0),
		Broker_name,
		Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
		sort,isintradaycol,ISNULL(Other_amt,0),ISNULL(ServTax_Amt,0),ISNULL(Stt_amt ,0)
		FROM #alldata_Summary  


		GROUP BY Broker_name,id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 
		ORDER BY Broker_name

		Declare @Market_Amount Float
	    SELECT @Market_Amount= Round(bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)),2)
		FROM #mainoutputtable_1_Final_Summary 
		Group By bse_rate

		--print @Market_Amount
		
		IF(@IsAdvisory=1)
		BEGIN
			IF(@BrokerCode = '')
				BEGIN
					SELECT holding_type,
					script_name 'Script Name',
					SUM(closing_qty) AS 'Closing Qty', 
					ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate',
					ROUND(SUM(closing_value),4) AS 'Total Cast of Holding',
					ROUND((ROUND(SUM(closing_value),4)/ISNull (@Invested_Amount,1)) * 100,4)  AS '% Of AUA',
					bse_rate  AS  'CMP',
					bse_rate * SUM(closing_qty)  AS  'MARKET VALUES',
					Round(bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)),4)    AS  'GAIN',

					ROUND(IsNULL(bse_rate * SUM(closing_qty),1) /(ISNull (@Market_Amount,1)) * 100,4) AS '%  of Total Portfolio',			
					(Round(((IsNull (bse_rate,0)/ ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0))-1)*100,4))AS 'Gain(%)',
					Broker_name
								 		
					FROM #mainoutputtable_1_Final_Summary
					GROUP BY Broker_name,holding_type,script_name,bse_rate,nse_rate 
					HAVING SUM(closing_qty) != 0
				END
			ELSE
				BEGIN
					SELECT holding_type,
					script_name 'Script Name',
					SUM(closing_qty) AS 'Closing Qty', 
					ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate',
					ROUND(SUM(closing_value),4) AS 'Total Cast of Holding',
					ROUND(ROUND(SUM(closing_value),4)/(Select ISNULL(Amount,1) from  #BrokerTotal Where AC_Name = Ms.Broker_name) * 100,4)  AS '% Of AUA',
					bse_rate  AS  'CMP',
					bse_rate * SUM(closing_qty)  AS  'MARKET VALUES',
					Round(bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)),4)    AS  'GAIN',

					ROUND(IsNULL(bse_rate * SUM(closing_qty),1) /(ISNull (@Market_Amount,1)) * 100,4) AS '%  of Total Portfolio',			
					(Round(((IsNull (bse_rate,0)/ ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0))-1)*100,4))AS 'Gain(%)',
					Broker_name
					FROM #mainoutputtable_1_Final_Summary MS
					GROUP BY Broker_name,holding_type,script_name,bse_rate,nse_rate 
					HAVING SUM(closing_qty) != 0
				END
								
				Select
				 CASE WHEN  Sum(gain_loss)>0 THEN  (Sum(gain_loss)-Sum(closing_value)) ELSE (Sum(gain_loss) + Sum(closing_value))                          
							END AS 'PurchaseSaleValue'
      				    from #mainoutputtable_1_Final_Summary

                Select ISNULL(SUM(Amount),1) as 'AUA' from  #BrokerTotal
				
		END
	
		        ELSE IF(@RecordOnlyhavingClosingbalanceZero = 0)
			        BEGIN							
						IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
							BEGIN
						
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
										END AS 'Avg. Rate',

									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
										END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt, Broker_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,Broker_name
								HAVING SUM(closing_qty) != 0
								--HAVING (sum (CASE WHEN @RecordOnlyhavingClosingbalanceZero = 0 
								--	THEN closing_qty end  )!=0
									
														END
						ELSE IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0)
							BEGIN
								
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								''  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',

								SUM(ISNULL(Other_amt,0))Other_amt, Broker_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
						ELSE IF(@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1)
							BEGIN
								
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
										END AS 'Avg. Rate',

									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
										END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,Broker_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate,opening_date, purchase_date,sold_date,closing_qty
								HAVING SUM(closing_qty) != 0
							END
						ELSE --IF(@WithActualAvgRate = 0)
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
									CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt,  Broker_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Broker_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					--END
			END
		ELSE
			BEGIN
					IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
							BEGIN
						
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) >=0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
										END AS 'Avg. Rate',

									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
										END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt, Broker_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,Broker_name
								HAVING SUM(closing_qty) = 0
								--HAVING (sum (CASE WHEN @RecordOnlyhavingClosingbalanceZero = 0 
								--	THEN closing_qty end  )!=0
									
														END
						ELSE IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0)
							BEGIN
								
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								''  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
										END AS 'Avg. Rate',

									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
										END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  Broker_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) = 0
							END
						ELSE IF(@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1)
							BEGIN
								
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
										END AS 'Avg. Rate',

									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
										END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt, Broker_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate,opening_date, purchase_date,sold_date,closing_qty
								HAVING SUM(closing_qty) != 0
							END
						ELSE --IF(@WithActualAvgRate = 0)
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
									CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt,  Broker_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Broker_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) = 0
							END
			END

		Select Broker_Name,Sum(ISNULL (gain_loss,0)) from #mainoutputtable_1_Final_Summary
		Group By Broker_Name
		Having Sum(ISNULL (gain_loss,0))!=0
		Order by 1
			
		Select  Round(sum(Other_amt),4) from BrokerBill where Member_code=@memcode and Yearcode=@yearcode and isfnoBill=@Investmenttype and Trans_Dt<=@Todate

		
END


































GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency] AS' 
END
GO

--EXECUTE   proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency 0,1,'0','30001','1120182019','04/01/2018','03/31/2019','','','','0', '0' ,'0','ClosingStocks',0,'3P LAND HOLDINGS LTD/26/04/2018' 

ALTER PROCEDURE [dbo].[proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency] --0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','ScriptWiseTotal'
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@BrokerCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,
@OUTPUT_Flag VARCHAR(MAX),@IsWithTax bit = 0,
@Script_Name varchar(max) = '')
AS 
  BEGIN 
  SET NOCOUNT ON; 
		DECLARE @StartYearDate varchar(20) = '04/01/'+ (SELECT SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101)
		CREATE TABLE #mainoutputtable_1
        (  
			pkid INT identity(1,1),
			Dup_pkid int,
			Broker_name VARCHAR(MAX),
			Trans_No VARCHAR(20),
			id INT,
			prioritys INT,
			Trans_Type  VARCHAR(50), 
			Split_Type VARCHAR(50), 
			Flag_Type VARCHAR(10),
			Flag_Type_Sold VARCHAR(10),
			flag_script_name  VARCHAR(500),
			flag_holding_type VARCHAR(200), 
			script_name  VARCHAR(500),
			holding_type VARCHAR(200), 
			opening_bill_no VARCHAR(10),	
			opening_date DATETIME,
			opening_qty  FLOAT DEFAULT 0,
			opening_rate  FLOAT DEFAULT 0,
			opening_amount AS( [opening_qty] * [opening_rate] ), 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount AS( purchase_qty * purchase_rate ), 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount AS ( sold_qty * sold_rate ), 
			gain_loss float,
			closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 
			closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
			closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
			short_term FLOAT DEFAULT 0,
			long_term  FLOAT DEFAULT 0,
			speculation  FLOAT DEFAULT 0,
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			dayscount FLOAT DEFAULT 0,
			isintradaycol INT,
			[type] VARCHAR(20) ,
			ScriptCode  VARCHAR(50),
			Strike_Price float DEFAULT 0,
			OptionType VARCHAR(100),
			Last_Date VARCHAR(100),
			MemberCode VARCHAR(50),
			MemberName VARCHAR(max)
        )  

		CREATE TABLE #mainoutputtable_1_Final
        ( 
			Dup_pkid int,
			OrderBy varchar(100),
			Trans_No VARCHAR(20),
			id INT,
			prioritys INT   ,
			Split_Type VARCHAR(50),
			Flag_Type VARCHAR(10),
			Flag_Type_Sold VARCHAR(10),
			flag_script_name  VARCHAR(500),
			flag_holding_type VARCHAR(200), 
			script_name  VARCHAR(500),
			holding_type VARCHAR(200), 
			opening_bill_no VARCHAR(10),	
			opening_date DATETIME,
			opening_qty  FLOAT DEFAULT 0,
			opening_rate  FLOAT DEFAULT 0,
			opening_amount FLOAT DEFAULT 0, 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount FLOAT DEFAULT 0 , 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount FLOAT DEFAULT 0, 
			gain_loss FLOAT DEFAULT 0,
			gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
			loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
			closing_qty FLOAT DEFAULT 0, 
			closing_rate FLOAT DEFAULT 0,
			closing_value FLOAT DEFAULT 0,
			short_term FLOAT DEFAULT 0,
			long_term FLOAT DEFAULT 0, 
			speculation FLOAT DEFAULT 0, 
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			Broker_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			dayscount FLOAT DEFAULT 0,
			isintradaycol INT,[type] VARCHAR(20),
			sort   VARCHAR(5),
			ScriptCode  VARCHAR(50),
			Strike_Price float DEFAULT 0,
			OptionType VARCHAR(100),
			Last_Date VARCHAR(100),
			MemberCode VARCHAR(50),
			MemberName VARCHAR(max)
        ) 

		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty INT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT  
		DECLARE @tablerowscount INT
		IF(@status = 0) 
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
				@openingDate VARCHAR(50),@openingRate FLOAT,@openingQty INT,@openingAmount FLOAT,
				@purchaseDate VARCHAR(50),@PurchaseBillNo  VARCHAR(50),@purchaseRate FLOAT,@purchaseQty int,@purchaseAmount FLOAT,
				@soldDate VARCHAR(50),@soldBillNo  VARCHAR(50),@soldRate FLOAT,@soldQty INT,@soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50),@Broker_name  VARCHAR(100), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(10),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,@PurchaseIntraFlag VARCHAR(100),
				@SaleIntraFlag VARCHAR(10), @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@ScriptId VARCHAR(50),@Dup_pkid int, @Pkid varchar(50),@idcount int,
				@Strike_Price FLOAT,@OptionType VARCHAR(50),@Last_Date VARCHAR(50), @Member_Code varchar(50), @Member_Name varchar(max)    

				CREATE TABLE #SCriptName
				(
					ScriptName varchar(MAX)
				)

				IF(@Script_Name != '')
					INSERT INTO #SCriptName SELECT value FROM Fn_split(@Script_Name, ',') 
				ELSE 
					BEGIN
						INSERT INTO #SCriptName 
						Select distinct (Ms.script_name 
								+ '/' + CONVERT(VARCHAR(10),t.Last_Date,103) 
								+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
								+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' END) 
						from brokerbill_Trans t
						Left Join mst_Script ms on ms.script_Code = t.script_Code 
					END

				CREATE TABLE #BrokerCodes
				(
					BrokerCodes varchar(MAX)
				)
				 
				IF(@BrokerCode != '')
					INSERT INTO #BrokerCodes SELECT value FROM Fn_split(@BrokerCode, ',') 
				ELSE 
					INSERT INTO #BrokerCodes SELECT Broker_Code FROM brokerbill
					
				SELECT	ROW_NUMBER ( ) OVER (ORDER BY  mm.Member_Code,
						mm.Member_Name,ma.AC_Name, t.script_code, t.trans_dt ) AS NameId,t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,
						t.TransType,t.Script_Code,t.Last_Date,t.Qty,
						Case When @IsWithTax=0 Then t.Rate Else t.Exp_Rate END As 'Rate',--t.Rate,
						t.YearCode, t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,
						t.Exp_Rate,
						t.FrmNm,t.ID,
						Ms.bse_code,Ms.nse_code,
						Ms.script_name 
						+ '/' + CONVERT(varchar(20),t.Last_Date,103) 
						+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
						+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' 
						END	 script_name,
						'Empty' AS 'Holding Type',
						CASE WHEN (((t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101))AND t.TransType='Bought') THEN 'Opening'
							 WHEN t.TransType='Bought' AND  t.Bill_no != 'Opening'  THEN 'Bought' 
							 WHEN TransType='Sold' THEN 'Sold' 
						END AS 'Flag_Type',
						ma.AC_Name as 'Broker_Name',t.isstock,
						mm.Member_Code,
						mm.Member_Name
						INTO #alldata 
				FROM brokerbill_trans t 
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN BrokerBill BB ON BB.Member_Code = t.Member_code  and bb.Trans_no=t.Trans_No
				LEFT JOIN mst_account ma ON ma.AC_Code = BB.Broker_Code and t.member_Code=ma.member_Code and ma.Year_Code=bb.YearCode
				LEFT JOIN mst_account ma1	ON ma1.AC_Code = BB.Broker_Code AND ma1.Member_Code = BB.Member_code and ma1.Year_Code = BB.YearCode  and bb.Trans_no=t.Trans_No
			    LEFT JOIN Mst_Member mm	ON t.member_code = mm.Member_code 
				WHERE  t.isfnobill = @Investmenttype 
				AND  t.trans_dt <= @Todate
				AND t.member_code IN (SELECT Value FROM membercodestable(@memcode,','))
				--AND t.member_code = @memcode 
				AND  t.yearcode = @yearcode  
				AND ( Ms.script_name 
						+ '/' + CONVERT(varchar(20),t.Last_Date,103) 
						+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
						+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' 
						END ) IN (SELECT * FROM #SCriptName)
				AND	 BB.Broker_code IN (SELECT * FROM #BrokerCodes)
				AND  ISNULL(t.isIntraDay,0) =(CASE WHEN @IsIntraDay=0 THEN  ISNULL(t.isIntraDay,0) ELSE @IsIntraDay END)
				AND t.isstock=(select case when @Is_BFCF = 1 then  '' else  t.isstock end) 
			
				GROUP BY mm.Member_Code,
						mm.Member_Name, ma.AC_Name,t.YearCode, script_name,t.Trans_Dt,t.Bill_no,t.Trans_No,Sr_No,TransType,t.Script_Code,MonthYear,Last_Date,LotSize,Qty,LotQty,Disp_qty,
				Bal_qty,G_Rate,t.Brok_Amt,ServTax_Amount,Rate,t.Amount,Stt_Amount,
				EntrySource,t.Ref_TransNo,Ref_SrNo,MergedEntry,t.isFNOBill,Strike_Price,OptionType,isIntraDay,Brok_PerUnit,lockedbymerger,
				frac_Qty,Org_Trans_No,Org_SrNo,isDeleteMerger,isstock,ScripwiseExpense,isClient_code,isClient_Brokrage,c_Qty,C_Gross_Rate,
				C_Net_Rate,C_Amount,C_STT,C_STax,C_MisChg,TransactionChg,C_StampDuty,Exp_Rate,PerExp_Unit,FrmNm,ID,bse_code,nse_code,t.isstock
				ORDER  BY   NameId

			--	select * from #alldata

				DECLARE @isIntradayCol INT 
				DECLARE @COUNT INT 
					 
				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT id,Trans_No,script_name,Script_Code ,[holding type],bill_no,CONVERT(VARCHAR(10),trans_dt,101),qty,rate,ISNULL(qty, 0) * ISNULL(rate, 0),ISNULL(isintraday, 0),Broker_name,
				Strike_Price,OptionType,Last_Date,Member_Code,Member_Name   
				FROM #alldata
				WHERE ((TransType != 'Sold' AND #alldata.bill_no IN('Opening')) OR  CONVERT(date,trans_dt,101)  < CONVERT(date ,@StartYearDate,101)AND #alldata.TransType='Bought')
				
				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name 
				WHILE(@@FETCH_STATUS = 0)
					BEGIN

						IF(@Investmenttype=2)
							SET @holding_type='Mutual Fund'
						-- Insert All Openings
						SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE script_name = @scriptname)-- AND ID = @ID)
						SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
						SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
						SET @Dup_pkid = ISNULL(@Dup_pkid,0)
						SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
						SET @Dup_pkid = @Dup_pkid + 1

					 	DECLARE @IDs INT=0
						DECLARE @Flag_Types VARCHAR(10)
						SET @Flag_Types = (SELECT CASE WHEN @billno = 'Opening' THEN 'Opening' ELSE 'Bought' END)
						IF(@Flag_Types='Opening'  OR (@billno IN('Split') AND CONVERT(DATE,@dates,101)  < CONVERT(DATE ,@StartYearDate,101))
						OR (@billno NOT IN('Bought','Sold') AND CONVERT(date,@dates,101)  < CONVERT(date ,@StartYearDate,101)))
							BEGIN	
								INSERT INTO #mainoutputtable_1   
								(Dup_pkid,opening_bill_no ,id, Trans_No,ScriptCode  ,  Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,Broker_name, Strike_Price, OptionType, Last_Date,MemberCode,MemberName) 
								SELECT  @Dup_pkid,@billno,@ID, @Trans_No,@ScriptId  , 'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name
							END	
						SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),0) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
						IF(@idcount>0)
							BEGIN
								UPDATE #MainOutputtable_1 
								SET Dup_pkid = Dup_pkid + 1 
								WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
							END
			 			FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name
						END 

				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 
				DECLARE @salecount INT=0,@Boughtcount INT=0,@Flag_Type VARCHAR(20)
								 
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
				SELECT id,Bill_no,Flag_Type,TransType,Script_Code,script_name,[holding type],Trans_No,CONVERT(VARCHAR(10), trans_dt,101), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Broker_name, Strike_Price, OptionType, Last_Date,Member_Code,Member_Name
				FROM #alldata WHERE 
				(TransType in ('Bought','Sold')  OR CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
				
				--Select * from #MainOutputtable_1
				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType,@ScriptId,@scriptname, @holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name 								
				WHILE (@@FETCH_STATUS = 0) 
						BEGIN
 			
							SET @COUNT									=	0
							DECLARE @IsOpening INT						=	0
							DECLARE @prioritysId INT					=	0
							DECLARE @str VARCHAR(MAX)					=	''	
							DECLARE @purchase_Op_Qty FLOAT				=	0
							DECLARE @purchase_Op_Bill VARCHAR(20)		=	''
							DECLARE @purchase_Op_Date VARCHAR(20)		=	''
							DECLARE @purchase_Op_Rate FLOAT				=	0
							DECLARE	@PurQTY FLOAT						=	0
							DECLARE	@BalPurQTY FLOAT					=	0
							DECLARE @BalSoldQTY FLOAT					=	0
							DECLARE @Balpurchase_Op_Qty FLOAT			=	0
							DECLARE @BalOpeningQTY FLOAT				=	0
							DECLARE	@Sold_Qty FLOAT						=	0
							DECLARE @tempID INT							=	0
							
							IF(@isIntradayCol=0)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) 
															FROM #MainOutputtable_1 
															WHERE script_name = @scriptname 
															AND Flag_Type_Sold IN('Sold')  and  Flag_Type ='Sold'  
															AND ISNULL(sold_qty,0) != 0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) 
															AND isintradaycol=0 
															AND MemberName = @Member_Name  
															AND Broker_name = @Broker_name)

											--Select * from #MainOutputtable_1
											IF (@COUNT > 0)
												BEGIN
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  script_name, case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId, 
													* INTO #tempSoldValExists 
													FROM
													#MainOutputtable_1 
													WHERE script_name=@scriptname AND holding_type=@holding_type  AND isintradaycol=0 AND 
													Broker_name = @Broker_name
													AND MemberName = @Member_Name
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold ='Sold'  and  Flag_Type ='Sold' AND isintradaycol=0
													ORDER BY NameId

													DECLARE @R_Sold_COUNT INT=(SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty INT 
												
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists ORDER BY Dup_pkid,NameId)
															SET @str = @TransType

															SELECT TOP 1	@Sold_Qty		= sold_qty,
																			@soldDate		= sold_date,
																			@soldRate		= sold_Rate,
																			@soldBillNo		= sold_bill_no,
																			@Pkid			= Pkid
																	
															FROM #tempSoldValExists
															WHERE id  = @tempSaleID 

															SET @purchase_Op_Qty = @qty

															IF(@TransType='Opening')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	opening_date	=	@dates,
																		opening_rate	=	@rate,
																		opening_qty		=	CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	purchase_date	=	@dates,
																		purchase_rate	=	@rate,
																		purchase_bill_no=   @PurchaseBillNo, 
																		purchase_qty		=	CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(purchase_qty,0)=0 AND pkid = @pkid
																END
															
															IF(@Sold_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET sold_qty = @purchase_Op_Qty 
																	WHERE  id  = @tempSaleID AND Flag_Type_Sold='Sold' AND pkid = @pkid
																END

															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND Pkid = @Pkid
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempSoldValExists )
															DECLARE @Balancedval   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)

															IF(@Balancedval  < 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE script_name = @scriptname)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1


																	SET @soldQty=ABS(@Balancedval) 
																	SET @prioritysId  =(SELECT MAX(prioritys) FROM #MainOutputtable_1) 
																	SET @prioritysId = ISNULL(@prioritysId,0)+1

																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode  , Flag_Type,Flag_Type_Sold ,prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberCode,MemberName)
																	VALUES(@Dup_pkid,@tempSaleID ,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name)
																	
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 

																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			where Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																		SET @Balancedval=0
																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE script_name = @scriptname)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  = (SELECT MAX(prioritys + 1) FROM #MainOutputtable_1)

																	if(@TransType='Opening')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode, Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberCode,MemberName)
																			VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name)

																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	ELSE if(@TransType='Bought')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberCode,MemberName)
																			VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name)

																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid 
																			and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																ENd
															ELSE IF(@Balancedval=0)
																BEGIN
																	break;
																END

															SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
															SET @qty=@Balancedval
														END
													

													DROP TABLE #tempSoldValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
												 
													INSERT INTO #mainoutputtable_1 (Dup_pkid,id,Trans_No,ScriptCode, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberCode,MemberName) 
													VALUES ( @Dup_pkid,@ID,@Trans_No,@ScriptId, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name) 
												END
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
								
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */

											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 
												WHERE script_name=@scriptname 
												AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') 
												AND ISNULL(sold_qty,0)=0  
												AND isintradaycol=0  AND MemberName = @Member_Name 
												AND Broker_name = @Broker_name)
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  script_name ,case when opening_date IS NOT NULL then opening_date else purchase_date end ) AS NameId, 
													* INTO #tempValExists 
													FROM
													#MainOutputtable_1 
													WHERE script_name=@scriptname
													AND MemberName = @Member_Name 
													AND Broker_name = @Broker_name 
													AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') 
													AND ISNULL(sold_qty,0)=0  AND isintradaycol=0 
													ORDER BY NameId

													DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty int 
													
													
													WHILE(@RCOUNT > 0)
														BEGIN 
															SET @Sold_Qty = @qty
															SET @tempID = (Select top(1) id from #tempValExists  ORDER BY Dup_pkid)
															SET @str = (Select top(1) Flag_Type From #tempValExists Where id  = @tempID)
														
															IF(@str='Opening')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= opening_qty,
																					@openingDate	= opening_date,
																					@openingrate	= opening_rate,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID
																END
															ELSE IF(@str='Bought')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= purchase_qty,
																					@PurchaseDate	= purchase_date,
																					@Purchaserate	= purchase_rate,
																					@PurchaseBillNo = purchase_bill_no,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID
																END
															    
															IF(@Sold_Qty > 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	UPDATE #MainOutputtable_1  
																		SET	
																			opening_qty = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							END,
																			purchase_qty  = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							END,
																			sold_date=@dates,
																			sold_bill_no = @billno,
																			sold_rate=@rate,
																			sold_qty= CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold='Sold',
																			prioritys       = @prioritysId
																	WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND Pkid=@Pkid
																	SET @Balanceval = ABS(@Sold_Qty) - ABS(@TempSoldQty)
																END
															
														DELETE FROM #tempValExists WHERE id = @tempID AND Pkid=@Pkid
														SET @tablerowscount = (SELECT COUNT(*) FROM  #tempValExists )
														SET @RCOUNT = @RCOUNT - 1

														IF(@Balanceval  < 0)
															BEGIN
																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1
															
															 
																--SET @prioritysId  =(SELECT MAX(ISNULL(@prioritysId,0)+1) FROM #MainOutputtable_1)

																IF(@str='Opening')
																	BEGIN
																		SET @openingQty=ABS(@Balanceval) 
																		SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																		SET @prioritysId = ISNULL(@prioritysId,0)+1

																		INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberName,MemberCode)
																		VALUES(@Dup_pkid,@tempID,@Trans_No,@ScriptId, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Name,@Member_Code)

																		SET @prioritysId = ISNULL(@prioritysId,0)+1
																
																		UPDATE #MainOutputtable_1 
																		SET prioritys=@prioritysId+1  WHERE prioritys >=  @prioritysId 
																		AND ID <> @tempID
																	END
																ELSE 
																	BEGIN
																		SET @PurchaseQty = ABS(@Sold_Qty) 
																		SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																		SET @prioritysId = ISNULL(@prioritysId,0)+1
																		
																		INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberName,MemberCode)
																		VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Name,@Member_Code)
																		UPDATE #MainOutputtable_1 SET prioritys=@prioritysId  WHERE prioritys > @prioritysId AND ID<>@tempID

																		SET @prioritysId = ISNULL(@prioritysId,0)+1
																			
																		UPDATE #MainOutputtable_1 
																		SET prioritys=@prioritysId    
																		WHERE prioritys >= @prioritysId AND ID <> @tempID
																	END
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),1) FROM #MainOutputtable_1)) END)  
																IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
																set @Balanceval=0;
															BREAK;	
															END
														ELSE if(@Balanceval>0 and @tablerowscount=0)
															BEGIN

																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1
																SET @prioritysId  = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1)

																INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberName,MemberCode)
																VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Name,@Member_Code)

																UPDATE #MainOutputtable_1 
																SET prioritys=@prioritysId+1  
																WHERE prioritys > @prioritysId AND ID<>@tempSaleID 

																SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  

																IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1 
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																	FROM Fn_split(@Pkid, ',') ) 
																END
															ENd
															ELSE IF(ISNULL(@Balanceval,0) =0)
																BEGIN
																	SET @Balanceval=0
																	BREAK;
																END

														SET @qty = @Balanceval
													END
													DROP TABLE #tempValExists
												END
											
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
										
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
													INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No, ScriptCode, Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,Broker_name,Strike_Price,OptionType,Last_Date,MemberName,MemberCode)
													VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId,  'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Name,@Member_Code)

												END
											SET @purchase_Op_Date	=	''
											SET @purchase_Op_Rate	=	''
											SET @purchase_Op_Qty	=	''
											SET @purchase_Op_Bill	=	''
										END
								END
							 
							FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type ,@TransType,@ScriptId, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Broker_name,@Strike_Price,@OptionType,@Last_Date,@Member_Code,@Member_Name
						END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 
		--	  select * from #mainoutputtable_1
				INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,Broker_name,nse_rate,bse_rate, sort,isintradaycol,Strike_Price,OptionType,Last_Date,MemberCode,MemberName  )

				SELECT ROW_NUMBER ( ) OVER (
				ORDER BY MemberName,Script_Name,
					case   WHEN  Dup_pkid is Null Then Pkid
						   WHEN  Dup_pkid is NOt Null then Dup_pkid 
						   ELSE Dup_pkid end,
					prioritys,
				case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END desc)  
			    AS NameId,
				opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,
				
					    Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365) --short term for purchase
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
						
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365) --short term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) = 0) 
							AND (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				Broker_name,nse_rate,bse_rate,1 sort,isintradaycol ,Strike_Price,OptionType,Last_Date,MemberCode,MemberName 
				FROM #mainoutputtable_1 
				order by NameId
		
			UPDATE #mainoutputtable_1_Final SET prioritys=0
			DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
			UPDATE #mainoutputtable_1_Final
			SET prioritys  = @i , @i = @i + 1
		IF(@OUTPUT_Flag='Details')
			BEGIN
				IF(@BrokerCode!='')
					BEGIN
						SELECT prioritys,ScriptCode,script_name 'Script Name',Holding_Type,opening_bill_no,
						CONVERT(date, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_rate,0) 'Opening Rate',
						ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(date, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',
						ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(date, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',
						ISNULL(sold_rate,0) 'Sold Rate',
						ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',
						ISNULL(gain,0) 'Gain',
						ISNULL(loss,0) 'Loss',
						ISNULL(closing_qty,0) 'Closing Qty',
						ISNULL(closing_rate,0) 'Closing Rate',
						ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0) as 'short_term', 
						ISNULL(long_term,0) as 'long_term',
						ISNULL(speculation,0) as 'speculation',
						CASE WHEN isintradaycol=1 and gain!=0 THEN gain  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 and loss!=0  THEN loss  ELSE '' END loss_speculation,Broker_name,nse_rate,bse_rate,isintradaycol,1 sort 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
						ORDER BY Broker_name,script_name,prioritys,Holding_Type,id
					END
				ELSE
					BEGIN
						SELECT prioritys,ScriptCode,script_name 'Script Name',Holding_Type,opening_bill_no,
						CONVERT(date, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(date, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(date, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',
						ISNULL(sold_rate,0) 'Sold Rate',
						ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',
						CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',
						CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
						ISNULL(closing_qty,0) 'Closing Qty',
						ISNULL(closing_rate,0) 'Closing Rate',
						ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0) as 'short_term', 
						ISNULL(long_term,0) as 'long_term',
						ISNULL(speculation,0) as 'speculation',
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						Broker_name,nse_rate,bse_rate,isintradaycol,1 sort 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
						ORDER BY Broker_name,script_name,prioritys,Holding_Type --,id
					END
			END

		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
				SELECT  '' Opening_Bill_No,0 id ,  0 prioritys,'' ScriptCode, script_name 'Script Name', '' Holding_Type,
				NULL 'Opening Date', SUM(ISNULL(opening_qty,0)) 'Opening Qty', 
				 ISNULL((ISNULL(SUM(opening_amount),0)  / NULLIF(SUM(Opening_qty),0)),0) 'Opening Rate', 
				 SUM(opening_amount) 'Opening Amount',
				NULL 'Purchase Date',MAX(purchase_bill_no) 'Purchase BillNo', 
				SUM(ISNULL(purchase_qty,0))  'Purchase Qty', 
				ISNULL((ISNULL(SUM(purchase_amount),0)  / SUM(NULLIF(purchase_qty,0))),0)  'Purchase Rate', 
				--SUM(purchase_amount)  'Purchase Amount',
				SUM(ISNULL(purchase_amount,0)) 'Purchase Amount',
				NULL 'Sold Date', MAX(sold_bill_no) 'Sold BillNo',
				 SUM(ISNULL(sold_qty,0)) 'Sold Qty', 
				 ISNULL((ISNULL(SUM(sold_amount),0) / NULLIF (SUM(sold_qty),0)),0) 'Sold Rate', 
				SUM(ISNULL(sold_amount,0)) 'Sold Amount', 
				SUM(ISNULL(gain_loss,0) ) 'Gain/Loss', 
				SUM(ISNULL(gain,0))  'Gain', 
				SUM(ISNULL(loss,0))  'Loss',
				SUM(ISNULL(closing_qty,0))  'Closing Qty',  
				ISNULL((ISNULL(SUM(closing_value),0) / NULLIF(SUM(closing_qty),0)),0)   'Closing Rate', 
				SUM(ISNULL(closing_value,0))  'Closing Value', 
				SUM(ISNULL(short_term,0))  short_term, 
				SUM(ISNULL(long_term,0))  long_term,
				SUM(ISNULL(speculation,0)) speculation, 
				SUM(ISNULL(gain_speculation,0))gain_speculation, 
				SUM(ISNULL(loss_speculation,0))loss_speculation, Broker_name,0 nse_rate,0 bse_rate,1 sort --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
				FROM
					(
						SELECT  '' Opening_Bill_No,MAX(id+0)id ,MAX (prioritys+0) prioritys,'' ScriptCode, script_name  ,'' Holding_Type,'' 'Opening Date',SUM(ISNULL(opening_qty,0)) 'Opening_Qty',sum(opening_rate) opening_rate ,SUM(opening_amount) 'Opening_Amount',
						'' 'Purchase Date',purchase_bill_no,SUM(purchase_qty) 'Purchase_Qty', SUM(ISNULL(purchase_rate,0)) purchase_rate,SUM(purchase_amount) 'Purchase_Amount',
						'' 'Sold Date',sold_bill_no ,SUM(ISNULL(sold_qty,0)) 'Sold_Qty', SUM(sold_rate)sold_rate  , SUM(ISNULL(sold_amount,0)) 'Sold_Amount',SUM(gain_loss) 'Gain_Loss',SUM(gain) 'Gain',SUM(loss) 'Loss',
						SUM(closing_qty) 'Closing_Qty',SUM(closing_rate) 'Closing_Rate',SUM(closing_value) 'Closing_Value',SUM(short_term) short_term,SUM(long_term) long_term,
						SUM(speculation) speculation,SUM(gain_speculation) gain_speculation,SUM(loss_speculation) loss_speculation, Broker_name,0 nse_rate,0 bse_rate,1 sort --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
						FROM #mainoutputtable_1_Final 
						GROUP BY script_name,Holding_Type,purchase_bill_no,sold_bill_no,Broker_name 
					)a
				GROUP BY  script_name,Broker_name  
				ORDER BY   script_name,id
				
				 
				--ORDER BY  prioritys 
			END

		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN
			
				SELECT  prioritys ,Trans_No,id ,  ScriptCode,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,
				opening_date,ISNULL(opening_qty,0) ,ISNULL(opening_rate,0),ISNULL(opening_amount,0),
				CONVERT(date, purchase_date,101),purchase_bill_no,ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,
				CONVERT(date, sold_date,101),sold_bill_no ,ISNULL(sold_qty,0) ,sold_rate,ISNULL(sold_amount,0) ,
				ISNULL(gain_loss,0) 'gain_loss',
				ISNULL(gain,0) gain,
				ISNULL(loss,0) loss,
				ISNULL(closing_qty,0) closing_qty,
				ISNULL(closing_rate,0) closing_rate,
				ISNULL(closing_value,0) closing_value,
				ISNULL(short_term,0) short_term,
				ISNULL(long_term,0) long_term,
				ISNULL(speculation,0) speculation,
				ISNULL(gain_speculation,0) gain_speculation,
				ISNULL(loss_speculation,0) loss_speculation,
				Broker_name,nse_rate,bse_rate,0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort 
				,isintradaycol,Last_Date,Strike_Price,OptionType
				FROM #mainoutputtable_1_Final
				ORDER BY Broker_name,script_name,CONVERT(date, purchase_date,101)
			END

			ELSE IF(@output_Flag='ClosingStocks')
			BEGIN
			--Select * from #mainoutputtable_1_Final
				 SELECT id,
						Trans_No ,
						script_name,
						ScriptCode,
						Holding_Type,
						CASE
							WHEN ISNULL(closing_qty,0) < 0		THEN sold_bill_no
							WHEN ISNULL(opening_date,'') != ''  THEN 'Opening'
							WHEN ISNULL(purchase_date,'') != '' THEN  purchase_bill_no
							ELSE ''
						END  AS  'bill_no',
						CASE
							WHEN ISNULL(closing_qty,0) < 0		THEN CONVERT(DATE,sold_date,101)
							WHEN ISNULL(opening_date,'') != ''	THEN  CONVERT(DATE,opening_date,101)
							WHEN ISNULL(purchase_date,'') != '' THEN CONVERT(DATE,purchase_date,101)
						END  AS  'trans_dt',
						Strike_Price,
						OptionType,
						'' MonthYear,
						Last_Date,
						'' Exp_Rate,
						Broker_name,
						'' DP_Code,
						ABS(ISNULL(closing_qty,0)) 'Qty',
						ISNULL(closing_rate,0) 'rate',
						ISNULL(closing_value,0) 'amount',
						isintradaycol,
						'' consultant_name,
						'' Consultant_code,
						MemberCode,
						MemberName,
						CASE
							WHEN ISNULL(closing_qty,0)    < 0		THEN 'Sold'
							WHEN ISNULL(opening_date,'')  != ''		THEN 'Opening'
							WHEN ISNULL(purchase_date,'') != ''		THEN  'Bought'
							ELSE ''
						END  AS  'Type'
				from #mainoutputtable_1_Final 
				WHERE ISNULL(closing_qty,0) <> 0
				ORDER BY Trans_No			
			END
			ELSE IF(@OUTPUT_Flag='Annexture')
				BEGIN
				 SELECT	'' opening_bill_no,
						0 id,
						0 prioritys,
						ScriptCode,
						'' 'Family_Name',
						MemberName 'Member_Name',
						'' 'Family_Code',
						MemberCode 'Member_Code',
						script_name 'Script Name',  
						Holding_Type,
						NULL 'Opening Date', 
						SUM(ISNULL(opening_qty,0)) 'Opening Qty', 
						CASE WHEN SUM(opening_qty) != 0
							 THEN SUM(opening_amount)/ NULLIF(SUM(opening_qty),0)  
							 ELSE 0
						END  'Opening Rate', 
						SUM(opening_amount) 'Opening Amount',
						NULL 'Purchase Date',
						'' AS 'Purchase BillNo', 
						SUM(ISNULL(purchase_qty,0))  'Purchase Qty', 
						SUM(ISNULL(purchase_amount,0))  / nullif(SUM(ISNULL(purchase_qty,0)),0) 'Purchase Rate', 
						SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
						NULL 'Sold Date', 
						'' AS 'Sold BillNo', 
						SUM(ISNULL(sold_qty,0)) 'Sold Qty', 
						CASE	WHEN SUM(sold_qty) != 0
								THEN SUM(ISNULL(sold_amount,0))/nullif(SUM(sold_qty),0)   
								ELSE 0
						END  'Sold Rate',
						SUM(ISNULL(sold_amount,0)) 'Sold Amount', 
						SUM(ISNULL(gain_loss,0) ) 'Gain/Loss', 
						SUM(ISNULL(gain,0))  'Gain', 
						SUM(ISNULL(loss,0))  'Loss',
						SUM(ISNULL(closing_qty,0))  'Closing Qty', 
						CASE  WHEN SUM(closing_qty) != 0
							  THEN (SUM(closing_value) / SUM(NULLIF(closing_qty,0))) 
							  ELSE 0
						END  'Closing Rate',
						SUM(closing_value)  'Closing Value', 
						SUM(ISNULL(short_term,0))  as short_term, 
						SUM(ISNULL(long_term,0)) as long_term,
						SUM(ISNULL(speculation,0)) as speculation, 
						SUM(ISNULL(gain_speculation,0))gain_speculation, 
						SUM(ISNULL(loss_speculation,0))loss_speculation,   
						'' consultant_name, 
						0 nse_rate,
						0 bse_rate,
						1 sort,
						broker_code 					
				FROM
					(
						SELECT MAX(id+0)id ,MAX (prioritys+0) prioritys,'' opening_bill_no,ScriptCode, script_name,   Holding_Type,'' 'Opening Date',
						SUM(ISNULL(opening_qty,0)) 'Opening_Qty',sum(ISNULL(opening_rate,0)) opening_rate ,SUM(ISNULL(opening_amount,0)) 'Opening_Amount',
						'' 'Purchase Date','' purchase_bill_no,SUM(ISNULL(purchase_qty,0)) 'Purchase_Qty',
						 SUM(ISNULL(purchase_rate,0)) purchase_rate,SUM(ISNULL(purchase_amount,0)) 'Purchase_Amount',
						'' 'Sold Date',sold_bill_no ,SUM(ISNULL(sold_qty,0)) 'Sold_Qty', SUM(sold_rate)sold_rate  , SUM(ISNULL(sold_amount,0)) 'Sold_Amount',SUM(ISNULL(gain_loss,0)) 'Gain_Loss',SUM(ISNULL(gain,0)) 'Gain',SUM(ISNULL(loss,0)) 'Loss',
						SUM(ISNULL(closing_qty,0)) 'Closing_Qty',
						SUM(ISNULL(closing_rate,0)) 'Closing_Rate',SUM(ISNULL(closing_value,0)) 'Closing_Value',
						sum(ISNULL(short_term,0)) as short_term,
						sum(ISNULL(long_term,0)) as long_term,
						sum(ISNULL(speculation,0)) as speculation,
						SUM(ISNULL(gain_speculation,0)) gain_speculation,
						SUM(ISNULL(loss_speculation,0)) loss_speculation,  Broker_name,0 nse_rate,0 bse_rate,1 sort,MemberCode,MemberName,
						MA.AC_Code as 'broker_code'
						FROM #mainoutputtable_1_Final F
						LEFT JOIN MST_Account MA ON MA.AC_Name = F.Broker_name AND MA.Member_Code in (SELECT Value FROM membercodestable(@memcode,','))  AND MA.Year_Code = @yearcode
						GROUP BY MemberCode,MemberName,Broker_name,ScriptCode,script_name, Holding_Type,purchase_bill_no,sold_bill_no ,opening_date,purchase_date,sold_date,isintradaycol,MA.AC_Code,MA.AC_Name
					)a
					GROUP BY  a.MemberCode,a.MemberName,a.broker_code,Broker_name,a.ScriptCode,script_name ,Holding_Type
					ORDER BY  MemberName,Broker_name,Holding_Type ,script_name,sort
				END

		DROP TABLE #mainoutputtable_1 
		 
		DROP TABLE #alldata 
		 
  END  


































GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency_Summary] AS' 
END
GO



--Execute  proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency_Summary   0,1,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-02-01 03:50:37:50','B0044','','','', '0' ,'0',0,1,0
--Execute  proc_Stockholdingposition_Equity_Summary    0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0',1,1,1
ALTER PROCEDURE [dbo].[proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency_Summary]  --''
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate Datetime ,@Todate Datetime, 
@ScriptCode VARCHAR(max),@BrokerCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,
@RecordOnlyhavingClosingbalanceZero as bit,@WithActualAvgRate as bit, @DateWiseClosinStock as bit,@IsWithTax bit = 0,@Script_Name varchar(max) = '')
AS
BEGIN
SET NOCOUNT ON;
		CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
           prioritys INT,Trans_No VARCHAR(50),id INT,scriptCode  VARCHAR(500),script_name  VARCHAR(500),holding_type VARCHAR(200),flag_script_name  VARCHAR(500),flag_holding_type VARCHAR(200),
           opening_date VARCHAR(50),opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
           purchase_date VARCHAR(50),purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
           sold_date VARCHAR(50),sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   Broker_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   Other_amt FLOAT DEFAULT 0,
		   ServTax_Amt FLOAT DEFAULT 0,
		   Stt_amt FLOAT DEFAULT 0,
		   sort   VARCHAR(5),
		   isintradaycol  INT,
		   Last_Date dateTime,
		   Strike_Price float,
		   OptionType varchar(max) 
        ) 


		Insert into #mainoutputtable_1_Final_Summary
		EXEC proc_StockholdingPosition_BrokerWise_F_And_O_AND_MCX_And_Currency   @status,@Investmenttype,@Ac_Type,@memcode,@yearcode,@Fromdate,@Todate,@ScriptCode,@BrokerCode,@BSE_NSE_Code,@Is_BFCF,@IsIntraDay,@short_Long_Term,'ALLData',@IsWithTax,@Script_Name
	 


		SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
		T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
		T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
		T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
		T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
		T1.Broker_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt ,  
		Isnull(Dr.Bse_FO_Rate,0) AS 'bse_rate', /**/
		Isnull(Dr.Nse_FO_Rate,0) AS 'nse_rate' /**/
		
		INTO #alldata_Summary 
		FROM #mainoutputtable_1_Final_Summary  T1
		LEFT JOIN BrokerBill T2 ON T1.Trans_No=T2.Trans_no
		LEFT JOIN DailyRate  DR  
		ON 
			DR.InvestmentType != 0 and Dr.InvestmentType != 2 AND
			DR.Script_Code = T1.ScriptCode and  Convert(varchar,dr.Trans_Dt,101) =  Convert(varchar,@Todate,101) AND 
			Convert(varchar,DR.Expir_Date ,101) =  Convert(varchar,T1.Last_Date,101) AND
			ISNULL(Substring(RTRIM(LTRIM(T1.OptionType)),0,3),'') = ISNULL( DR.OptionType,'') AND
			ISNULL(DR.Strike_Price,0) = ISNULL(T1.Strike_Price,'')
		ORDER BY Broker_name

		
		TRUNCATE TABLE #mainoutputtable_1_Final_Summary

		INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		Broker_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt) 

		SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		Broker_name,
		Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 
		FROM #alldata_Summary  


		GROUP BY Broker_name,id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 
		ORDER BY Broker_name

		IF(@RecordOnlyhavingClosingbalanceZero = 0)
			BEGIN
			IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
				BEGIN
						
					SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
					CASE
						WHEN closing_qty < 0 THEN sold_date
						WHEN ISNULL(opening_date,'') != '' THEN opening_date
						WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
					END  AS  'Closing Date',
					bse_rate  AS  'BSERATE',
					bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
					CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  END  AS  'BSE_UnRealizedGainLoss',
					nse_rate AS  'NSERATE',
					nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
					CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
					SUM(gain_loss) AS 'Profit/Loss',
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
							ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
							0 END 
							END AS 'Avg. Rate',

						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
							ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
							0 END 
							END AS 'Value After Profit/Loss',
					SUM(ISNULL(Other_amt,0))Other_amt, Broker_name
					FROM #mainoutputtable_1_Final_Summary
					GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate,
					CASE
						WHEN closing_qty < 0 THEN sold_date
						WHEN ISNULL(opening_date,'') != '' THEN opening_date
						WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
					END,bse_rate,nse_rate,Broker_name
					HAVING SUM(closing_qty) != 0
					--HAVING (sum (CASE WHEN @RecordOnlyhavingClosingbalanceZero = 0 
					--	THEN closing_qty end  )!=0
									
											END
			ELSE IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0)
				BEGIN
								
					SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
					''  'Closing Date',
					bse_rate  AS  'BSERATE',
					bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
					CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  END  AS  'BSE_UnRealizedGainLoss',
					nse_rate AS  'NSERATE',
					nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
					CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
					SUM(gain_loss) AS 'Profit/Loss',
					CASE WHEN 
							SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
						ELSE
					CASE WHEN 
							SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
						0 END 
						END AS 'Avg. Rate',

					CASE WHEN 
							SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
						ELSE
					CASE WHEN 
							SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
						0 END 
						END AS 'Value After Profit/Loss',

					SUM(ISNULL(Other_amt,0))Other_amt, Broker_name
					FROM #mainoutputtable_1_Final_Summary
					GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate 
					HAVING SUM(closing_qty) != 0
				END
			ELSE IF(@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1)
				BEGIN
								
					SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
					CASE
						WHEN closing_qty < 0 THEN sold_date
						WHEN ISNULL(opening_date,'') != '' THEN opening_date
						WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
					END  AS  'Closing Date',
					bse_rate  AS  'BSERATE',
					bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
					CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  END  AS  'BSE_UnRealizedGainLoss',
					nse_rate AS  'NSERATE',
					nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
					CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
					SUM(gain_loss) AS 'Profit/Loss',
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
							ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
							0 END 
							END AS 'Avg. Rate',

						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
							ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
							0 END 
							END AS 'Value After Profit/Loss',
					SUM(ISNULL(Other_amt,0))Other_amt,Broker_name
					FROM #mainoutputtable_1_Final_Summary
					GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate,opening_date, purchase_date,sold_date,closing_qty
					HAVING SUM(closing_qty) != 0
				END
			ELSE --IF(@WithActualAvgRate = 0)
				BEGIN
					SELECT holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
					bse_rate  AS  'BSERATE',
					bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
					CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
					nse_rate AS  'NSERATE',
					nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
					CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
					SUM(gain_loss) AS 'Profit/Loss',
						CASE WHEN 
							SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
						ELSE
					CASE WHEN 
							SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
						0 END 
						END AS 'Avg. Rate',

					CASE WHEN 
							SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
						ELSE
					CASE WHEN 
							SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
						0 END 
						END AS 'Value After Profit/Loss',
					0 Other_amt,  Broker_name
					FROM #mainoutputtable_1_Final_Summary
					GROUP BY Broker_name,holding_type,script_name,bse_rate,nse_rate 
					HAVING SUM(closing_qty) != 0
				END
END
		ELSE
			BEGIN
			IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
					BEGIN
						
						SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
						CASE
							WHEN closing_qty < 0 THEN sold_date
							WHEN ISNULL(opening_date,'') != '' THEN opening_date
							WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
						END  AS  'Closing Date',
						bse_rate  AS  'BSERATE',
						bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
						CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  END  AS  'BSE_UnRealizedGainLoss',
						nse_rate AS  'NSERATE',
						nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
						CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
						SUM(gain_loss) AS 'Profit/Loss',
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
								ELSE
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) >=0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
								0 END 
								END AS 'Avg. Rate',

							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
								ELSE
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) >= 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
								0 END 
								END AS 'Value After Profit/Loss',
						SUM(ISNULL(Other_amt,0))Other_amt, Broker_name
						FROM #mainoutputtable_1_Final_Summary
						GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate,
						CASE
							WHEN closing_qty < 0 THEN sold_date
							WHEN ISNULL(opening_date,'') != '' THEN opening_date
							WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
						END,bse_rate,nse_rate,Broker_name
						HAVING SUM(closing_qty) = 0
						--HAVING (sum (CASE WHEN @RecordOnlyhavingClosingbalanceZero = 0 
						--	THEN closing_qty end  )!=0
									
												END
				ELSE IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0)
					BEGIN
								
						SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
						''  'Closing Date',
						bse_rate  AS  'BSERATE',
						bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
						CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  END  AS  'BSE_UnRealizedGainLoss',
						nse_rate AS  'NSERATE',
						nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
						CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
						SUM(gain_loss) AS 'Profit/Loss',
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
								ELSE
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
								0 END 
								END AS 'Avg. Rate',

							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
								ELSE
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
								0 END 
								END AS 'Value After Profit/Loss',
						SUM(ISNULL(Other_amt,0))Other_amt,  Broker_name
						FROM #mainoutputtable_1_Final_Summary
						GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate 
						HAVING SUM(closing_qty) = 0
					END
				ELSE IF(@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1)
					BEGIN
								
						SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
						CASE
							WHEN closing_qty < 0 THEN sold_date
							WHEN ISNULL(opening_date,'') != '' THEN opening_date
							WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
						END  AS  'Closing Date',
						bse_rate  AS  'BSERATE',
						bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
						CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  END  AS  'BSE_UnRealizedGainLoss',
						nse_rate AS  'NSERATE',
						nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
						CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
						SUM(gain_loss) AS 'Profit/Loss',
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
								ELSE
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
								0 END 
								END AS 'Avg. Rate',

							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
								ELSE
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
								0 END 
								END AS 'Value After Profit/Loss',
						SUM(ISNULL(Other_amt,0))Other_amt, Broker_name
						FROM #mainoutputtable_1_Final_Summary
						GROUP BY Broker_name, holding_type,script_name,bse_rate,nse_rate,opening_date, purchase_date,sold_date,closing_qty
						HAVING SUM(closing_qty) != 0
					END
				ELSE --IF(@WithActualAvgRate = 0)
					BEGIN
						SELECT holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
						bse_rate  AS  'BSERATE',
						bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
						CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
						nse_rate AS  'NSERATE',
						nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
						CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
						SUM(gain_loss) AS 'Profit/Loss',
							CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
							ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
							0 END 
							END AS 'Avg. Rate',

						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
							ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
							0 END 
							END AS 'Value After Profit/Loss',
						0 Other_amt,  Broker_name
						FROM #mainoutputtable_1_Final_Summary
						GROUP BY Broker_name,holding_type,script_name,bse_rate,nse_rate 
						HAVING SUM(closing_qty) = 0
					END
			END


			Select Broker_Name,Sum(ISNULL (gain_loss,0)) from #mainoutputtable_1_Final_Summary 
			Group By Broker_Name
			Having Sum(ISNULL (gain_loss,0))!=0
			Order by 1

			Select  sum(Other_amt) as 'Expense_Amount' from BrokerBill where Member_code=@memcode and Yearcode=@yearcode and isfnoBill=@Investmenttype and Trans_Dt<=@Todate
END





























GO
/****** Object:  StoredProcedure [dbo].[proc_Stockholdingposition_CapitalStock_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockholdingposition_CapitalStock_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Stockholdingposition_CapitalStock_Summary] AS' 
END
GO


----GO  
-- proc_Stockholdingposition_CapitalStock_Summary 0,0,'0','30001','1120172018','04/01/2017','06/15/2017','','','','', '0' ,'0','details' 
-- proc_Stockholdingposition_Equity 0,0,'0','30001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','WholeMainTableData' 
ALTER PROCEDURE [dbo].[proc_Stockholdingposition_CapitalStock_Summary] 
--0,0,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','ScriptWiseTotal' 
(
	@status          INT, 
	@Investmenttype  INT, 
	@Ac_Type         NVARCHAR(100), 
	@memcode         VARCHAR(100), 
	@yearcode        VARCHAR(100), 
	@Fromdate        VARCHAR(30), 
	@Todate          VARCHAR(30), 
	@ScriptCode      VARCHAR(max), 
	@ConsultantCode  VARCHAR(max), 
	@BSE_NSE_Code    VARCHAR(max), 
	@Is_BFCF         VARCHAR(max), 
	@IsIntraDay      VARCHAR(max), 
	@short_Long_Term INT, 
	@OUTPUT_Flag     VARCHAR(max), 
	@IsScripWise     BIT = 1,
	@ScriptName		 VARCHAR(max) = ''
	) 
AS 
  BEGIN 
  SET NOCOUNT ON;
      DECLARE @StartYear VARCHAR(4) = (SELECT Substring(@yearcode, 3, 4)) 
      DECLARE @EndYear VARCHAR(4) = (SELECT Substring(@yearcode, 7, 4)) 

      CREATE TABLE #mainoutputtable_1_final_capstock_summary 
        ( 
           pkid             INT, 
           dup_pkid         INT, 
           trans_no         VARCHAR(20), 
           ac_type          VARCHAR(20), 
           id               INT, 
           script_name      VARCHAR(500), 
           holding_type     VARCHAR(200), 
           opening_bill_no  VARCHAR(10), 
           opening_date     DATETIME, 
           opening_qty      FLOAT DEFAULT 0, 
           opening_rate     FLOAT DEFAULT 0, 
           opening_amount   FLOAT DEFAULT 0, 
           purchase_date    DATETIME, 
           purchase_bill_no VARCHAR(100), 
           purchase_qty     FLOAT DEFAULT 0, 
           purchase_rate    FLOAT DEFAULT 0, 
           purchase_amount  FLOAT DEFAULT 0, 
           sold_date        DATETIME, 
           sold_bill_no     VARCHAR(100), 
           sold_qty         FLOAT DEFAULT 0, 
           sold_rate        FLOAT DEFAULT 0, 
           sold_amount      FLOAT DEFAULT 0, 
           gain_loss        FLOAT DEFAULT 0, 
           gain             FLOAT DEFAULT 0, 
           loss             FLOAT DEFAULT 0, 
           closing_qty      FLOAT DEFAULT 0, 
           closing_rate     FLOAT DEFAULT 0, 
           closing_value    FLOAT DEFAULT 0, 
           short_term       FLOAT DEFAULT 0, 
           long_term        FLOAT DEFAULT 0, 
           speculation      FLOAT DEFAULT 0, 
           gain_speculation FLOAT DEFAULT 0, 
           loss_speculation FLOAT DEFAULT 0, 
           isintradaycol    INT, 
           scriptcode       VARCHAR(50) 
        ) 

      IF(@Investmenttype = 0 OR @Investmenttype = 2)
		BEGIN
		  INSERT INTO #mainoutputtable_1_final_capstock_summary 
		  EXEC Proc_stockholdingposition_equity 
			@status, 
			@Investmenttype, 
			@Ac_Type, 
			@memcode, 
			@yearcode, 
			@Fromdate, 
			@Todate, 
			@ScriptCode, 
			@ConsultantCode, 
			@BSE_NSE_Code, 
			@Is_BFCF, 
			@IsIntraDay, 
			@short_Long_Term, 
			'WholeMainTableData' 
		END
	ELSE
	BEGIN
		  INSERT INTO #mainoutputtable_1_final_capstock_summary 
		  EXEC proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency 
			@status, 
			@Investmenttype, 
			@Ac_Type, 
			@memcode, 
			@yearcode, 
			@Fromdate, 
			@Todate, 
			@ScriptCode, 
			@ConsultantCode, 
			@BSE_NSE_Code, 
			@Is_BFCF, 
			@IsIntraDay, 
			@short_Long_Term, 
			'WholeMainTableData',
			0,
			@ScriptName
		END


      IF( @OUTPUT_Flag = 'Details' ) 
        BEGIN 
            --select top  1 convert(date,opening_date,103),convert(date,purchase_date,103),sold_date from #mainoutputtable_1_Final_CapStock_Summary
            SELECT opening_bill_no, 
                   scriptcode, 
                   script_name                     'Script Name', 
                   Sum(Isnull(opening_qty, 0))     'Opening Qty', 
                   Sum(Isnull(opening_amount, 0))  'Opening Amount', 
                   Sum(Isnull(purchase_qty, 0))    'Purchase Qty', 
                   Sum(Isnull(purchase_amount, 0)) 'Purchase Amount', 
                   Sum(Isnull(sold_qty, 0))        'Sold Qty', 
                   Sum(Isnull(sold_amount, 0))     'Sold Amount', 
                   Sum(Isnull(gain_loss, 0))       'Gain/Loss', 
                   CASE 
                     WHEN Sum(Isnull(gain_loss, 0)) > 0 
					 THEN Sum(Isnull(gain_loss, 0)) 
                     ELSE 0 
                   END                             AS 'Gain', 
                   CASE 
                     WHEN Sum(Isnull(gain_loss, 0)) < 0 
					 THEN Sum(Isnull(gain_loss, 0)) 
                     ELSE 0 
                   END                             AS 'Loss', 
                   Sum(Isnull(short_term, 0))      short_term, 
                   Sum(Isnull(long_term, 0))       long_term, 
                   Sum(Isnull(speculation, 0))     speculation, 
                   0                               isintradaycol 
            INTO   #main 
            FROM   (SELECT opening_bill_no, 
                           scriptcode, 
                           script_name                     'Script_Name', 
                           Sum(Isnull(opening_qty, 0))     'Opening_Qty', 
                           Sum(Isnull(opening_amount, 0))  'Opening_Amount', 
                           Sum(Isnull(purchase_qty, 0))    'purchase_qty', 
                           Sum(Isnull(purchase_amount, 0)) 'purchase_amount', 
                           Sum(Isnull(sold_qty, 0))        'sold_qty', 
                           Sum(Isnull(sold_amount, 0))     'sold_amount', 
                           Sum(Isnull(gain_loss, 0))       'gain_loss', 
                           CASE 
                             WHEN Sum(Isnull(gain_loss, 0)) > 0 
							 THEN Sum(Isnull(gain_loss, 0)) 
                             ELSE 0 
                           END AS 'Gain', 
                           CASE 
                             WHEN Sum(Isnull(gain_loss, 0)) < 0 
							 THEN Sum(Isnull(gain_loss, 0)) 
							 ELSE 0 
                           END AS 'Loss', 
                           Sum(Isnull(short_term, 0))      short_term, 
                           Sum(Isnull(long_term, 0))       long_term, 
                           Sum(Isnull(speculation, 0))     speculation, 
                           0                               isintradaycol 
                    FROM   #mainoutputtable_1_final_capstock_summary 
                    GROUP  BY scriptcode, 
                              script_name, 
                              opening_bill_no, 
                              sold_qty, 
                              opening_qty, 
                              purchase_qty 
                    HAVING ( ( Isnull(sold_qty, 0) ) <> 0 ) 
                           AND ( ( Isnull(opening_qty, 0) ) != 0 
                                  OR ( Isnull(purchase_qty, 0) ) != 0 )) a 
            GROUP  BY scriptcode, 
                      script_name, 
                      opening_bill_no 

            DECLARE @StartDate VARCHAR(15) = '01/04/' + @StartYear 
            DECLARE @EndDate VARCHAR(15) = '15/06/' + @StartYear 
            DECLARE @Title VARCHAR(25) = @StartDate + ' TO ' + @EndDate 
			
			DECLARE @gain_loss		FLOAT
			DECLARE @short_term		FLOAT
			DECLARE @long_term		FLOAT
			DECLARE @speculation	FLOAT
			DECLARE @gain			FLOAT
			DECLARE @loss			FLOAT

		

            /*First Group*/ 
		--	Select * from #mainoutputtable_1_final_capstock_summary

            SELECT 'First Group'							AS 'Opening_Date', 
                   ''										AS 'purchase_date', 
                   @Title									AS 'Title', 
                   Round(ISNULL(Sum(gain_loss),0),2)				AS 'Gain/Loss', 
                   Round(ISNULL(Sum(short_term),0),2)				AS 'short_term', 
                   Round(ISNULL(Sum(long_term),0),2)				AS 'long_term',
                   Round(ISNULL(Sum(speculation),0),2)				AS 'speculation', 
                   Round(ISNULL(Sum(gain),0),2)						AS 'Gain', 
                   Round(ISNULL(Sum(loss),0),2)						AS 'Loss' 

            INTO   #qaurter1 
            FROM   (SELECT CONVERT(DATE, opening_date, 103)  'Opening_Date', 
                           CONVERT(DATE, purchase_date, 103) 'Purchase_Date', 
                           CONVERT(DATE, sold_date, 103)     'Sold_Date', 
                           Round(Sum(Isnull(gain_loss, 0)),2)         'gain_loss', 
                           CASE 
                             WHEN Round(Sum(Isnull(gain_loss, 0)),2) > 0 
							 THEN Round(Sum(Isnull(gain_loss, 0)),2) 
                             ELSE 0 
                           END  AS 'Gain', 
                           CASE 
                             WHEN Round(Sum(Isnull(gain_loss, 0)),2) < 0 
							 THEN Round(Sum(Isnull(gain_loss, 0)),2) 
                             ELSE 0 
                           END  AS 'Loss', 
                           Round(Sum(Isnull(short_term, 0)),2)        short_term, 
                           Round(Sum(Isnull(long_term, 0)),2)         long_term, 
                           Round(Sum(Isnull(speculation, 0)),2)       speculation 
                    FROM   #mainoutputtable_1_final_capstock_summary 
                    WHERE ((CONVERT(DATE, opening_date, 103) IS NOT NULL and CONVERT(DATE, opening_date, 103) <= CONVERT(DATE, @EndDate, 103) )
							OR ( CONVERT(DATE, purchase_date, 103) IS NOT NULL AND  CONVERT(DATE, purchase_date, 103) >=CONVERT(DATE, @StartDate, 103)  and  CONVERT(DATE, purchase_date, 103) <= CONVERT(DATE, @EndDate, 103) ))
						  AND (CONVERT(DATE, sold_date, 103) >=  CONVERT(DATE, @StartDate, 103)  and CONVERT(DATE, sold_date, 103) <= CONVERT(DATE, @EndDate, 103) )

                    GROUP  BY opening_date, 
                              purchase_date, 
                              sold_date 
                    HAVING Sum(Isnull(gain_loss, 0)) != 0)a 

		    SELECT  @gain_loss    = Round(ISNULL(q1.[Gain/Loss],0),2), 
					@short_term   = Round(ISNULL(q1.[short_term],0),2),
					@long_term    = Round(ISNULL(q1.[long_term],0),2), 
					@speculation  = Round(ISNULL(q1.[speculation],0),2), 
					@gain		  = Round(ISNULL(q1.[Gain],0),2),
					@loss		  = Round(ISNULL(q1.[Loss],0),2)
			FROM #qaurter1 q1

            --/*Second Group*/ 
			SET @EndDate = '15/09/' + @StartYear 
            SET @Title   = '16/06/' + @StartYear + ' TO ' + @EndDate 
            
			SELECT 'Second Group'											AS 'Opening_Date', 
                   ''														AS 'purchase_date', 
                   @Title													AS 'Title', 
                   Round(ISNULL(Sum(gain_loss),0)		 - @gain_loss,2)   		AS 'Gain/Loss', 
                   Round(ISNULL(Sum(short_term),0)		 - @short_term,2)  		AS 'short_term', 
                   Round(ISNULL(Sum(long_term),0)		 - @long_term,2)			AS 'long_term',
                   Round(ISNULL(Sum(speculation),0)		 - @speculation,2) 		AS 'speculation', 
                   Round(ISNULL(Sum(gain),0)			 - @gain,2)				AS 'Gain', 
                   Round(ISNULL(Sum(loss),0)			 - @loss,2)				AS 'Loss' 
            INTO   #qaurter2 
            FROM   (SELECT CONVERT(DATE, opening_date, 103)  'Opening_Date', 
                           CONVERT(DATE, purchase_date, 103) 'Purchase_Date', 
                           CONVERT(DATE, sold_date, 103)     'Sold_Date', 
                           Round(Sum(Isnull(gain_loss, 0)),2)         'gain_loss', 
                           CASE 
                             WHEN Round(Sum(Isnull(gain_loss, 0)),2) > 0 
							 THEN Round(Sum( Isnull(gain_loss, 0)),2) 
                             ELSE 0 
                           END  AS 'Gain', 
                           CASE 
                             WHEN Round(Sum(Isnull(gain_loss, 0)),2) < 0 
							 THEN Round(Sum( Isnull(gain_loss, 0)),2) 
                             ELSE 0 
                           END  AS 'Loss', 
                           Round(Sum(Isnull(short_term, 0)),2)        short_term, 
                           Round(Sum(Isnull(long_term, 0)),2)         long_term, 
                           Round(Sum(Isnull(speculation, 0)),2)       speculation 
                    FROM   #mainoutputtable_1_final_capstock_summary 
					WHERE ((CONVERT(DATE, opening_date, 103) IS NOT NULL and CONVERT(DATE, opening_date, 103) <= CONVERT(DATE, @EndDate, 103) )
							OR ( CONVERT(DATE, purchase_date, 103) IS NOT NULL AND  CONVERT(DATE, purchase_date, 103) >=CONVERT(DATE, @StartDate, 103)  and  CONVERT(DATE, purchase_date, 103) <= CONVERT(DATE, @EndDate, 103) ))
						  AND (CONVERT(DATE, sold_date, 103) >=  CONVERT(DATE, @StartDate, 103)  and CONVERT(DATE, sold_date, 103) <= CONVERT(DATE, @EndDate, 103) )

                    GROUP  BY opening_date, 
                              purchase_date, 
                              sold_date 
                    HAVING Sum(Isnull(gain_loss, 0)) != 0)a 

         
			 SELECT @gain_loss   =  CASE WHEN Round((ISNULL(q2.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q2.[Gain/Loss],0)),2)   = 0 THEN @gain_loss     ELSE Round(@gain_loss	    + Round(ISNULL(q2.[Gain/Loss],0),2),2)   END, 
					@short_term  =  CASE WHEN Round((ISNULL(q2.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q2.[short_term],0)),2)  = 0 THEN @short_term    ELSE Round(@short_term	+ Round(ISNULL(q2.[short_term],0),2),2)  END,
					@long_term   =  CASE WHEN Round((ISNULL(q2.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q2.[long_term],0)),2)   = 0 THEN @long_term	   ELSE Round(@long_term	+ Round(ISNULL(q2.[long_term],0),2),2)   END, 
					@speculation =  CASE WHEN Round((ISNULL(q2.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q2.[speculation],0)),2) = 0 THEN @speculation   ELSE Round(@speculation	+ Round(ISNULL(q2.[speculation],0),2),2) END, 
					@gain        =  CASE WHEN Round((ISNULL(q2.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q2.[Gain],0)),2)        = 0 THEN @gain          ELSE Round(@gain			+ Round(ISNULL(q2.[Gain],0),2),2)        END, 
					@loss		 =  CASE WHEN Round((ISNULL(q2.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q2.[Loss],0)),2)        = 0 THEN @loss          ELSE Round(@loss			+ Round(ISNULL(q2.[Loss],0),2),2)        END
			FROM #qaurter2 q2
		

            /*Third Group*/ 
			SET @EndDate = '15/12/' + @StartYear 
            SET @Title   = '16/09/' + @StartYear + ' TO ' + @EndDate 

            SELECT  'Third Group'											AS 'Opening_Date', 
                   ''														AS 'purchase_date', 
                   @Title													AS 'Title', 
                   Round(ISNULL(Sum(gain_loss),0)		 - @gain_loss,2)   	        AS 'Gain/Loss', 
                   Round(ISNULL(Sum(short_term),0)		 - @short_term ,2)  		AS 'short_term', 
                   Round(ISNULL( Sum(long_term),0)		 - @long_term,2) 			AS 'long_term',
                   Round(ISNULL(Sum(speculation),0)		 - @speculation,2)  		AS 'speculation', 
                   Round(ISNULL(Sum(gain),0)			 - @gain,2) 				AS 'Gain', 
                   Round(ISNULL(Sum(loss),0)			 - @loss,2) 				AS 'Loss' 
            INTO   #qaurter3 
            FROM   (SELECT CONVERT(DATE, opening_date, 103)  'Opening_Date', 
                           CONVERT(DATE, purchase_date, 103) 'Purchase_Date', 
                           CONVERT(DATE, sold_date, 103)     'Sold_Date', 
                           Round(Sum(Isnull(gain_loss, 0)),2)         'gain_loss', 
                           CASE 
                             WHEN Round(Sum(Isnull(gain_loss, 0)),2) > 0 
							 THEN Round(Sum(Isnull(gain_loss, 0)),2) 
                             ELSE 0 
                           END                               AS 'Gain', 
                           CASE 
                             WHEN Round(Sum(Isnull(gain_loss, 0)),2) < 0 
							 THEN Round(Sum( Isnull(gain_loss, 0)),2) 
                             ELSE 0 
                           END                               AS 'Loss', 
                           Round(Sum(Isnull(short_term, 0)),2)        short_term, 
                           Round(Sum(Isnull(long_term, 0)),2)         long_term, 
                           Round(Sum(Isnull(speculation, 0)),2)       speculation 
                    FROM   #mainoutputtable_1_final_capstock_summary 
                    WHERE ((CONVERT(DATE, opening_date, 103) IS NOT NULL and CONVERT(DATE, opening_date, 103) <= CONVERT(DATE, @EndDate, 103) )
							OR ( CONVERT(DATE, purchase_date, 103) IS NOT NULL AND  CONVERT(DATE, purchase_date, 103) >=CONVERT(DATE, @StartDate, 103)  and  CONVERT(DATE, purchase_date, 103) <= CONVERT(DATE, @EndDate, 103) ))
						  AND (CONVERT(DATE, sold_date, 103) >=  CONVERT(DATE, @StartDate, 103)  and CONVERT(DATE, sold_date, 103) <= CONVERT(DATE, @EndDate, 103) )
                    GROUP  BY opening_date, 
                              purchase_date, 
                              sold_date 
                    HAVING Sum(Isnull(gain_loss, 0)) != 0)a 

           
			 SELECT @gain_loss   =  CASE WHEN Round((ISNULL(q3.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q3.[Gain/Loss],0)),2)   = 0 THEN @gain_loss	     ELSE Round(@gain_loss	+ Round(ISNULL(q3.[Gain/Loss],0),2),2)    END, 
					@short_term  =  CASE WHEN ROUND((ISNULL(q3.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q3.[short_term],0)),2)  = 0 THEN @short_term      ELSE Round(@short_term	+ Round(ISNULL(q3.[short_term],0),2),2)   END,
					@long_term   =  CASE WHEN Round((ISNULL(q3.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q3.[long_term],0)),2)   = 0 THEN @long_term	     ELSE Round(@long_term	+ Round(ISNULL(q3.[long_term],0),2),2)    END, 
					@speculation =  CASE WHEN Round((ISNULL(q3.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q3.[speculation],0)),2) = 0 THEN @speculation     ELSE Round(@speculation	+ Round(ISNULL(q3.[speculation],0),2),2)  END,
					@gain        =  CASE WHEN Round((ISNULL(q3.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q3.[Gain],0)),2)        = 0 THEN @gain            ELSE Round(@gain			+ Round(ISNULL(q3.[Gain],0),2),2)         END, 
					@loss		 =  CASE WHEN Round((ISNULL(q3.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q3.[Loss],0)),2)        = 0 THEN @loss            ELSE Round(@loss			+ Round(ISNULL(q3.[Loss],0),2),2)         END
			 FROM #qaurter3 q3

            /*Fourth Group*/ 
			SET @EndDate = '15/03/' + @EndYear 
            SET @Title   = '16/12/' + @StartYear + ' TO ' + @EndDate 

			
            SELECT   'Fourth Group'											AS 'Opening_Date', 
                   ''														AS 'purchase_date', 
                   @Title													AS 'Title', 
                   Round(ISNULL(Sum(gain_loss),0),2)	     - @gain_loss   		AS 'Gain/Loss', 
                   Round(ISNULL(Sum(short_term),0),2)		 - @short_term  		AS 'short_term', 
                   Round(ISNULL(Sum(long_term),0),2)		 - @long_term			AS 'long_term',
                   Round(ISNULL(Sum(speculation),0),2)		 - @speculation 		AS 'speculation', 
                   Round(ISNULL(Sum(gain),0),2)				 - @gain				AS 'Gain', 
                   Round(ISNULL(Sum(loss),0),2)				 - @loss				AS 'Loss' 
            INTO   #qaurter4 
            FROM   (SELECT CONVERT(DATE, opening_date, 103)  'Opening_Date', 
                           CONVERT(DATE, purchase_date, 103) 'Purchase_Date', 
                           CONVERT(DATE, sold_date, 103)     'Sold_Date', 
                           Round(Sum(Isnull(gain_loss, 0)),2)         'gain_loss', 
                           CASE 
                             WHEN Round(Sum(Isnull(gain_loss, 0)),2) > 0 
							 THEN Round(Sum(Isnull(gain_loss, 0)),2) 
                             ELSE 0 
                           END                               AS 'Gain', 
                           CASE 
                             WHEN Round(Sum(Isnull(gain_loss, 0)),2) < 0 
							 THEN Round(Sum(Isnull(gain_loss, 0)),2) 
                             ELSE 0 
                           END                               AS 'Loss', 
                           Round(Sum(Isnull(short_term, 0)),2)        short_term, 
                           Round(Sum(Isnull(long_term, 0)),2)         long_term, 
                           Round(Sum(Isnull(speculation, 0)),2)       speculation 
                    FROM   #mainoutputtable_1_final_capstock_summary 
                    WHERE ((CONVERT(DATE, opening_date, 103) IS NOT NULL and CONVERT(DATE, opening_date, 103) <= CONVERT(DATE, @EndDate, 103) )
							OR ( CONVERT(DATE, purchase_date, 103) IS NOT NULL AND  CONVERT(DATE, purchase_date, 103) >=CONVERT(DATE, @StartDate, 103)  and  CONVERT(DATE, purchase_date, 103) <= CONVERT(DATE, @EndDate, 103) ))
						  AND (CONVERT(DATE, sold_date, 103) >=  CONVERT(DATE, @StartDate, 103)  and CONVERT(DATE, sold_date, 103) <= CONVERT(DATE, @EndDate, 103) )
                    GROUP  BY opening_date, 
                              purchase_date, 
                              sold_date 
                    HAVING Sum(Isnull(gain_loss, 0)) != 0)a 
			 
			 SELECT @gain_loss   =  CASE WHEN Round((ISNULL(q4.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q4.[Gain/Loss],0)),2)   = 0 THEN @gain_loss	   ELSE Round(@gain_loss	+ Round(ISNULL(q4.[Gain/Loss],0),2),2)    END, 
					@short_term  =  CASE WHEN Round((ISNULL(q4.[Gain/Loss],0)),2) IS NULL OR ROUND((ISNULL(q4.[short_term],0)),2)  = 0 THEN @short_term    ELSE Round(@short_term	+ Round(ISNULL(q4.[short_term],0),2),2)   END,
					@long_term   =  CASE WHEN Round((ISNULL(q4.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q4.[long_term],0)),2)   = 0 THEN @long_term	   ELSE Round(@long_term	+ Round(ISNULL(q4.[long_term],0),2),2)   END, 
					@speculation =  CASE WHEN Round((ISNULL(q4.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q4.[speculation],0)),2) = 0 THEN @speculation   ELSE Round(@speculation	+ Round(ISNULL(q4.[speculation],0),2),2)  END,
					@gain        =  CASE WHEN Round((ISNULL(q4.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q4.[Gain],0)),2)        = 0 THEN @gain          ELSE Round(@gain			+ Round(ISNULL(q4.[Gain],0),2),2)         END, 
					@loss		 =  CASE WHEN Round((ISNULL(q4.[Gain/Loss],0)),2) IS NULL OR Round((ISNULL(q4.[Loss],0)),2)        = 0 THEN @loss          ELSE Round(@loss			+ Round(ISNULL(q4.[Loss],0),2),2)         END
			FROM #qaurter4 q4

            /*Fifth Group*/ 
			SET @EndDate = '31/03/' + @EndYear 
            SET @Title	 ='16/03/' + @EndYear + ' TO ' + @EndDate 
		    SELECT  'Fifth Group'											AS 'Opening_Date', 
                   ''														AS 'purchase_date', 
                   @Title													AS 'Title', 
                   Round(ISNULL(Sum(gain_loss),0),2)		 - @gain_loss   	    AS 'Gain/Loss', 
                   Round(ISNULL(Sum(short_term),0),2)		 - @short_term  		AS 'short_term', 
                   Round(ISNULL(Sum(long_term),0),2)		 - @long_term			AS 'long_term',
                   Round(ISNULL(Sum(speculation),0),2)		 - @speculation 		AS 'speculation', 
                   Round(ISNULL(Sum(gain),0),2)				 - @gain				AS 'Gain', 
                   Round(ISNULL(Sum(loss),0),2)				 - @loss				AS 'Loss' 
            INTO   #qaurter5
            FROM   (SELECT CONVERT(DATE, opening_date, 103)  'Opening_Date', 
                           CONVERT(DATE, purchase_date, 103) 'Purchase_Date', 
                           CONVERT(DATE, sold_date, 103)     'Sold_Date', 
                           Round(Sum(Isnull(gain_loss, 0)),2) 'gain_loss', 
                           CASE 
                             WHEN  Round(Sum(Isnull(gain_loss, 0)),2) > 0 
							 THEN  Round(Sum(Isnull(gain_loss, 0)),2) 
                             ELSE 0 
                           END                               AS 'Gain', 
                           CASE 
                             WHEN  Round(Sum(Isnull(gain_loss, 0)),2) < 0 
							 THEN  Round(Sum( Isnull(gain_loss, 0)),2) 
                             ELSE 0 
                           END                               AS 'Loss', 
                            Round(Sum(Isnull(short_term, 0)),2)        short_term, 
                            Round(Sum(Isnull(long_term, 0)),2)           long_term, 
                            Round(Sum(Isnull(speculation, 0)),2)         speculation 
                    FROM   #mainoutputtable_1_final_capstock_summary 
                    WHERE ((CONVERT(DATE, opening_date, 103) IS NOT NULL and CONVERT(DATE, opening_date, 103) <= CONVERT(DATE, @EndDate, 103) )
							OR ( CONVERT(DATE, purchase_date, 103) IS NOT NULL AND  CONVERT(DATE, purchase_date, 103) >=CONVERT(DATE, @StartDate, 103)  and  CONVERT(DATE, purchase_date, 103) <= CONVERT(DATE, @EndDate, 103) ))
						  AND (CONVERT(DATE, sold_date, 103) >=  CONVERT(DATE, @StartDate, 103)  and CONVERT(DATE, sold_date, 103) <= CONVERT(DATE, @EndDate, 103) )
                    GROUP  BY opening_date, 
                              purchase_date, 
                              sold_date 
                    HAVING Sum(Isnull(gain_loss, 0)) != 0)a 



            /*Sixth Group - Whole Year*/ 
			SET @EndDate = '01/04/' + @EndYear 
            SET @EndDate = '31/03/' + @EndYear 
			SET @Title  = @StartDate + ' TO ' + @EndDate

            SELECT  ' Sixth Group'					AS 'Opening_Date', 
                   ''								AS 'purchase_date', 
                   @Title							AS 'Title', 
                   Round(ISNULL(Sum(gain_loss),0),2) 		AS 'Gain/Loss', 
                   Round(ISNULL(Sum(short_term),0),2)		AS 'short_term', 
                   Round(ISNULL(Sum(long_term),0),2)			AS 'long_term',
                   Round(ISNULL(Sum(speculation),0),2)		AS 'speculation', 
                   Round(ISNULL(Sum(gain),0),2)				AS 'Gain', 
                   Round(ISNULL(Sum(loss),0),2)				AS 'Loss' 
            INTO   #fullyear 
            FROM   (SELECT CONVERT(DATE, opening_date, 103)  'Opening_Date', 
                           CONVERT(DATE, purchase_date, 103) 'Purchase_Date', 
                           CONVERT(DATE, sold_date, 103)     'Sold_Date', 
                           Round(Sum(Isnull(gain_loss, 0)),2)         'gain_loss', 
                           CASE 
                             WHEN Round(Sum(Isnull(gain_loss, 0)),2) > 0 
							 THEN Round(Sum(Isnull(gain_loss, 0)),2) 
                             ELSE 0 
                           END                               AS 'Gain', 
                           CASE 
                             WHEN Round(Sum(Isnull(gain_loss, 0)),2) < 0 
							 THEN Round(Sum(Isnull(gain_loss, 0)),2) 
                             ELSE 0 
                           END                               AS 'Loss', 
                           Round(Sum(Isnull(short_term, 0)),2)        short_term, 
                           Round(Sum(Isnull(long_term, 0)),2)         long_term, 
                           Round(Sum(Isnull(speculation, 0)),2)       speculation 
                    FROM   #mainoutputtable_1_final_capstock_summary 
                    GROUP  BY opening_date, 
                              purchase_date, 
                              sold_date 
                    HAVING Sum(Isnull(gain_loss, 0)) != 0)a 

		   
            SELECT * FROM   #main 

            SELECT * FROM   #qaurter1 

            SELECT * FROM   #qaurter2 

            SELECT * FROM   #qaurter3 

            SELECT * FROM   #qaurter4 

			SELECT * FROM   #qaurter5

            SELECT * FROM   #fullyear 
        END 

      DROP TABLE #mainoutputtable_1_final_capstock_summary 
  END 












GO
/****** Object:  StoredProcedure [dbo].[proc_Stockholdingposition_Equity]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockholdingposition_Equity]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Stockholdingposition_Equity] AS' 
END
GO


-- proc_Stockholdingposition_Equity 0,0,'','Y0001','1120172018','2017-04-01 12:00:00:00','2018-03-31 03:50:37:50','','','','', '0' ,'0','details',0
-- proc_Stockholdingposition_Equity 0,2,'0','30001','1120182019','2018-04-01 12:00:00:00','2019-03-31 03:50:37:50','','','','', '' ,'','details'
ALTER  PROCEDURE [dbo].[proc_Stockholdingposition_Equity] --0,0,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','ScriptWiseTotal'
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),
@IsIntraDay VARCHAR(max),@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX),
@IsScripWise bit = 1,@IsWithTax bit = 0,@IsFromMonthWise bit = 0, @IsLTCG bit=0,@IsBSEISIN bit=0)
AS 
  BEGIN 
	  SET NOCOUNT ON;
		DECLARE @StartYearDate varchar(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate = CONVERT(VARCHAR(10),@StartYearDate,101)
		CREATE TABLE #mainoutputtable_1
        ( 
		   pkid INT identity(1,1), 
		   Dup_pkid INT, 
           Trans_No VARCHAR(20),
		   Ac_type VARCHAR(20),
		   id INT,
		   sr_no int,
		   prioritys INT,
		   Trans_Type  VARCHAR(100), 
		   Split_Type VARCHAR(100), 
		   Flag_Type VARCHAR(100),
		   Flag_Type_Sold VARCHAR(100),
		   flag_script_name  VARCHAR(Max),
		   flag_holding_type VARCHAR(MAx), 
		   script_name  VARCHAR(Max),
		   holding_type VARCHAR(Max),
		   opening_bill_no VARCHAR(100),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount AS( [opening_qty] * [opening_rate] ), 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount AS( 
		   purchase_qty * purchase_rate ), 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount AS ( sold_qty * sold_rate ), 
           gain_loss float,
		   closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 

           closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
		   closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
		   short_term FLOAT DEFAULT 0,
		   long_term  FLOAT DEFAULT 0,
           speculation  FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   isintradaycol INT,[type] VARCHAR(100) , ScriptCode Varchar(50) ,
		   Broker_Code VARCHAR(100),Dp_code VARCHAR(100),Consultant_code VARCHAR(20)
        )  

		CREATE TABLE #mainoutputTable_1_BSEISISNO
		(
		   pkid INT,
		   Dup_pkid INT, 
		   Trans_No VARCHAR(20),
		   Ac_type VARCHAR(20),
		   id INT,
		   sr_no int,
		   prioritys INT,
		   Trans_Type  VARCHAR(100), 
		   Split_Type VARCHAR(100), 
		   Flag_Type VARCHAR(100),
		   Flag_Type_Sold VARCHAR(100),
		   flag_script_name  VARCHAR(Max),
		   flag_holding_type VARCHAR(MAx), 
		   script_name  VARCHAR(Max),
		   holding_type VARCHAR(Max),
		   opening_bill_no VARCHAR(100),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0,
		   purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0,
		   sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0,
		   gain_loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0,
		   closing_rate FLOAT DEFAULT 0,
		   closing_value  FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term  FLOAT DEFAULT 0,
           speculation  FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(100) ,
		   ScriptCode Varchar(50) ,
		   Broker_Code VARCHAR(100),
		   Dp_code VARCHAR(100),
		   Consultant_code VARCHAR(20)
		)

		CREATE TABLE #mainoutputtable_1_Final
        ( 
		   pkid int,
		   Dup_pkid int, 
		   OrderBy varchar(100),
           Trans_No VARCHAR(20),
		   Ac_type VARCHAR(50),
		   id INT,
		   sr_no int,
		   prioritys INT,
		   Split_Type VARCHAR(100), 
		   Flag_Type VARCHAR(100),
		   Flag_Type_Sold VARCHAR(100),
		   flag_script_name  VARCHAR(Max),
		   flag_holding_type VARCHAR(Max), 
		   script_name  VARCHAR(Max),
		   holding_type VARCHAR(Max),
		   opening_bill_no VARCHAR(100),		     
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,		   
		   isintradaycol INT,
		   [type] VARCHAR(100),
		   sort   VARCHAR(50) , 
		   ScriptCode Varchar(50) ,
		   Broker_Code VARCHAR(100),
		   Dp_code  VARCHAR(100),
		   Consultant_code VARCHAR(20)
       
	   ) 

		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty FLOAT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(100)
		DECLARE @showIntraday INT ,@ScriptId VARCHAR(50) ,@Ac_Types VARCHAR(100) 
		IF(@status=0)
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
				@openingDate VARCHAR(50),@openingRate FLOAT,@openingQty FLOAT,@openingAmount FLOAT,
				@purchaseDate VARCHAR(50),@PurchaseBillNo  VARCHAR(100),@purchaseRate FLOAT,@purchaseQty FLOAT,@purchaseAmount FLOAT,
				@soldDate VARCHAR(50),@soldBillNo  VARCHAR(100),@soldRate FLOAT,@soldQty FLOAT,@soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50),@Consultant_Name  VARCHAR(100), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(100),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,@PurchaseIntraFlag VARCHAR(100),@SaleIntraFlag VARCHAR(100) 
	
				DECLARE @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@Sr_No INT,@Broker_code VARCHAR(100),@Dp_code VARCHAR(100),@Consultant_code VARCHAR(20),@Dup_pkid int, @Pkid varchar(20),@idcount int  

				CREATE TABLE #SCriptCodes
				(
					ScriptCode varchar(MAX)
				)

				IF(@ScriptCode != '')
					INSERT INTO #SCriptCodes SELECT value FROM Fn_split(@ScriptCode, ',') 
				ELSE 
					INSERT INTO #SCriptCodes select BBT.Script_Code from mst_script 
					INNER JOIN BrokerBill_Trans  BBT ON BBT.Script_Code=Mst_Script.Script_Code  
					GROUP BY BBT.Script_Code

				CREATE TABLE #ConsultantCodes
				(
					ConsultantCodes varchar(MAX)
				)
				
				IF(@ConsultantCode = '0')	
					BEGIN
						SELECT DISTINCT p.member_code,p.year_code,
							STUFF((	SELECT distinct ',' + p1.Consultant_Code
									FROM Mst_Consultant p1
									FOR XML PATH(''), TYPE
									).value('.', 'NVARCHAR(MAX)')
							,1,1,'') ConsultantCode
						into #temoConsultant
						FROM Mst_Consultant p
						SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant )--WHERE member_code = @memcode AND year_code = @yearcode)
						DROP table #temoConsultant
					END
								 
				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes select MC.Consultant_Code from Mst_Consultant MC
					JOIN BrokerBill_Trans BBT ON BBT.Consultant_code = MC.Consultant_Code
					GROUP BY MC.Consultant_Code  
				--Select @StartYearDate
				SELECT  ROW_NUMBER ( ) OVER (ORDER BY t.script_code,t.Ac_Type,t.trans_dt ) AS NameId,	
				t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,t.TransType,t.Ac_Type,t.Script_Code, t.Qty,
				Case When @IsWithTax=0 Then t.Rate Else t.Exp_Rate END As 'Rate',
				t.Member_code,t.YearCode,t.Consultant_code,t.isFNOBill,  t.isIntraDay, t.FrmNm,t.ID,
				Ms.bse_code,Ms.nse_code,Ms.script_name,UPPER(ma.ac_name) AS 'Holding Type',
					CASE
						WHEN TransType='Sold' THEN 'Sold' 	
						WHEN (((t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101))AND t.TransType='Bought') THEN 'Opening'
						WHEN TransType='Bought' AND t.Bill_no = 'Bonus' THEN 'Bonus' 
						WHEN TransType='Bought' AND t.Bill_no ='Rights'THEN 'Rights' 
						WHEN TransType='Bought' AND  t.Bill_no ='Split' THEN 'Split' 
						WHEN TransType='Bought' AND  t.Bill_no ='Transfer' THEN 'Transfer' 
						WHEN TransType='Bought' AND Frmnm = 'IPO' THEN 'IPO'  
						WHEN TransType='Bought' AND Frmnm='MFDRI' THEN 'Devidend Re-Investment'
						WHEN TransType='Bought' AND  t.Bill_no != 'Opening'  THEN 'Bought'						
						END AS 'Flag_Type',
						ISNULL(cm.Consultant_Name,'')Consultant_Name,
						ISNULL(BB.Broker_Code,'') Broker_Code,dp_code 
				INTO #alldata
				FROM brokerbill_trans t  WITH (NOLOCK)
				LEFT JOIN mst_script ms					ON t.script_code		= Ms.script_code 
				LEFT JOIN mst_account ma				ON t.ac_type			= ma.ac_code AND ma.member_code = @memcode  AND ma.Year_Code=@yearcode
				LEFT JOIN Mst_Consultant cm				ON t.Consultant_code	= cm.Consultant_code  
				LEFT JOIN BrokerBill BB					ON BB.Trans_No			= t.Trans_No  AND BB.Member_code= @memcode AND BB.YearCode=@yearcode
				LEFT JOIN BrokerBill_DmatInfo BD		ON BD.Trans_No			= t.Trans_No AND BD.Sr_No = t.Sr_No AND BD.Member_code=@memcode AND BD.Yearcode=@yearcode
				WHERE t.isfnobill = @Investmenttype  
				AND t.trans_dt <= @Todate 
				AND t.member_code = @memcode 
				AND t.yearcode = @yearcode  
				AND t.Ac_Type =(CASE WHEN  @Ac_Type='0' THEN t.Ac_Type  ELSE  @Ac_Type END)
				AND	t.script_code IN (SELECT * FROM #SCriptCodes)
				AND	t.Consultant_code IN (SELECT * FROM #ConsultantCodes)
				AND ISNULL(t.isIntraDay,0) = (CASE WHEN ISNULL(@IsIntraDay,0)=0 THEN ISNULL(isIntraDay,0) ELSE ISNULL(@IsIntraDay,0) END) 
				AND t.MergedEntry=0 
				AND ISNULL( t.Ref_SrNo,0) != 1 
				AND (IsSLBS=0 OR IsSLBS IS NUll) 
							
				GROUP BY t.Trans_Dt,t.Trans_No,t.Sr_No,t.Script_Code,script_name,t.Ac_Type,ma.AC_Name,t.Consultant_code,cm.Consultant_Name ,BB.Broker_Code, 
				t.Bill_no,TransType,t.Qty,Rate,t.Exp_Rate,t.Amount,Stt_Amount,t.Member_Code,t.YearCode,t.MergedEntry,
				t.isFNOBill,isIntraDay,FrmNm,ID,bse_code,nse_code,dp_code,BD.Trans_no
			 
			  --  Select * from #alldata
				 
				DECLARE @isIntradayCol INT 
				DECLARE  @COUNT INT = 0

				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT id,Trans_No,sr_no,script_name,Script_Code, [holding type],Ac_type,Broker_Code, Consultant_code  ,DP_Code,bill_no,CONVERT(VARCHAR(10),trans_dt,101) trans_dt ,qty,rate,ISNULL(qty, 0) * ISNULL(rate, 0),ISNULL(isintraday, 0),consultant_name   
				FROM #alldata
				WHERE ((TransType != 'Sold' AND #alldata.bill_no IN('Split','Opening')) OR  CONVERT(date,trans_dt,101)  < CONVERT(date ,@StartYearDate,101) AND #alldata.TransType='Bought')

				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No,@Sr_No, @scriptname,@ScriptId,@holding_type,@Ac_types,@Broker_Code, @Consultant_code  ,@DP_Code, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
						IF(@Investmenttype=2)
							SET @holding_type='Mutual Fund'
						SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
						SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
						SET @Dup_pkid = ISNULL((Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end),0)
						SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
						SET @Dup_pkid = @Dup_pkid + 1

						DECLARE @IDs INT=0
						DECLARE @Flag_Types VARCHAR(100)
						SET @Flag_Types = (SELECT CASE WHEN @billno = 'Opening' THEN 'Opening' ELSE 'Bought' END)
						IF(@Flag_Types='Opening'  OR (@billno IN('Split') AND CONVERT(DATE,@dates,101)  < CONVERT(DATE ,@StartYearDate,101))OR (@billno NOT IN('Bought','Sold') AND CONVERT(date,@dates,101)  < CONVERT(date ,@StartYearDate,101)))
							BEGIN	
								INSERT INTO #MainOutputtable_1
								(Dup_pkid,Sr_No,  opening_bill_no ,id, DP_Code,ScriptCode,Broker_Code, Consultant_code  , Trans_No,Ac_type,  Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,consultant_name,Trans_Type) 
								VALUES
								(@Dup_pkid,@Sr_No, @billno,@ID,@Dp_code,@ScriptId,@Broker_code,@Consultant_code,@Trans_No,@Ac_types,'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Consultant_Name,'Opening')
							END
							
							 
						SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),0) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  

						IF(@idcount>0)
							BEGIN
								UPDATE #MainOutputtable_1 
								SET Dup_pkid = Dup_pkid + 1 
								WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
							END
							FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No,@Sr_No, @scriptname,@ScriptId,@holding_type,@Ac_types,@Broker_Code, @Consultant_code  ,@DP_Code, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name
					END 
				CLOSE alldatacursor 
				DEALLOCATE alldatacursor						

				DECLARE @tablerowscount INT
				DECLARE @salecount INT = 0,@Boughtcount INT = 0,@Flag_Type VARCHAR(100)
	
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 

				SELECT   id,Sr_No, Bill_no,Flag_Type,TransType,script_name,Script_Code, [holding type],Ac_type,Broker_Code, Consultant_code  ,DP_Code, Trans_No,CONVERT(VARCHAR(10), trans_dt,101), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name
				FROM #alldata WHERE  
				(TransType in('Bought','Sold')  OR CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
								
				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Sr_No, @billno,@Flag_Type , @TransType, @scriptname,@ScriptId,@holding_type,@Ac_types,@broker_Code, @Consultant_code  ,@DP_Code, @Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
				WHILE (@@FETCH_STATUS = 0)
						BEGIN
							SET @COUNT = 0
							DECLARE @IsOpening	INT				=	0, 
							@prioritysId		INT				=	0,
							@str				VARCHAR(MAX)	=	''	, 
							@purchase_Op_Qty	FLOAT			=	0,
							@purchase_Op_Bill	VARCHAR(20)		=	'',
							@purchase_Op_Date	VARCHAR(20)		=	'',
							@purchase_Op_Rate	FLOAT			=	0,
							@PurQTY				FLOAT			=	0,
							@BalPurQTY			FLOAT			=	0,
							@BalSoldQTY			FLOAT			=	0,
							@Balpurchase_Op_Qty FLOAT			=	0,
							@BalOpeningQTY		FLOAT			=	0, 
							@Sold_Qty			FLOAT			=	0,
							@tempID				INT				=	0
							
							IF(@isIntradayCol=0)
								BEGIN
									IF(@Investmenttype=2)
										 SET @holding_type='Mutual Fund'

									IF(@TransType LIKE '%Bought%')
										BEGIN

										 -- Select * from #MainOutputtable_1
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											--SET @COUNT = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE holding_type = @holding_type AND script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and  Flag_Type ='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=0  AND consultant_name=   @Consultant_Name )
											SET @COUNT = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE holding_type = @holding_type AND script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and  Flag_Type ='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=0  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
											
											IF (@COUNT > 0)
												BEGIN
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  Ac_Type,scriptcode, 
													CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,* 
													INTO #tempSoldValExists 
													FROM #MainOutputtable_1 
													WHERE script_name=@scriptname AND holding_type=@holding_type  
													AND (consultant_name = CASE WHEN  @Consultant_Name <> '' THEN @Consultant_Name ELSE consultant_name END)
													AND ISNULL(sold_qty,0)<> 0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold IN ('Sold')  AND   Flag_Type = 'Sold' AND isintradaycol=0
													ORDER BY NameId								
									
													DECLARE @R_Sold_COUNT FLOAT = ( SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty FLOAT 
													WHILE(@R_Sold_COUNT  > 0 )
														BEGIN
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists ORDER BY Dup_pkid,NameId)
															SET @str = @TransType

															SELECT TOP 1	@Sold_Qty		= sold_qty,
																			@soldDate		= sold_date,
																			@soldRate		= sold_Rate,
																			@soldBillNo		= sold_bill_no,
																			@Pkid			= Pkid
																	
															FROM #tempSoldValExists
															WHERE id  = @tempSaleID 
															SET @purchase_Op_Qty = @qty
														 
															IF(@TransType='Opening')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	opening_date=@dates,
																		opening_rate=@rate,
																		opening_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type = 'Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid
																END
															ELSE IF(@TransType = 'Bought')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	purchase_date=@dates,
																		purchase_bill_no=@billno,
																		purchase_rate=@rate,
																		purchase_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type = 'Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(purchase_qty,0)=0 AND pkid = @pkid
																END
															if(@Sold_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	sold_qty = @purchase_Op_Qty 
																	WHERE  id  = @tempSaleID AND Flag_Type_Sold='Sold' AND pkid = @pkid
																END
															
															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND pkid = @pkid
															DECLARE @Balancedval   FLOAT = Round((ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)),6) /* This is related to pending sold qty from table. If it is Negative then 
															 it will save into sale data else it is positive means Bought is greater So it will be inserted into Purchase Entry */
															
															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempSoldValExists)
															IF(@Balancedval  < 0)
																BEGIN
																--	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty = ABS(@Balancedval) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1) 
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	INSERT INTO #MainOutputtable_1
																				(ID,Sr_No, Dup_pkid, DP_Code,ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Trans_No, Flag_Type,Flag_Type_Sold,  prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name, Trans_Type)
																	VALUES		(@tempSaleID , @Sr_No, @Dup_pkid ,@DP_Code,@ScriptId,@Ac_Types ,@Broker_Code, @Consultant_code  ,@Trans_No,'Sold','Sold', @prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																	--		SET @Balancedval = 0

																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1)

																	IF(@TransType='Opening')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name, Trans_Type)
																			VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId,@Ac_Types ,@Broker_Code,  @Consultant_code  ,'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name,@flag_Type)
																			
																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	ELSE IF(@TransType='Bought')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No, ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name, Trans_Type)
																			VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId,@Ac_Types ,@Broker_Code, @Consultant_code  , 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name,@flag_Type)
																			
																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																		SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																	ENd
															ELSE IF(@Balancedval=0)
																BEGIN
																	break;
																END
															SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
															SET @qty = @Balancedval
															 
														END
													DROP TABLE #tempSoldValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)

													INSERT INTO #mainoutputtable_1 (id,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type,Broker_Code, Consultant_code  , prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name, Trans_Type)
													VALUES ( @ID,@Sr_No, ISNULL(@Dup_pkid,0),@DP_Code,@Trans_No,@ScriptId,@Ac_Types,@Broker_Code, @Consultant_code  , @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name,@flag_Type) 
												END

										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
											--SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') AND ISNULL(sold_qty,0)=0  AND isnull(isintradaycol,0)=0 AND consultant_name= @Consultant_Name  )
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') AND ISNULL(sold_qty,0)=0  AND isnull(isintradaycol,0)=0 AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  Ac_type,ScriptCode,case when opening_date <> NULL then opening_date else purchase_date end) AS NameId,* 
													INTO #tempValExists 
													FROM
													#MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') 
													AND (consultant_name = CASE WHEN  @ConsultantCode <> '' THEN  @Consultant_Name ELSE consultant_name END) 
													AND ISNULL(sold_qty,0) = 0  AND isintradaycol = 0 
													ORDER BY NameId
													
													DECLARE @RCOUNT INT = (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty FLOAT 
													 
													WHILE(@RCOUNT > 0 )
														BEGIN 
															SET @Sold_Qty = @qty
														    Declare @tempTransNo INT
															Declare @tempSrno INT

															SET @tempID = (SELECT TOP(1) id FROM #tempValExists ORDER BY dup_pkid)
															SET @tempTransNo=(SELECT TOP(1) Trans_No FROM #tempValExists ORDER BY dup_pkid)
															SET @tempSrno = (SELECT TOP(1) sr_no FROM #tempValExists ORDER BY dup_pkid)

															SET @str = (SELECT TOP(1) Flag_Type FROM #tempValExists WHERE id = @tempID  )
															
															IF(@str='Opening')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= opening_qty,
																					@openingDate	= opening_date,
																					@openingrate	= opening_rate,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID
																END
															ELSE IF(@str='Bought')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= purchase_qty,
																					@PurchaseDate	= purchase_date,
																					@Purchaserate	= purchase_rate,
																					@PurchaseBillNo = purchase_bill_no,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID
																END

															IF(@Sold_Qty > 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	UPDATE #MainOutputtable_1  
																		SET	
																			opening_qty     = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							  END,
																			purchase_qty    = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							   END,
																			sold_date       = @dates,
																			sold_bill_no    = @billno,
																			sold_rate       = @rate,
																			sold_qty        = CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold  = 'Sold',
																			prioritys       = @prioritysId
																	WHERE  id = @tempID AND ISNULL(sold_qty,0)=0 AND pkid = @Pkid
																	SET @Balanceval = Round((ABS(@Sold_Qty) - ABS(@TempSoldQty)),6)
																END
															
															DELETE FROM #tempValExists WHERE id = @tempID AND pkid = @pkid
															DELETE FROM #tempValExists Where Trans_No=@tempTransNo AND pkid = @pkid
															DELETE FROM #tempValExists WHERE sr_no = @tempSrno AND pkid = @pkid

															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempValExists)
															SET @RCOUNT = @RCOUNT - 1
														
															IF(@Balanceval < 0)
																BEGIN
																
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	 																	 
																	IF(@str='Opening')
																		BEGIN
																			SET @openingQty = ABS(@Balanceval) 
																			SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																			SET @prioritysId = ISNULL(@prioritysId,0)+1
																			INSERT INTO #MainOutputtable_1(ID,opening_bill_no, Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code,  Consultant_code  ,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name,Trans_Type)
																			VALUES(@tempID,'Opening',@tempSrno, @Dup_pkid,@DP_Code,@tempTransNo,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																			
																			SET @prioritysId = ISNULL(@prioritysId,0)+1
															
																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId   
																			WHERE prioritys >= @prioritysId AND ID <> @tempID
																		END
																	ELSE 
																		BEGIN
																			SET @PurchaseQty = ABS(@Sold_Qty) 
																			SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																			SET @prioritysId = ISNULL(@prioritysId,0)+1
																			
																			INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code, Consultant_code  , ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name, Trans_Type)
																			VALUES(@tempID,@tempSrno, @Dup_pkid,@DP_Code,@tempTransNo,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																			
																			SET @prioritysId = ISNULL(@prioritysId,0)+1
																			
																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId    
																			WHERE prioritys >= @prioritysId AND ID <> @tempID
																		END
																	 																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),1) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																		SET @Balanceval = 0
																	BREAK;
																END
														
															ELSE IF(ISNULL(@Balanceval,0) > 0 and @tablerowscount=0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																	INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code, Consultant_code  , ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@tempTransNo,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																END
															ELSE IF(ISNULL(@Balanceval,0) =0)
																BEGIN
																	SET @Balanceval=0
																	BREAK;
																END
																 
															SET @qty = @Balanceval
														END

												DROP TABLE #tempValExists
											END
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #MainOutputtable_1)
													SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0)+1 from #MainOutputtable_1)

													INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type,Broker_Code, Consultant_code  ,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
													VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@tempTransNo,@ScriptId, @Ac_Types,@Broker_Code, @Consultant_code  , 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
												END
											
											SET @purchase_Op_Date	=	''
											SET @purchase_Op_Rate	=	''
											SET @purchase_Op_Qty	=	''
											SET @purchase_Op_Bill	=	''
										END
								END
							IF(@isIntradayCol=1)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											--SELECT * FROM #MainOutputtable_1 --WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and ISNULL(Flag_Type,'')='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=1  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
											SET @COUNT = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold ='Sold' and  Flag_Type  = 'Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=1  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
											IF (@COUNT > 0)
												BEGIN
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY   Ac_Type,scriptcode,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* INTO #tempBought	
													FROM	#MainOutputtable_1 
													WHERE script_name=@scriptname AND holding_type=@holding_type  
													AND isintradaycol=1 
													AND (consultant_name = CASE WHEN  @Consultant_Name <> '' THEN @Consultant_Name ELSE consultant_name END)
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold =  'Sold'   AND  Flag_Type = 'Sold' AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
													ORDER BY NameId
													 
													DECLARE @Bought_COUNT INT = ( SELECT COUNT(*) FROM #tempBought )
													DECLARE @Temppurchase_Qty FLOAT 
													SET @purchase_Op_Qty = @qty
													DECLARE @Balance_val FLOAT
													WHILE(@Bought_COUNT  > 0)
														BEGIN 
															DECLARE @tempSale_ID INT = (SELECT TOP(1) id FROM #tempBought ORDER BY Dup_pkid)
															SET @str=@TransType

															SELECT	@Temppurchase_Qty		= sold_qty,
																	@soldDate				= sold_date,
																	@soldRate				= sold_rate,
																	@soldBillNo				= sold_bill_no,
																	@pkid					= pkid
															FROM #tempBought 
															WHERE id  = @tempSale_ID 

															SET @Sold_Qty= ABS(@Temppurchase_Qty)
															 
															IF(@TransType='Bought')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	purchase_date=@dates,
																		purchase_bill_no=@billno,
																		purchase_rate=@rate,
																		purchase_qty= CASE	WHEN @Temppurchase_Qty > @purchase_Op_Qty 
																							THEN ABS(@purchase_Op_Qty) 
																							ELSE ABS(@Temppurchase_Qty) 
																					  END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSale_ID  and pkid=@pkid
																END
															IF(@Temppurchase_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET sold_qty = ABS(@purchase_Op_Qty) 
																	WHERE Flag_Type_Sold = 'Sold' 
																	AND   id = @tempSale_ID   and pkid=@pkid
																END
															
															DELETE FROM #tempBought  WHERE id = @tempSale_ID 
															SET @Balance_val = Round((isnull(@purchase_Op_Qty,0) - (@Sold_Qty)),6)
															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempBought)
															
															SET @Bought_COUNT  = @Bought_COUNT  - 1
															SET @qty = @Balance_val

															IF(@Balance_val  < 0)
																BEGIN
																	--SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty = ABS(@Balance_val) 
																	SET @prioritysId  =(SELECT MAX(prioritys) FROM #MainOutputtable_1 )--WHERE id=@tempSale_ID )
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Trans_No, Flag_Type,Flag_Type_sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name,Trans_Type)
																	VALUES(@tempSale_ID ,@Sr_No, @Dup_pkid,@DP_Code,@ScriptId,@Ac_Types ,@Broker_Code, @Consultant_code  ,@Trans_No,'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balance_val),@soldRate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys >= @prioritysId AND ID<>@tempSale_ID 
																
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	
																	IF(@idcount>0)
																		BEGIN
 																		   UPDATE #MainOutputtable_1
																		   SET Dup_pkid = Dup_pkid + 1 
																		   WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																		   FROM Fn_split(@Pkid, ',') ) 
																		END

																	BREAK;
																END
															ELSE IF(@Balance_val  > 0 and @tablerowscount = 0)
																BEGIN
																	IF(@TransType='Bought')
																		BEGIN
																			SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																			SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																			SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																			SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																			SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																			SET @Dup_pkid = @Dup_pkid + 1

																			SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																			
																			INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No, ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																			VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId,@Ac_Types ,@Broker_Code, @Consultant_code  , 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balance_val)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																			
																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																			
																			SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																			IF(@idcount>0)
																				BEGIN
																					UPDATE #MainOutputtable_1 
																					SET Dup_pkid = Dup_pkid + 1 
																					WHERE  Dup_pkid >= @Dup_pkid and   
																					CONVERT(VARCHAR(200),pkid) NOT IN ( SELECT value FROM Fn_split(@Pkid, ',') ) 
																				END
																		END
																ENd
															SET @purchase_Op_Qty= (@Balance_val)
														END

													
													DROP TABLE #tempBought
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0) + 1 from #mainoutputtable_1)

													INSERT INTO #mainoutputtable_1 (id,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type,Broker_Code, Consultant_code  , prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name,Trans_Type) 
													VALUES ( @ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId,@Ac_Types,@Broker_Code, @Consultant_code  , @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name,@Flag_Type) 
												END
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
										 	SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer','Other') AND ISNULL(sold_qty,0)=0  AND isnull(isintradaycol,0)=1 AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval_sold FLOAT
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  Ac_type,ScriptCode,case when opening_date <> NULL then opening_date else purchase_date end ) AS NameId,* 
													INTO #tempSold 
													FROM #MainOutputtable_1
													WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer','Other') 
													AND (consultant_name = CASE WHEN  @ConsultantCode <> '' THEN  @Consultant_Name ELSE consultant_name END) 
													AND ISNULL(sold_qty,0) = 0  AND isintradaycol = 1 
													ORDER BY NameId
													
													DECLARE @RSoldCOUNT INT = (SELECT COUNT(*) FROM #tempSold)
													DECLARE @TempQty_Sold FLOAT 
												    
													WHILE(@RSoldCOUNT > 0 )
														BEGIN 
															SET @Sold_Qty = @qty
															SET @tempID  =   (SELECT TOP(1) id FROM #tempSold)
															SET @str     =   (SELECT TOP(1) Flag_Type FROM #tempSold WHERE id = @tempID  ORDER BY Dup_pkid,NameId)
															SET @pkid    =   (SELECT TOP(1) pkid  FROM #tempSold WHERE id  = @tempID )
															
															IF(@str='Bought')
																BEGIN
																	SELECT	@TempQty_Sold	=	purchase_qty,
																			@PurchaseDate	=	purchase_date,
																			@Purchaserate	=	purchase_rate,
																			@PurchaseBillNo	=	purchase_bill_no
																	FROM #tempSold 
																	WHERE id  = @tempID 
																END
															IF(@Sold_Qty > 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	UPDATE #MainOutputtable_1  
																		SET	
																			purchase_qty  = CASE WHEN @str ='Bought'
																								 THEN CASE	WHEN  @TempQty_Sold >= @Sold_Qty 
																											THEN @Sold_Qty 
																											ELSE @TempQty_Sold 
																								      END
																							 END,
																			sold_date      = @dates,
																			sold_bill_no   = @billno,
																			sold_rate      = @rate,
																			sold_qty       = CASE WHEN @TempQty_Sold > @Sold_Qty THEN @Sold_Qty ELSE @TempQty_Sold END,
																			Flag_Type_Sold = 'Sold',
																			prioritys      = @prioritysId
																	WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND pkid = @pkid
																	SET @Balanceval_sold = Round((ABS(@Sold_Qty) - ABS(@TempQty_Sold)),6)
																END
															
															DELETE FROM #tempSold WHERE id = @tempID
															SET @RSoldCOUNT = @RSoldCOUNT - 1
															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempSold)
														
															IF(@Balanceval_sold < 0)
																BEGIN
																--	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @PurchaseQty=ABS(@Sold_Qty) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code, Consultant_code  , ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval_sold)  ,@Purchaserate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId    
																	WHERE prioritys >= @prioritysId AND ID <> @tempID
																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			 UPDATE #MainOutputtable_1 
																			 SET Dup_pkid = Dup_pkid + 1 
																			 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																	BREAK;
																END
															ELSE IF(ISNULL(@Balanceval_sold,0) > 0 AND @tablerowscount=0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)

																	INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code, Consultant_code  , ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval_sold)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)

																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																END
															SET @qty = @Balanceval_sold
														END	
													DROP TABLE #tempSold
												END
											
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
												
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0) +1 from #mainoutputtable_1)

													INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type,Broker_Code, Consultant_code  ,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
													VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId, @Ac_Types,@Broker_Code, @Consultant_code  , 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
												END
											
											SET @purchase_Op_Date	=	''
											SET @purchase_Op_Rate	=	''
											SET @purchase_Op_Qty	=	''
											SET @purchase_Op_Bill	=	''
										END

								END
							FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Sr_No, @billno,@Flag_Type , @TransType, @scriptname,@ScriptId,@holding_type,@Ac_types,@broker_Code, @Consultant_code  , @DP_Code,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
						END 
				
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 
				
	    if(@IsBSEISIN=1)
		BEGIN
				INSERT INTO #mainoutputTable_1_BSEISISNO 				
				SELECT ma.pkid,ma.Dup_pkid,ma.Trans_No,ma.Ac_type,ma.id,ma.sr_no, ma.prioritys,ma.Trans_Type, ma.Split_Type, ma.Flag_Type, ma.Flag_Type_Sold,ma.flag_script_name,
				ma.flag_holding_type,  
				ma.script_name + '[' +ms.BSE_Code + ']' + '[' +ms.ISIN_No+ ']',ma.holding_type,ma.opening_bill_no ,ma.opening_date ,ma.opening_qty,ma.opening_rate ,ma.opening_amount ,ma.purchase_date ,ma.purchase_bill_no ,
				ma.purchase_qty,ma.purchase_rate,ma.purchase_amount ,ma.sold_date ,ma.sold_bill_no ,ma.sold_qty,ma.sold_rate,ma.sold_amount ,ma.gain_loss ,ma.closing_qty,
				ma.closing_rate,ma.closing_value,ma.short_term ,ma.long_term ,ma.speculation ,ma.gain_speculation ,ma.loss_speculation ,ma.consultant_name ,ma.nse_rate ,ma.bse_rate, 
				ma.isintradaycol,ma.[type],ma.ScriptCode ,ma.Broker_Code,ma.Dp_code ,ma.Consultant_code 
				from #mainoutputtable_1 ma 
				INNER JOIN Mst_Script Ms On  ma.ScriptCode=Ms.Script_Code
		END
		ELSE if(@IsBSEISIN=0)
			BEGIN
			   
				INSERT INTO #mainoutputTable_1_BSEISISNO  
				SELECT ma.pkid,ma.Dup_pkid,ma.Trans_No,ma.Ac_type,ma.id,ma.sr_no, ma.prioritys,ma.Trans_Type, ma.Split_Type, ma.Flag_Type, ma.Flag_Type_Sold,ma.flag_script_name,
				ma.flag_holding_type, ma.script_name,ma.holding_type,ma.opening_bill_no ,ma.opening_date ,ma.opening_qty,ma.opening_rate ,ma.opening_amount ,ma.purchase_date,
				ma.purchase_bill_no ,ma.purchase_qty, ma.purchase_rate,ma.purchase_amount ,ma.sold_date ,ma.sold_bill_no ,ma.sold_qty,ma.sold_rate,ma.sold_amount ,ma.gain_loss,
				ma.closing_qty,ma.closing_rate ,ma.closing_value,ma.short_term ,ma.long_term ,ma.speculation ,ma.gain_speculation ,ma.loss_speculation ,
				ma.consultant_name ,ma.nse_rate ,ma.bse_rate, ma.isintradaycol,ma.[type],ma.ScriptCode ,ma.Broker_Code,ma.Dp_code ,ma.Consultant_code 
				from #mainoutputtable_1 ma 
				
		END
		
		IF(@IsIntraDay = 0 AND @short_Long_Term != 0  )
			BEGIN
				IF(@short_Long_Term = 1 AND @IsLTCG=1 )  -- Long Term WITH LTCG
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy,sr_no, opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  , Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type])

						SELECT  ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN   CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
							 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId, 
						sr_no,opening_bill_no,
						id,Ac_type,Broker_Code,Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,

						Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4)
						as gain_loss,

						closing_qty ,closing_rate ,ROUND(closing_value,4) ,
						0,
						Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4),
						0,0,0,consultant_name,nse_rate,bse_rate,1 sort ,isintradaycol,Trans_Type
						FROM #mainoutputTable_1_BSEISISNO 
						WHERE (@IsFromMonthWise = 1 OR ISNULL(closing_qty,0) = 0)  
						AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
									(
										 
									       DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME,opening_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365 
									)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									(
										DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME, purchase_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365
									)
								)
							)
							order by NameId
					END
				ELSE If(@short_Long_Term = 2)  -- Short Term
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy, sr_no,opening_bill_no, id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,sr_no,
						opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4) as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						Round(ISNULL(
								CASE	WHEN isintradaycol = 0 and opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN isintradaycol = 0 and purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
										ELSE 0.0
								END 
						,0),4) ,
						0,0,0,0,consultant_name,nse_rate,bse_rate,1 sort,isintradaycol ,Trans_Type
						FROM #mainoutputTable_1_BSEISISNO 
						WHERE (@IsFromMonthWise = 1 OR ISNULL(closing_qty,0) = 0)   
						AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
										(		
											DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME,opening_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) <= 365 
										)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									  (		
											DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME, purchase_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) <= 365
									  )
								)
							)
					order by NameId
					END

				ELSE If(@short_Long_Term = 4 AND @IsLTCG=1 )  -- Short Term + Long Term WITH LTCG
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy,sr_no, opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,sr_no,
						
						opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						
						closing_qty ,closing_rate ,closing_value ,
						(CASE  WHEN isintradaycol = 0 AND  ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
								    (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
							  THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						(CASE WHEN isintradaycol = 0 AND  ( (ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365) OR
								   (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365))  
							  THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol ,
						Trans_Type
						FROM #mainoutputTable_1_BSEISISNO 
						WHERE  (@IsFromMonthWise = 1 OR ISNULL(closing_qty,0) = 0) 
						  AND ISNULL(isintradaycol,0)=0
						--order by ScriptCode,holding_type,case when CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) else CONVERT(DATE,purchase_date,103) END, prioritys 
						order by NameId
					END

				ELSE If(@short_Long_Term = 5 AND @IsLTCG=1  )  -- Without Speculation WITH LTCG
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy,sr_no, opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,sr_no,
						
						opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						
						closing_qty ,closing_rate ,closing_value ,
						(CASE  WHEN isintradaycol = 0 AND  ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
									(ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
								THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						(CASE WHEN isintradaycol = 0 AND  ( (ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365) OR
									(ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365))  
								THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol ,
						Trans_Type
						FROM #mainoutputTable_1_BSEISISNO 
						WHERE  ISNULL(isintradaycol,0)=0
						order by NameId
					END
                ELSE IF(@short_Long_Term = 1) --Long Term
				    BEGIN
					INSERT INTO #mainoutputtable_1_Final (OrderBy,sr_no, opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  , Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type])

						SELECT  ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN   CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
							 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId, 
						sr_no,opening_bill_no,
						id,Ac_type,Broker_Code,Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,

						Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN sold_rate * sold_qty - opening_rate*opening_qty 
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN sold_rate * sold_qty - purchase_rate*purchase_qty   
											ELSE 0.0	
										END,0) ,4)
						as gain_loss,

						closing_qty ,closing_rate ,ROUND(closing_value,4) ,
						0,
						Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN sold_rate * sold_qty - opening_rate*opening_qty  
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN sold_rate * sold_qty - purchase_rate*purchase_qty    
											ELSE 0.0	
										END,0) ,4),
						0,0,0,consultant_name,nse_rate,bse_rate,1 sort ,isintradaycol,Trans_Type
						FROM #mainoutputTable_1_BSEISISNO 
						WHERE (@IsFromMonthWise = 1 OR ISNULL(closing_qty,0) = 0)  
						AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
									(
										 
									       DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME,opening_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365 
									)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									(
										DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME, purchase_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365
									)
								)
							)
							order by NameId
				    END
                ELSE IF(@short_Long_Term = 4) -- Short Term + Long Term
			      	BEGIN
					    INSERT INTO #mainoutputtable_1_Final (OrderBy,sr_no, opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,sr_no,
						
						opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN sold_rate * sold_qty - opening_rate * opening_qty
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN sold_rate * sold_qty - purchase_rate * purchase_qty 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						
						closing_qty ,closing_rate ,closing_value ,
						(CASE  WHEN isintradaycol = 0 AND  ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
								    (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
							  THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN sold_rate * sold_qty - opening_rate * opening_qty
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN sold_rate * sold_qty - purchase_rate * purchase_qty  
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						(CASE WHEN isintradaycol = 0 AND  ( (ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365) OR
								   (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365))  
							  THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN sold_rate * sold_qty - opening_rate * opening_qty
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN sold_rate * sold_qty - purchase_rate * purchase_qty 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol ,
						Trans_Type
						FROM #mainoutputTable_1_BSEISISNO 
						WHERE  (@IsFromMonthWise = 1 OR ISNULL(closing_qty,0) = 0) 
						  AND ISNULL(isintradaycol,0)=0
						--order by ScriptCode,holding_type,case when CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) else CONVERT(DATE,purchase_date,103) END, prioritys 
						order by NameId
				    END
                ELSE IF(@short_Long_Term = 5)  --Without Speculation
				     BEGIN
				    	 INSERT INTO #mainoutputtable_1_Final (OrderBy,sr_no, opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,sr_no,
						
						opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN  sold_rate * sold_qty - opening_rate * opening_qty
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN sold_rate * sold_qty - purchase_rate * purchase_qty
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						
						closing_qty ,closing_rate ,closing_value ,
						(CASE  WHEN isintradaycol = 0 AND  ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
									(ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
								THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN sold_rate * sold_qty - opening_rate * opening_qty
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN sold_rate * sold_qty - purchase_rate * purchase_qty 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						(CASE WHEN isintradaycol = 0 AND  ( (ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365) OR
									(ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365))  
								THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN sold_rate * sold_qty - opening_rate * opening_qty
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN sold_rate * sold_qty - purchase_rate * purchase_qty
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol ,
						Trans_Type
						FROM #mainoutputTable_1_BSEISISNO 
						WHERE  ISNULL(isintradaycol,0)=0
						order by NameId
					 END 
			END

		ELSE IF(@short_Long_Term = 3 AND @IsIntraDay = 1 )  -- Only Speculation
			BEGIN
				INSERT INTO #mainoutputtable_1_Final (OrderBy,sr_no, opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

				SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
				case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
				sr_no,opening_bill_no,id,Ac_type,Broker_Code, Consultant_code  ,Trans_No,ScriptCode, prioritys,script_name,Holding_Type,opening_date,
				ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),purchase_date,ISNULL(purchase_bill_no,0),
				ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,sold_date ,sold_bill_no ,isnull(sold_qty,0) ,
				ISNULL(sold_rate,0),ISNULL(sold_amount,0) ,
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4) as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				0,0,
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4),
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,
				Trans_Type
				FROM #mainoutputTable_1_BSEISISNO 
				WHERE  (@IsFromMonthWise = 1 OR ISNULL(closing_qty,0) = 0)  AND (ISNULL(isintradaycol,0)=1) AND (ISNULL(purchase_qty,0)! = 0 AND  ISNULL(sold_qty,0) ! = 0) 
				order by NameId
			END
		ELSE IF(@IsLTCG=1)
			BEGIN			
			--	Select * from #mainoutputtable_1
				INSERT INTO #mainoutputtable_1_Final ( pkid,sr_no,Dup_pkid,OrderBy, opening_bill_no,id,Ac_type,Broker_Code,Dp_code, Consultant_code,Trans_No,ScriptCode, prioritys,script_name,Holding_Type,
				flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

				SELECT pkid,sr_no,Dup_pkid,
				ROW_NUMBER ( ) OVER (ORDER BY   holding_type,ScriptCode,-- Pkid,
			   case  WHEN  Dup_pkid is Null Then Pkid
				    WHEN  Dup_pkid is NOt Null then Dup_pkid 
				    else Dup_pkid end,prioritys,
			    Case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
				opening_bill_no,id,ISNULL(Ac_type,''),ISNULL(Broker_Code,''), ISNULL(Dp_code,'')Dp_code ,ISNULL(Consultant_code ,'') ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type, 
				flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,sold_rate,sold_amount ,
				Round(ISNULL(
					CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term for openings
								THEN  sold_rate * sold_qty - opening_rate*opening_qty
							WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term for purchase
							THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
							ELSE --long term
								CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
											THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, opening_date, sold_date, opening_qty, sold_qty)) 
										WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
											THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, purchase_date, sold_date, purchase_qty, sold_qty))
										ELSE 0.0
								END
					END,0) ,4)
				as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN  isintradaycol = 0 AND (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365)   --short term for openings
						THEN  sold_rate * sold_qty - opening_rate*opening_qty	-- Short Tem openings
					 WHEN  isintradaycol = 0 AND (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365) --short term for purchase
						THEN sold_rate * sold_qty - purchase_rate*purchase_qty 	-- Short Tem purchase		
					 ELSE 0.0 END,   
				CASE WHEN isintradaycol = 0 AND (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --long term for openings
							OR
						  isintradaycol = 0 AND	(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365) --long term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN 
									(Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,  -- Long Term
				CASE WHEN  isintradaycol = 1 AND  purchase_bill_no = sold_bill_no
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,
				Trans_Type 
				FROM #mainoutputTable_1_BSEISISNO 
				order by NameId
			END
        ELSE
		  BEGIN
		        INSERT INTO #mainoutputtable_1_Final ( pkid,sr_no,Dup_pkid,OrderBy, opening_bill_no,id,Ac_type,Broker_Code,Dp_code, Consultant_code,Trans_No,ScriptCode, prioritys,script_name,Holding_Type,
				flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type] )

				SELECT pkid,sr_no,Dup_pkid,
				ROW_NUMBER ( ) OVER (ORDER BY   holding_type,ScriptCode,-- Pkid,
			   case  WHEN  Dup_pkid is Null Then Pkid
				    WHEN  Dup_pkid is NOt Null then Dup_pkid 
				    else Dup_pkid end,prioritys,
			    Case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
				opening_bill_no,id,ISNULL(Ac_type,''),ISNULL(Broker_Code,''), ISNULL(Dp_code,'')Dp_code ,ISNULL(Consultant_code ,'') ,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type, 
				flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,sold_rate,sold_amount ,
				Round(ISNULL(
					CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term for openings
								THEN  sold_rate * sold_qty - opening_rate*opening_qty
							WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term for purchase
							THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
							ELSE --long term
								CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
											THEN sold_rate * sold_qty - opening_rate*opening_qty
										WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
											THEN sold_rate * sold_qty - purchase_rate*purchase_qty 
										ELSE 0.0
								END
					END,0) ,4)
				as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN  isintradaycol = 0 AND (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365)   --short term for openings
						THEN  sold_rate * sold_qty - opening_rate*opening_qty	-- Short Tem openings
					 WHEN  isintradaycol = 0 AND (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365) --short term for purchase
						THEN sold_rate * sold_qty - purchase_rate*purchase_qty 	-- Short Tem purchase		
					 ELSE 0.0 END,   
				CASE WHEN isintradaycol = 0 AND (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --long term for openings
							OR
						  isintradaycol = 0 AND	(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365) --long term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN sold_rate * sold_qty - opening_rate*opening_qty								
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN sold_rate * sold_qty - purchase_rate*purchase_qty 
								ELSE 0.0
						END
				ELSE 0.0 END,  -- Long Term
				CASE WHEN  isintradaycol = 1 AND  purchase_bill_no = sold_bill_no
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,
				Trans_Type 
				FROM #mainoutputTable_1_BSEISISNO 
				order by NameId
		  END
     	--Select * from #mainoutputtable_1
		--Select * from #mainoutputtable_1_Final
		IF(@OUTPUT_Flag='Details')
			BEGIN
				IF(@Investmenttype != 2)
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN
								SELECT opening_bill_no, id,prioritys,Ac_type,Broker_Code, Consultant_code  ,ScriptCode, script_name  'Script Name',Holding_Type,
								CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
								CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
								CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
								gain_loss 'Gain/Loss',ISNULL(gain,0) 'Gain',ISNULL(loss,0) 'Loss',ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
								ISNULL(short_term,0) short_term, ISNULL(long_term,0) long_term, ISNULL(speculation,0) speculation,
								CASE WHEN isintradaycol=1 AND ISNULL(gain,0)!=0 THEN ISNULL(gain ,0) ELSE '0' END gain_speculation,
								CASE WHEN isintradaycol=1 AND ISNULL(loss,0)!=0  THEN ISNULL(loss ,0) ELSE '0' END loss_speculation,
								consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),ISNULL(isintradaycol,0),1 sort,[type] 
								FROM #mainoutputtable_1_Final 
								WHERE (opening_qty != 0  OR purchase_qty != 0  or sold_qty != 0)  
								ORDER BY  consultant_name,script_name,Holding_Type
							END
						ELSE
							BEGIN
					
								UPDATE #mainoutputtable_1_Final SET prioritys=0
								DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
								UPDATE #mainoutputtable_1_Final
								SET prioritys  = @i , @i = @i + 1

								SELECT id,Trans_no, Sr_No, Holding_Type as 'flag_HT', ISNULL(opening_bill_no,'') opening_bill_no , Dup_pkid,prioritys,ScriptCode,  ISNULL(Ac_type,'') Ac_type,   ISNULL(Broker_Code,'')Broker_Code,ISNULL(Consultant_code,'')Consultant_code  ,script_name 'Script Name',Holding_Type, 
								CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount', 
								CONVERT(DATE,purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ROUND(ISNULL(purchase_qty,0),4) 'Purchase Qty',ROUND(ISNULL(purchase_rate,0),4) 'Purchase Rate',ROUND(ISNULL(purchase_amount,0),4) 'Purchase Amount',
								CONVERT(DATE,sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ROUND(ISNULL(sold_qty,0),4) 'Sold Qty',ROUND(ISNULL(sold_rate,0),4) 'Sold Rate',ROUND(ISNULL(sold_amount,0),4) 'Sold Amount',
								ROUND(ISNULL(gain_loss,0),4) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS  'Loss',
								ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
								ISNULL(short_term,0)short_term, 
								ISNULL(long_term,0)long_term, 
								ISNULL(speculation,0)speculation,
								CASE WHEN ISNULL(speculation,0) > 0  THEN ISNULL(gain,0)  ELSE 0 END gain_speculation,
								CASE WHEN ISNULL(speculation,0) < 0  THEN ISNULL(loss,0)  ELSE 0 END loss_speculation,
								consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,ISNULL(isintradaycol,0)isintradaycol,1 sort,[type] 
								FROM #mainoutputtable_1_Final
								WHERE (opening_qty != 0  OR purchase_qty != 0  or sold_qty != 0)  
								order by id,script_name,holding_type
							END
					END
				ELSE
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN
								SELECT opening_bill_no, id,prioritys,ScriptCode,' '  Ac_type,    Broker_Code,   Consultant_code  ,script_name 'Script Name', Holding_Type, 
								CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount', 
								CONVERT(DATE,purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ROUND(ISNULL(purchase_qty,0),4) 'Purchase Qty',ROUND(ISNULL(purchase_rate,0),4) 'Purchase Rate',ROUND(ISNULL(purchase_amount,0),4) 'Purchase Amount',
								CONVERT(DATE,sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ROUND(ISNULL(sold_qty,0),4) 'Sold Qty',ROUND(sold_rate,4) 'Sold Rate',ROUND(ISNULL(sold_amount,0),4) 'Sold Amount',
								ROUND(ISNULL(gain_loss,0),4) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS  'Loss',
								ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
								ISNULL(short_term,0) short_term,ISNULL(long_term,0) long_term,ISNULL(speculation,0) speculation,
								CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
								CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
								consultant_name,ISNULL(nse_rate,0) nse_rate,ISNULL(bse_rate,0) bse_rate,ISNULL(isintradaycol,0) isintradaycol,1 sort ,[type]
								FROM #mainoutputtable_1_Final
								WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)
								ORDER BY consultant_name, Holding_Type,script_name,id
							END
						ELSE
							BEGIN
								SELECT opening_bill_no, id,prioritys,ScriptCode,' '  Ac_type,    Broker_Code,   Consultant_code  ,script_name 'Script Name', Holding_Type, 
								CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount', 
								CONVERT(DATE,purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ROUND(ISNULL(purchase_qty,0),4) 'Purchase Qty',ROUND(ISNULL(purchase_rate,0),4) 'Purchase Rate',ROUND(ISNULL(purchase_amount,0),4) 'Purchase Amount',
								CONVERT(DATE,sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ROUND(ISNULL(sold_qty,0),4) 'Sold Qty',ROUND(ISNULL(sold_rate,0),4) 'Sold Rate',ROUND(ISNULL(sold_amount,0),4) 'Sold Amount',
								ROUND(ISNULL(gain_loss,0),4) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS  'Loss',
								ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate ,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
								ISNULL(short_term,0) short_term,
								ISNULL(long_term,0) long_term,
								ISNULL(speculation,0) speculation,
								CASE WHEN   ISNULL(speculation,0) > 0 THEN ISNULL(speculation,0)  ELSE '' END gain_speculation,
								CASE WHEN   ISNULL(speculation,0) < 0  THEN ISNULL(speculation,0)  ELSE '' END loss_speculation,
							    consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,ISNULL(isintradaycol,0)isintradaycol,1 sort ,[type]
								FROM #mainoutputtable_1_Final
								WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)
								ORDER BY   script_name,Holding_Type,id
							END
					END
			END

		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
				SELECT  0 id ,  0 prioritys,'' opening_bill_no,ScriptCode,  Ac_type, script_name 'Script Name',   Holding_Type,
				NULL 'Opening Date', SUM(ISNULL(opening_qty,0)) 'Opening Qty', 
			    ISNULL((SUM(ISNULL(opening_amount,0)) / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate', SUM(ISNULL(opening_amount,0)) 'Opening Amount',
				NULL 'Purchase Date','' 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty',  ISNULL((ISNULL(SUM(purchase_amount),0)  / SUM(NULLIF(purchase_qty,0))),0)   'Purchase Rate', SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
				NULL 'Sold Date', '' 'Sold BillNo', SUM(ISNULL(sold_qty,0)) 'Sold Qty', ISNULL((SUM(ISNULL(sold_amount,0)) / NULLIF (SUM(ISNULL(sold_qty,0)),0)),0) 'Sold Rate', SUM(ISNULL(sold_amount,0)) 'Sold Amount', 
				SUM(ISNULL(gain_loss,0)) 'Gain/Loss', SUM(ISNULL(gain,0))  'Gain', SUM(ISNULL(loss,0))  'Loss',
				
				SUM(ISNULL(closing_qty,0))  'Closing Qty',
			    CASE WHEN SUM(closing_qty) != 0
					 THEN (SUM(closing_value) / SUM(NULLIF(closing_qty,0))) 
					 ELSE 0
				END  'Closing Rate',
				
				SUM(ISNULL(closing_value,0))  'Closing Value', SUM(ISNULL(short_term,0))  short_term, SUM(ISNULL(long_term,0))  long_term,
				SUM(ISNULL(speculation,0)) speculation, SUM(ISNULL(gain_speculation,0)) gain_speculation, SUM(ISNULL(loss_speculation,0)) loss_speculation,''consultant_name,0 nse_rate,0 bse_rate,1 sort  
				FROM
					(
						SELECT MAX(id+0)id ,MAX (prioritys+0) prioritys,'' opening_bill_no, ScriptCode,Ac_type,  script_name  ,  Holding_Type,
						NULL 'Opening Date',SUM(ISNULL(opening_qty,0)) 'Opening_Qty',sum(ISNULL(opening_rate,0)) opening_rate ,SUM(ISNULL(opening_amount,0)) 'Opening_Amount',
						NULL 'Purchase Date',purchase_bill_no,SUM(ISNULL(purchase_qty,0)) 'Purchase_Qty', (SUM(ISNULL(purchase_amount,0)) / SUM(NULLIF(ISNULL(purchase_qty,0),0))) purchase_rate,SUM(ISNULL(purchase_amount,0)) 'Purchase_Amount',
						NULL 'Sold Date',sold_bill_no ,SUM(ISNULL(sold_qty,0)) 'Sold_Qty', (SUM(ISNULL(sold_amount,0)) / SUM(NULLIF(ISNULL(sold_qty,0),0))) sold_rate  , SUM(ISNULL(sold_amount,0)) 'Sold_Amount',SUM(ISNULL(gain_loss,0)) 'Gain_Loss',SUM(ISNULL(gain,0)) 'Gain',SUM(ISNULL(loss,0)) 'Loss',
						SUM(ISNULL(closing_qty,0)) 'Closing_Qty', (SUM(ISNULL(closing_value,0)) / SUM(NULLIF(closing_qty,0))) 'Closing_Rate',SUM(ISNULL(closing_value,0)) 'Closing_Value',
						SUM(ISNULL(short_term,0)) AS short_term,SUM(ISNULL(long_term,0)) AS long_term,SUM(ISNULL(speculation,0)) AS speculation,
						SUM(ISNULL(gain_speculation,0)) gain_speculation,SUM(ISNULL(loss_speculation,0)) loss_speculation,''consultant_name,0 nse_rate,0 bse_rate,1 sort 
						FROM #mainoutputtable_1_Final 
						GROUP BY ScriptCode,script_name,Holding_Type,Ac_type,purchase_bill_no,sold_bill_no,opening_date,purchase_date ,sold_date,isintradaycol
					)a
				GROUP BY  ScriptCode,script_name,Holding_Type,Ac_type,[Opening Date],[Purchase Date]  
				ORDER BY  Holding_Type,script_name,id
			END

		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN
				SELECT  prioritys ,Trans_No,id ,ISNULL(Ac_type,'')Ac_type,ISNULL(Broker_Code,'')Broker_Code,  ISNULL(Consultant_code,'') Consultant_code ,
				ISNULL(ScriptCode,'')ScriptCode,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,CONVERT(DATE, opening_date,103),
				ISNULL(opening_qty ,0),ISNULL(opening_Rate,0),ISNULL(opening_amount,0),CONVERT(DATE, purchase_date,103),purchase_bill_no,
				ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,CONVERT(DATE,sold_date,103) ,sold_bill_no ,ISNULL(sold_qty ,0),
				ISNULL(sold_rate,0),ISNULL(sold_amount ,0),ISNULL(gain_loss ,0),ISNULL(gain ,0),ISNULL(loss,0),ISNULL(closing_qty ,0),ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
				ISNULL(short_term,0),ISNULL(long_term,0),ISNULL(speculation,0),ISNULL(gain_speculation,0),ISNULL(loss_speculation,0),
				consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0 ),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol
				FROM #mainoutputtable_1_Final
				ORDER BY  Holding_Type,script_name,id
			END
		
		ELSE IF(@OUTPUT_Flag='StoskTransfer_BrokerBillTrans')
			BEGIN
				SELECT Trans_No,'' id,sr_no,prioritys,ScriptCode,  ISNULL(Ac_type,'') Ac_type,    DP_Code, Broker_Code,ISNULL(Consultant_code,'')Consultant_code,
				script_name 'Script Name',Holding_Type, 
				CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',opening_Rate 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount', 
				CONVERT(DATE,purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ROUND(ISNULL(purchase_qty,0),4) 'Purchase Qty',ROUND(ISNULL(purchase_rate,0),4) 'Purchase Rate',ROUND(ISNULL(purchase_amount,0),4) 'Purchase Amount',
				CONVERT(VARCHAR,sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ROUND(ISNULL(sold_qty,0),4) 'Sold Qty',ROUND(sold_rate,4) 'Sold Rate',ROUND(ISNULL(sold_amount,0),4) 'Sold Amount',
				ROUND(ISNULL(gain_loss,0),4) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS  'Loss',
				ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
				CASE
					WHEN ISNULL(closing_qty,0) < 0 THEN CONVERT(DATE,sold_date,101)
					WHEN ISNULL(opening_date,'') != '' THEN  CONVERT(DATE,opening_date,101)
					WHEN ISNULL(purchase_date,'') != '' THEN CONVERT(DATE,purchase_date,101)
					END  AS  'Closing Date',
				ISNULL(short_term,0) short_term,ISNULL(long_term,0) long_term,ISNULL(speculation,0) speculation,
				CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
				CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
				'' consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),ISNULL(isintradaycol,0),1 sort 
				FROM #mainoutputtable_1_Final
				WHERE ISNULL(closing_qty,0) <> 0
				ORDER BY Trans_No
			END
		 
		ELSE IF(@OUTPUT_Flag='StoskTransfer_BrokerBill')
			BEGIN
				SELECT 0 id,0 prioritys,'' ScriptCode,  '' Ac_type,''  DP_Code,  
				ISNULL(Broker_Code,'') Broker_Code,'' Consultant_code,
				'' 'Script Name','' Holding_Type, '' 'Opening Date',
				0 'Opening Qty',0 'Opening Rate',0 'Opening Amount', '' 'Purchase Date','' 'Purchase BillNo',
				0 'Purchase Qty',0 'Purchase Rate',0 'Purchase Amount',
				'' 'Sold Date','' 'Sold BillNo',0 'Sold Qty',
				0 'Sold Rate',0 'Sold Amount',0 'Gain/Loss',
				0 'Gain',0  'Loss',0 'Closing Qty',0 'Closing Rate',SUM(ISNULL(closing_value,0)) 'Closing Value',
				'' 'Closing Date',
				0 short_term,0 long_term,0 speculation,
				0 gain_speculation,
				0 loss_speculation,
				'' consultant_name,0 nse_rate,0 bse_rate,0 isintradaycol,1 sort 
				FROM #mainoutputtable_1_Final
				WHERE ISNULL(closing_qty,0) <> 0
				GROUP BY Broker_Code
				ORDER BY Broker_Code
			END
		
		 ELSE IF(@OUTPUT_Flag='StoskTransfer_DemateInfo')
			BEGIN
				SELECT id,prioritys,'' ScriptCode,  '' Ac_type,   DP_Code,  '' Broker_Code,'' Consultant_code,
				'' 'Script Name','' Holding_Type, '' 'Opening Date',
				0 'Opening Qty',0 'Opening Rate',0 'Opening Amount', '' 'Purchase Date','' 'Purchase BillNo',
				0 'Purchase Qty',0 'Purchase Rate',0 'Purchase Amount',
				'' 'Sold Date','' 'Sold BillNo',0 'Sold Qty',
				0 'Sold Rate',0 'Sold Amount',0 'Gain/Loss',
				0 'Gain',0  'Loss',0 'Closing Qty',0 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
				'' 'Closing Date',
				0 short_term,0 long_term,0 speculation,
				0 gain_speculation,
				0 loss_speculation,
				'' consultant_name,0 nse_rate,0 bse_rate,0 isintradaycol,1 sort 
				FROM #mainoutputtable_1_Final
				WHERE ISNULL(closing_qty,0) <> 0
				ORDER BY Broker_Code
			END

		ELSE IF(@OUTPUT_Flag='ClosingBalTransfer_Mst_Ac')
			BEGIN
				SELECT  MAX(prioritys+1) ,'' Trans_No,'' id ,ISNULL(Ac_type,'') Ac_type, '' Broker_Code,  '' Consultant_code ,
				'' ScriptCode,'' script_name ,'' Holding_Type,'' flag_script_name,'' flag_Holding_Type,'' opening_date,
				0 opening_qty , 0 opening_Rate,0 opening_amount,'' purchase_date ,'' purchase_bill_no,
				0 purchase_qty ,0 purchase_rate ,0 purchase_amount ,'' sold_date  ,'' sold_bill_no ,0 sold_qty ,
				0 sold_rate,0 sold_amount ,0 gain_loss ,0 gain ,0 loss,SUM(ISNULL(closing_qty,0)) closing_qty,0 closing_rate , SUM(ISNULL(closing_value,0)) closing_value,
				0 short_term,0 long_term,0 speculation,0 gain_speculation,0 loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,
				0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort , isintradaycol--,holding_type + space(5) + '1'
				FROM #mainoutputtable_1_Final
				GROUP BY Ac_type,  isintradaycol
			END

		ELSE IF(@OUTPUT_Flag='Broker_ClosingBalanceTRansfer_Mst_Ac')
			BEGIN
				SELECT Broker_Code,BrokerClosingBal
					FROM 
					(
						SELECT   Broker_Code, 
						ISNULL((CASE WHEN Ac_Type='D' THEN SUM(ISNULL(Net_amt,0)) END)  ,0)
						-
						ISNULL((CASE WHEN Ac_Type='C' THEN SUM(ISNULL(Net_amt,0)) END) ,0)  AS 'BrokerClosingBal'
						FROM BrokerBill  WHERE YearCode=@yearcode AND Member_Code=@memcode
						GROUP BY Broker_Code,Ac_Type
					)t
						WHERE t.BrokerClosingBal <> 0 GROUP BY Broker_Code,BrokerClosingBal
			END

		ELSE IF(@output_Flag='WholeMainTableData')
			BEGIN
				 SELECT pkid ,Dup_pkid , Trans_No ,Ac_type  ,id  ,script_name   ,holding_type  ,
				 opening_bill_no  ,opening_date  ,ISNULL(opening_qty ,0) opening_qty ,ISNULL(opening_rate ,0) opening_rate ,ISNULL(opening_amount ,0)opening_amount , 
				 purchase_date ,purchase_bill_no ,ISNULL(purchase_qty,0) purchase_qty,ISNULL(purchase_rate,0) purchase_rate,ISNULL(purchase_amount,0) purchase_amount,
				 sold_date ,sold_bill_no ,ISNULL(sold_qty,0) sold_qty,ISNULL(sold_rate,0) sold_rate,ISNULL(sold_amount,0) sold_amount, 
				 ISNULL(gain_loss,0) gain_loss,ISNULL(gain,0) gain,ISNULL(loss,0) loss,ISNULL(closing_qty,0) closing_qty, ISNULL(closing_rate,0) closing_rate,ISNULL(closing_value,0) closing_value,
				 ISNULL(short_term,0) short_term,ISNULL(long_term,0) long_term, ISNULL(speculation,0) speculation, ISNULL(gain_speculation,0) gain_speculation,ISNULL(loss_speculation,0) loss_speculation,ISNULL(isintradaycol,0) isintradaycol,ScriptCode 
			from #mainoutputtable_1_Final 
			END

		ELSE IF(@output_Flag='ClosingStocks')
			BEGIN

			--Select * from #mainoutputtable_1_Final
				 SELECT id,
						Trans_No ,
						sr_no,
						script_name,
						ScriptCode,
						Holding_Type,
						ISNULL(Ac_type,'') Ac_type,
						Broker_Code,
						ISNULL(Consultant_code,'') Consultant_code,
						DP_Code,
						CASE						
							WHEN ISNULL(closing_qty,0) < 0		THEN sold_bill_no
							WHEN ISNULL(purchase_date,'') != '' THEN  purchase_bill_no
							WHEN ISNULL(opening_date,'') != ''  THEN opening_bill_no
							ELSE ''
						END  AS  'bill_no',
						CASE
							WHEN ISNULL(closing_qty,0) < 0		THEN CONVERT(DATE,sold_date,101)
							WHEN ISNULL(opening_date,'') != ''	THEN  CONVERT(DATE,opening_date,101)
							WHEN ISNULL(purchase_date,'') != '' THEN CONVERT(DATE,purchase_date,101)
						END  AS  'trans_dt',
						ABS(ISNULL(closing_qty,0)) 'Qty',
						ISNULL(closing_rate,0) 'rate',
						ISNULL(closing_value,0) 'amount',
						isintradaycol,
						consultant_name,
						CASE
							WHEN ISNULL(closing_qty,0)    < 0		THEN 'Sold'
							WHEN ISNULL(opening_date,'')  != ''		THEN 'Opening'
							WHEN ISNULL(purchase_date,'') != ''		THEN 'Bought'
							ELSE ''
						END  AS  'Type'
				from #mainoutputtable_1_Final 
				WHERE ISNULL(closing_qty,0) <> 0
				ORDER BY  trans_dt,Trans_No			
			END

		ELSE IF(@output_Flag='ClosingStocksAmountTotal')
			BEGIN
				 SELECT 
						 Sum(ISNULL(closing_value,0)) 'amount'
						
				from #mainoutputtable_1_Final 
				WHERE ISNULL(closing_qty,0) <> 0							
			END

		DROP TABLE #mainoutputtable_1 
		DROP TABLE #mainoutputTable_1_BSEISISNO
		DROP TABLE #alldata 
	
END  






















































GO
/****** Object:  StoredProcedure [dbo].[proc_Stockholdingposition_Equity_LTCG]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockholdingposition_Equity_LTCG]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Stockholdingposition_Equity_LTCG] AS' 
END
GO

--[proc_Stockholdingposition_Equity_LTCG]  0,2,'0','30001','1120182019','2018-04-01 12:00:00:00','2019-03-31 03:50:37:50','','','','', '0' ,'0','Details'
ALTER PROCEDURE [dbo].[proc_Stockholdingposition_Equity_LTCG] --0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','ScriptWiseTotal'
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate datetime,@Todate datetime, 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),
@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX),@IsBSEISIN bit=0)
AS 
  BEGIN
  SET NOCOUNT ON;
		DECLARE @StartYearDate varchar(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101) 
		CREATE TABLE #mainoutputtable_1
        ( 
		    Dup_pkid int,
			Ac_type VARCHAR(20),
			pkid INT identity(1,1), 
			Trans_No VARCHAR(20),
			id INT,prioritys INT,
			Trans_Type  VARCHAR(50), 
			Split_Type VARCHAR(50), 
			Flag_Type VARCHAR(10),
			Flag_Type_Sold VARCHAR(100),
			flag_script_name  VARCHAR(Max),
			flag_holding_type VARCHAR(Max), 
			script_name  VARCHAR(500),
			holding_type VARCHAR(200), 
			opening_bill_no VARCHAR(50),		    
			opening_date DATETIME,
			opening_qty  FLOAT DEFAULT 0,
			opening_rate  FLOAT DEFAULT 0,
			opening_amount AS( [opening_qty] * [opening_rate] ), 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount AS( 
			purchase_qty * purchase_rate ), 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount AS ( sold_qty * sold_rate ), 
			gain_loss float,
			closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 

			closing_rate  AS 
			(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
				CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
				CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
				ELSE 0 END END END),
			closing_value AS
			(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
				CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
				CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
				ELSE 0 END END END)
				*
				(CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
				END ),
		   
			short_term FLOAT DEFAULT 0,
			long_term  FLOAT DEFAULT 0,
			speculation  FLOAT DEFAULT 0,
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			consultant_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			dayscount FLOAT DEFAULT 0,
			isintradaycol INT,[type] VARCHAR(20) , ScriptCode Varchar(50) 
        )  

		CREATE TABLE #mainoutputTable_1_BSEISISNO
		(
		    Dup_pkid int,
		    Ac_type VARCHAR(20),
			pkid INT identity(1,1), 
			Trans_No VARCHAR(20),
			id INT,prioritys INT,
			Trans_Type  VARCHAR(50), 
			Split_Type VARCHAR(50), 
			Flag_Type VARCHAR(10),
			Flag_Type_Sold VARCHAR(100),
			flag_script_name  VARCHAR(Max),
			flag_holding_type VARCHAR(Max), 
			script_name  VARCHAR(500),
			holding_type VARCHAR(200), 
			opening_bill_no VARCHAR(50),		    
			opening_date DATETIME,
			opening_qty  FLOAT DEFAULT 0,
			opening_rate  FLOAT DEFAULT 0,
			opening_amount FLOAT DEFAULT 0,
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount FLOAT DEFAULT 0,
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount FLOAT DEFAULT 0,
			gain_loss FLOAT DEFAULT 0,
			closing_qty FLOAT DEFAULT 0,
			closing_rate  FLOAT DEFAULT 0,
			closing_value FLOAT DEFAULT 0,
			short_term FLOAT DEFAULT 0,
			long_term  FLOAT DEFAULT 0,
			speculation  FLOAT DEFAULT 0,
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			consultant_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			dayscount FLOAT DEFAULT 0,
			isintradaycol INT,
			[type] VARCHAR(20) , 
			ScriptCode Varchar(50) 
		)

		CREATE TABLE #mainoutputtable_1_Final
        ( 
		   Dup_pkid int,
		   Ac_type VARCHAR(20),
		   OrderBy varchar(100), 
           Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT   ,
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(50),
		   Flag_Type_Sold VARCHAR(50),
		   flag_script_name  VARCHAR(Max),
		   flag_holding_type VARCHAR(MAx), 
		   script_name  VARCHAR(Max),
		   holding_type VARCHAR(Max), 
		   opening_bill_no VARCHAR(100),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(20),
		   sort   VARCHAR(5) , 
		   ScriptCode Varchar(50) ,
		   LTCG_Rate FLOAT DEFAULT 0,
		   NoofDays INT 
        ) 

		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates DATETIME,@qty FLOAT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT ,@ScriptId VARCHAR(50) 
		
      IF(@status=0) 
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
				@openingDate DATETIME , @openingRate FLOAT , @openingQty FLOAT , @openingAmount FLOAT,
				@purchaseDate DATETIME , @PurchaseBillNo  VARCHAR(50), @purchaseRate FLOAT, @purchaseQty FLOAT, @purchaseAmount FLOAT,
				@soldDate DATETIME, @soldBillNo  VARCHAR(50), @soldRate FLOAT, @soldQty FLOAT, @soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50), @Consultant_Name  VARCHAR(100), 
				@SoldScriptId VARCHAR(50), @pendingSoldDate VARCHAR(50), @pendingSoldBillNo VARCHAR(10), @pendingSoldQty FLOAT, @pendingSoldRate FLOAT, @PurchaseIntraFlag VARCHAR(100), 
				@SaleIntraFlag VARCHAR(10),@TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@Dup_pkid int, @Pkid VARCHAR(50),@idcount int  ,@Ac_Types VARCHAR(50),@tablerowscount INT
				
		
				CREATE TABLE #SCriptCodes
				(
					ScriptCode VARCHAR(MAX)
				)
	
				IF(@ScriptCode != '')
					INSERT INTO #SCriptCodes SELECT value FROM Fn_split(@ScriptCode, ',') 
				ELSE 
					INSERT INTO #SCriptCodes SELECT Script_Code FROM mst_script 
		

				CREATE TABLE #ConsultantCodes
				(
					ConsultantCodes VARCHAR(MAX)
				)

				IF(@ConsultantCode = '0')	
					BEGIN
							SELECT DISTINCT p.member_code,p.year_code,
								STUFF((	SELECT distinct ',' + p1.Consultant_Code
										FROM Mst_Consultant p1
										FOR XML PATH(''), TYPE
									  ).value('.', 'NVARCHAR(MAX)')
								,1,1,'') ConsultantCode
							into #temoConsultant
							FROM Mst_Consultant p
							SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant)-- WHERE member_code = @memcode AND year_code = @yearcode)
							DROP table #temoConsultant							
					END
				 
				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes SELECT Consultant_Code FROM Mst_Consultant  

				SELECT  ROW_NUMBER ( ) OVER (ORDER BY	t.script_code,t.Ac_Type,t.trans_dt ) AS NameId,	
														t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,t.TransType,t.Ac_Type,
														t.Script_Code,t.Last_Date,t.Qty,t.Rate,
														t.Member_code,t.YearCode,t.Consultant_code,t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,t.Exp_Rate,t.FrmNm,t.ID,
														Ms.bse_code,Ms.nse_code,Ms.script_name,ma.ac_name AS 'Holding Type',
					CASE	WHEN (t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101) THEN 'Opening'
							WHEN TransType		=	'Bought'	AND t.Bill_no = 'Bonus'			THEN 'Bonus' 
							WHEN TransType		=	'Bought'	AND t.Bill_no = 'Rights'		THEN 'Rights' 
							WHEN TransType		=	'Bought'	AND t.Bill_no = 'Split'			THEN 'Split' 
							WHEN TransType		=	'Bought'	AND t.Bill_no = 'Transfer'		THEN 'Transfer' 
							WHEN t.TransType	=	'Bought'	AND t.Bill_no != 'Opening'		THEN 'Bought' 
							WHEN TransType		=	'Sold'										THEN 'Sold' 
							WHEN TransType		=	'Bought'	AND Frmnm = 'IPO'				THEN 'IPO'  
					END AS 'Flag_Type',
					ISNULL(cm.Consultant_Name,'')Consultant_Name,
					ISNULL(BB.Broker_Code,'') Broker_Code --,t.isstock
				INTO #alldata
				FROM brokerbill_trans t 
				LEFT JOIN mst_script ms		ON t.script_code = Ms.script_code 
				LEFT JOIN mst_account ma	ON t.ac_type = ma.ac_code AND ma.member_code = @memcode
				LEFT JOIN Mst_Consultant cm ON t.Consultant_code = cm.Consultant_code    			
				LEFT JOIN BrokerBill BB		oN BB.Trans_No=t.Trans_No 
				WHERE 
				((t.TransType = 'Sold' AND t.Trans_Dt >= '01/31/2018') OR t.TransType != 'Sold') AND
				t.isfnobill = @Investmenttype AND t.trans_dt <= @Todate AND t.member_code = @memcode AND t.yearcode = @yearcode  AND 
				t.Ac_Type =(CASE WHEN  @Ac_Type='0' THEN t.Ac_Type  ELSE  @Ac_Type END)
				AND	t.script_code IN (SELECT * FROM #SCriptCodes)
				AND	t.Consultant_code IN (SELECT * FROM #ConsultantCodes)
				AND ISNULL(t.isIntraDay,0) = (CASE WHEN ISNULL(@IsIntraDay,0)=0 THEN ISNULL(isIntraDay,0) ELSE ISNULL(@IsIntraDay,0) END) 
				AND t.MergedEntry = 0 AND ISNULL( t.Ref_SrNo,0) != 1
				AND (IsSLBS=0 OR IsSLBS IS NUll) 
				GROUP BY t.Trans_Dt,t.Trans_No,t.Sr_No,t.Script_Code,t.Ac_Type,t.Bill_no,TransType,BB.Broker_Code,MonthYear,Last_Date,LotSize,t.Qty,LotQty,Disp_qty,
				Bal_qty,G_Rate,t.Brok_Amt,ServTax_Amount,Rate,t.Amount,Stt_Amount,t.Member_Code,t.YearCode,t.Consultant_code,
				t.EntrySource,t.Ref_TransNo,Ref_SrNo,t.MergedEntry,t.isFNOBill,Strike_Price,OptionType,isIntraDay,Brok_PerUnit,lockedbymerger,
				frac_Qty,Org_Trans_No,Org_SrNo,isDeleteMerger,isstock,ScripwiseExpense,isClient_code,isClient_Brokrage,c_Qty,C_Gross_Rate,
				C_Net_Rate,C_Amount,C_STT,C_STax,C_MisChg,TransactionChg,C_StampDuty,Exp_Rate,PerExp_Unit,FrmNm,ID,bse_code,nse_code,script_name,ma.AC_Name,cm.Consultant_Name,t.isstock			
				DECLARE @isIntradayCol INT 
				DECLARE  @COUNT INT = 0
				DECLARE alldatacursor CURSOR READ_ONLY FOR 

				SELECT id,Trans_No,script_name,Script_Code,[holding type],bill_no,CONVERT(VARCHAR(10),trans_dt,101) trans_dt ,qty,rate,ISNULL(qty, 0) * ISNULL(rate, 0),ISNULL(isintraday, 0),consultant_name   
				FROM #alldata
				WHERE (TransType != 'Sold' AND #alldata.bill_no IN('Split','Opening')) OR  CONVERT(date,trans_dt,101)  < CONVERT(date ,@StartYearDate,101)
				
				--select * from #alldata
				
				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId,@holding_type, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
						IF(@Investmenttype=2)
							SET @holding_type='Mutual Fund'
							
						SET @Pkid = (SELECT (MAX(ISNULL(pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId AND ID = @ID)
						SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
						SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
						SET @Dup_pkid = ISNULL(@Dup_pkid,0)
						SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
						SET @Dup_pkid = @Dup_pkid + 1

						DECLARE @IDs INT=0
						DECLARE @Flag_Types VARCHAR(10)
						SET @Flag_Types = (SELECT CASE WHEN @billno = 'Opening' THEN 'Opening' ELSE 'Bought' END)
						IF(@Flag_Types='Opening'  OR (@billno IN('Split') AND CONVERT(DATE,@dates,101)  < CONVERT(DATE ,@StartYearDate,101))OR (@billno NOT IN('Bought','Sold') AND CONVERT(date,@dates,101)  < CONVERT(date ,@StartYearDate,101)))
							BEGIN	
								INSERT INTO #mainoutputtable_1   
									(Dup_pkid,opening_bill_no ,id,ScriptCode,  Trans_No,  Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,consultant_name) 
								VALUES 
									( @Dup_pkid,@billno,@ID,@ScriptId,  @Trans_No, 'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Consultant_Name)
							END	
							--SET @COUNT = @COUNT - 1
								
						SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),0) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
								
						IF(@idcount>0)
							BEGIN
								UPDATE #MainOutputtable_1 
								SET Dup_pkid = Dup_pkid + 1 
								WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
								END
					
						FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type,@billno,@dates,@qty,@rate,@amount,@isIntradayCol, @Consultant_Name
					END 

				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 
				DECLARE @salecount INT = 0, @Boughtcount INT = 0,@Flag_Type VARCHAR(20)
				 
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
				SELECT id,Bill_no,Flag_Type,TransType,script_name,Script_Code, [holding type],Trans_No,  trans_dt,   qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name
				FROM #alldata 
				WHERE  (TransType in('Bought','Sold')  AND CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
			
				--GROUP BY  script_name,Script_Code,[holding type],trans_dt,Bill_no,Sr_No,Trans_No,id,Flag_Type,TransType,qty,rate ,isIntraDay,Consultant_Name
				--ORDER BY script_name, [holding type],  trans_dt  ,Bill_no  asc
				
				OPEN purchaseANDSaledatacursor 
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType, @scriptname,@ScriptId,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
				
				WHILE (@@FETCH_STATUS = 0) 
						BEGIN
							SET @COUNT = 0
							DECLARE @IsOpening			INT		= 0 , @prioritysId		INT				=	0,	@str				VARCHAR(MAX)	= ''	
							DECLARE @purchase_Op_Qty	FLOAT	= 0 , @purchase_Op_Bill VARCHAR(20)		=	'', @purchase_Op_Date	VARCHAR(20)		= ''
							DECLARE @purchase_Op_Rate	FLOAT	= 0 , @PurQTY			FLOAT			=	0
							DECLARE	@BalPurQTY			FLOAT	= 0 , @BalSoldQTY		FLOAT			=	0 , @Balpurchase_Op_Qty FLOAT = 0, @BalOpeningQTY FLOAT = 0
							DECLARE	@Sold_Qty			FLOAT	= 0 , @tempID			int				=	0
							IF(@isIntradayCol=0)
								BEGIN
									IF(@Investmenttype=2)
										 SET @holding_type='Mutual Fund'

									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (	SELECT COUNT(*) 
															FROM #MainOutputtable_1 
															WHERE holding_type = @holding_type 
															AND script_name=@scriptname 
															AND Flag_Type_Sold ='Sold'  
															and  Flag_Type ='Sold' 
															AND ISNULL(sold_qty,0)!=0 
															AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) 
															AND isintradaycol=0  
															AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))

											IF (@COUNT > 0)
												BEGIN
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  Ac_Type,scriptcode, 
													CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,* 
													INTO #tempSoldValExists 
													FROM #MainOutputtable_1 
													WHERE holding_type = @holding_type 
													AND script_name=@scriptname 
													AND Flag_Type_Sold ='Sold'  
													and  Flag_Type ='Sold' 
													AND ISNULL(sold_qty,0)!=0 
													AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) 
													AND isintradaycol=0  
													AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
													ORDER BY NameId				

													DECLARE @R_Sold_COUNT INT = ( SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty FLOAT 
													--SET @purchase_Op_Qty=@qty
													WHILE(@R_Sold_COUNT  > 0 )
														BEGIN
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists ORDER BY pkid)
															SET @str = @TransType
															
															SELECT TOP 1	@Sold_Qty		= sold_qty,
																			@soldDate		= sold_date,
																			@soldRate		= sold_Rate,
																			@soldBillNo		= sold_bill_no,
																			@Pkid			= Pkid
																	
															FROM #tempSoldValExists
															WHERE id  = @tempSaleID 

															SET @purchase_Op_Qty = @qty
															 
															IF(@TransType='Opening')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	opening_date=@dates,
																		opening_rate=@rate,
																		opening_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																	Flag_Type = 'Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	purchase_date=@dates,
																		purchase_bill_no=@billno,
																		purchase_rate=@rate,
																		purchase_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type = 'Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(purchase_qty,0)=0 AND pkid = @pkid
																END
															if(@Sold_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	sold_qty = @purchase_Op_Qty 
																	WHERE  id  = @tempSaleID AND Flag_Type_Sold='Sold' AND pkid = @pkid
																END

															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND pkid = @pkid
															DECLARE @Balancedval   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Sold_Qty) 
															
															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempSoldValExists)

															IF(@Balancedval  < 0)
																BEGIN
																--	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty = ABS(@Balancedval) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1) 
																	SET @prioritysId = ISNULL(@prioritysId,0)+1

																	INSERT INTO #MainOutputtable_1
																		(ID,Dup_pkid, ScriptCode,Ac_type ,   Trans_No, Flag_Type, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name)
																	VALUES
																		(@tempSaleID , @Dup_pkid , @ScriptId,@Ac_Types ,   @Trans_No,'Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name)
																	
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID
																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																		SET @Balancedval = 0

																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount=0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1)

																	IF(@TransType='Opening')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(ID,Dup_pkid, Trans_No,ScriptCode,Ac_type ,  Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name)
																			VALUES(@ID,@Dup_pkid, @Trans_No,@ScriptId,@Ac_Types , 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name)
																			
																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	ELSE IF(@TransType='Bought')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(ID,Dup_pkid, Trans_No, ScriptCode,Ac_type ,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name)
																			VALUES(@ID,@Dup_pkid, @Trans_No,@ScriptId,@Ac_Types ,  'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name)
																			
																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END

																		SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																	ENd
															ELSE IF(@Balancedval=0)
																BEGIN
																	break;
																END
															SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
															SET @qty = @Balancedval
														END
												 
													
													DROP TABLE #tempSoldValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)

													INSERT INTO #mainoutputtable_1 (id,Dup_pkid, Trans_No,ScriptCode,Ac_type,  prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name) 
												    VALUES ( @ID,ISNULL(@Dup_pkid,0), @Trans_No,@ScriptId,@Ac_Types,  @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name) 

												
												END

										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') AND ISNULL(sold_qty,0)=0  AND isnull(isintradaycol,0)=0  )
										
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,Ac_type,case when opening_date <> NULL then opening_date else purchase_date end ) AS NameId,* 
													INTO #tempValExists 
													FROM
													#MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') 
													AND ISNULL(sold_qty,0) = 0  AND isintradaycol = 0 
													ORDER BY NameId
													
													DECLARE @RCOUNT INT = (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty FLOAT 

													WHILE(@RCOUNT > 0 )
														BEGIN 
															SET @Sold_Qty = @qty
															SET @tempID = (SELECT TOP(1) id FROM #tempValExists ORDER BY dup_pkid)
															SET @str = (SELECT TOP(1) Flag_Type FROM #tempValExists WHERE id = @tempID  )

															IF(@str='Opening')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= opening_qty,
																					@openingDate	= opening_date,
																					@openingrate	= opening_rate,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID
																END
															ELSE IF(@str='Bought')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= purchase_qty,
																					@PurchaseDate	= purchase_date,
																					@Purchaserate	= purchase_rate,
																					@PurchaseBillNo = purchase_bill_no,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID
																END

															IF(@Sold_Qty > 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	UPDATE #MainOutputtable_1  
																		SET	
																			opening_qty     = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							  END,
																			purchase_qty    = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							   END,
																			sold_date       = @dates,
																			sold_bill_no    = @billno,
																			sold_rate       = @rate,
																			sold_qty        = CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold  = 'Sold',
																			prioritys       = @prioritysId
																	WHERE  id = @tempID AND ISNULL(sold_qty,0)=0 AND pkid = @Pkid
																	SET @Balanceval = ABS(@Sold_Qty) - ABS(@TempSoldQty)
																END
															DELETE FROM #tempValExists WHERE id = @tempID AND pkid = @pkid
															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempValExists)
															SET @RCOUNT = @RCOUNT - 1
														
														
															IF(@Balanceval < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	IF(@str='Opening')
																		BEGIN
																			SET @openingQty = ABS(@Balanceval) 
																			SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																			SET @prioritysId = ISNULL(@prioritysId,0)+1
																			
																			INSERT INTO #MainOutputtable_1(ID,Dup_pkid, Trans_No,Ac_type, ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name)
																			VALUES(@tempID,@Dup_pkid, @Trans_No,@Ac_Types, @ScriptId, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name)
																			
																			SET @prioritysId = ISNULL(@prioritysId,0)+1
															
																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId   
																			WHERE prioritys >= @prioritysId AND ID <> @tempID
																		END
																	ELSE 
																		BEGIN
																			SET @PurchaseQty = ABS(@Sold_Qty) 
																			SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																			SET @prioritysId = ISNULL(@prioritysId,0)+1
																			INSERT INTO #MainOutputtable_1(ID,Dup_pkid, Trans_No,Ac_type  , ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name)
																			VALUES(@tempID,@Dup_pkid, @Trans_No,@Ac_Types, @ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name)
																			SET @prioritysId = ISNULL(@prioritysId,0)+1

																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId    
																			WHERE prioritys >= @prioritysId AND ID <> @tempID
																 
																		END
																	 
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),1) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																		SET @Balanceval = 0
																	BREAK;
																END
														
															ELSE IF(ISNULL(@Balanceval,0) > 0 and @tablerowscount=0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1


																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																	INSERT INTO #MainOutputtable_1(ID,Dup_pkid, Trans_No,Ac_type,  ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
																	VALUES(@ID,@Dup_pkid, @Trans_No,@Ac_Types, @ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name)
																	
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																END
															
															ELSE IF(ISNULL(@Balanceval,0) =0)
																BEGIN
																	SET @Balanceval=0
																	BREAK;
																END
																 
															SET @qty = @Balanceval
														END

												DROP TABLE #tempValExists
											END
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													--SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
													--SET @prioritysId = ISNULL(@prioritysId,0)+1
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #MainOutputtable_1)
													SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0)+1 from #MainOutputtable_1)
													 
													INSERT INTO #MainOutputtable_1(ID,Dup_pkid, Trans_No,ScriptCode,Ac_type,   Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
													VALUES(@ID,@Dup_pkid, @Trans_No,@ScriptId, @Ac_Types, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name)
												END
											
											SET @purchase_Op_Date	=	''
											SET @purchase_Op_Rate	=	''
											SET @purchase_Op_Qty	=	''
											SET @purchase_Op_Bill	=	''
										END
								END
							FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType, @scriptname,@ScriptId,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
						END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
	  	END 
		If(@IsBSEISIN=1)
		BEGIN
				INSERT INTO #mainoutputTable_1_BSEISISNO 				
				SELECT ma.Dup_pkid,ma.Ac_type, ma.pkid,ma.Trans_No,ma.id,ma.Trans_Type, ma.Split_Type, ma.Flag_Type, ma.Flag_Type_Sold,ma.flag_script_name,
				ma.flag_holding_type,  
				ma.script_name + '[' +ms.BSE_Code + ']' + '[' +ms.ISIN_No+ ']',ma.holding_type,ma.opening_bill_no ,ma.opening_date ,ma.opening_qty,ma.opening_rate ,ma.opening_amount ,ma.purchase_date ,ma.purchase_bill_no ,
				ma.purchase_qty,ma.purchase_rate,ma.purchase_amount ,ma.sold_date ,ma.sold_bill_no ,ma.sold_qty,ma.sold_rate,ma.sold_amount ,ma.gain_loss ,ma.closing_qty,
				ma.closing_rate,ma.closing_value,ma.short_term ,ma.long_term ,ma.speculation ,ma.gain_speculation ,ma.loss_speculation ,ma.consultant_name ,ma.nse_rate ,ma.bse_rate, 
				ma.dayscount, ma.isintradaycol,ma.[type],ma.ScriptCode
				from #mainoutputtable_1 ma 
				INNER JOIN Mst_Script Ms On  ma.ScriptCode=Ms.Script_Code
		END
		ELSE if(@IsBSEISIN=0)
			BEGIN	   
				INSERT INTO #mainoutputTable_1_BSEISISNO 				
				SELECT ma.Dup_pkid,ma.Ac_type, ma.pkid,ma.Trans_No,ma.id,ma.Trans_Type, ma.Split_Type, ma.Flag_Type, ma.Flag_Type_Sold,ma.flag_script_name,
				ma.flag_holding_type,ma.script_name,ma.holding_type,ma.opening_bill_no ,ma.opening_date ,ma.opening_qty,ma.opening_rate ,ma.opening_amount ,ma.purchase_date ,ma.purchase_bill_no ,
				ma.purchase_qty,ma.purchase_rate,ma.purchase_amount ,ma.sold_date ,ma.sold_bill_no ,ma.sold_qty,ma.sold_rate,ma.sold_amount ,ma.gain_loss ,ma.closing_qty,
				ma.closing_rate,ma.closing_value,ma.short_term ,ma.long_term ,ma.speculation ,ma.gain_speculation ,ma.loss_speculation ,ma.consultant_name ,ma.nse_rate ,ma.bse_rate, 
				ma.dayscount, ma.isintradaycol,ma.[type],ma.ScriptCode
				from #mainoutputtable_1 ma 
		END
	 
					INSERT INTO #mainoutputtable_1_Final (OrderBy,id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
					opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
					purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
					sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
					short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )
				
					SELECT  ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
							 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId, 
					id,Trans_No,ScriptCode, prioritys,script_name ,Holding_Type,opening_date,
					opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
					purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
					sold_rate,sold_amount ,
						Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
											THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
										WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
											THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
										ELSE 0.0	
									END,0) ,4)
					as gain_loss,
					closing_qty ,closing_rate ,ROUND(closing_value,4) ,
					0,
					Round(
					ISNULL((Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty))
							,0)
						,4),
					0,
					0,
					0,
					consultant_name,nse_rate,bse_rate,1 sort ,isintradaycol
					FROM #mainoutputTable_1_BSEISISNO 
					WHERE ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
					AND 
						(
							(ISNULL(opening_date,'') !=''  AND 
								(
										 
									    DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME,opening_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365 
								)
							)
							OR 
							(ISNULL(purchase_date,'') !=''  AND
								(
									DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME, purchase_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365
								)
							)
						)
						order by NameId
					SELECT t.Trans_No,	t.id,	t.prioritys,	t.Split_Type,	t.Flag_Type,	t.Flag_Type_Sold,	t.flag_script_name,	t.flag_holding_type,	t.script_name,	t.holding_type,
					t.opening_date	,t.opening_qty	,t.opening_rate	,t.opening_amount,	t.purchase_date,	t.purchase_bill_no,	t.purchase_qty,	t.purchase_rate,
					t.purchase_amount	,t.sold_date	,t.sold_bill_no	,t.sold_qty,	t.sold_rate	,t.sold_amount,	t.gain_loss,	t.gain	,t.loss	,
					t.closing_qty	,t.closing_rate,	t.closing_value,	t.short_term,	t.long_term,	t.speculation	,t.gain_speculation,
					t.loss_speculation,	t.consultant_name	,t.nse_rate,	t.bse_rate,	t.dayscount,	t.isintradaycol,	t.type,	t.sort,	t.ScriptCode,
					CASE WHEN Dr.Bse_High_Rate IS  NOT NULL  THEN  Dr.Bse_High_Rate  ELSE Dr.NSE_High_Rate  end as 'LTCG_Rate',DATEDIFF(DAY,t.opening_date,t.sold_date)As'NoofDays' 						 					
					INTO #alldata1
					FROM #mainoutputtable_1_Final t
					JOIN DailyRate DR ON DR.Script_Code=t.ScriptCode AND DR.InvestmentType = @Investmenttype AND  DR.Trans_Dt = '01/31/2018'
							 
					IF(@OUTPUT_Flag='Details')
						BEGIN
							SELECT id,prioritys,ScriptCode,script_name 'Script Name',Holding_Type,'' Ac_Type, 
							CONVERT(DATETIME, opening_date,101 )  'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',opening_Rate 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount', 
							CONVERT(DATETIME, purchase_date,101)'Purchase Date',purchase_bill_no 'Purchase BillNo',ROUND(ISNULL(purchase_qty,0),4) 'Purchase Qty',ROUND(ISNULL(purchase_rate,0),4) 'Purchase Rate',ROUND(ISNULL(purchase_amount,0),4) 'Purchase Amount',
							CONVERT(DATETIME, sold_date,101 ) 'Sold Date',sold_bill_no 'Sold BillNo',ROUND(ISNULL(sold_qty,0),4) 'Sold Qty',
							ROUND(sold_rate,4) 'Sold Rate',ROUND(ISNULL(sold_amount,0),4) 'Sold Amount',ROUND(ISNULL(gain_loss,0),4) 'Gain/Loss',
							CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS 'Gain',
							CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS  'Loss',
							ISNULL(closing_qty,0) 'Closing Qty',closing_rate 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
							short_term,
							long_term,
							speculation,
							gain_speculation,
							loss_speculation,
							'' consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),ISNULL(isintradaycol,0),1 sort ,LTCG_Rate,NoofDays
							FROM #alldata1
							WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)
							ORDER BY  Holding_Type,script_name,prioritys,id

						END
		 
		DROP TABLE #mainoutputtable_1 
		DROP TABLE #mainoutputTable_1_BSEISISNO
		DROP TABLE #alldata 
	 	DROP TABLE #alldata1
  END  









































GO
/****** Object:  StoredProcedure [dbo].[proc_Stockholdingposition_Equity_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockholdingposition_Equity_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Stockholdingposition_Equity_Summary] AS' 
END
GO
--Execute  proc_Stockholdingposition_Equity_Summary    0,0,'0','Y0001','1120172018','2015-02-01 12:00:00:00','2018-03-28 03:50:37:50','','','','', '0' ,'0',0,1,0
--Execute  proc_Stockholdingposition_Equity_Summary    0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0',1,1,1
ALTER PROCEDURE [dbo].[proc_Stockholdingposition_Equity_Summary]  --''
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,
@RecordOnlyhavingClosingbalanceZero as bit,@WithActualAvgRate as bit, @DateWiseClosinStock as bit,@IsWithTax bit = 0)
AS
BEGIN
SET NOCOUNT ON;
		CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
			prioritys INT,
			Trans_No VARCHAR(50),
			id INT,
			Ac_type VARCHAR(50),
			Broker_Code VARCHAR(20),
			Consultant_Code varchar(20), 
			ScriptCode  VARCHAR(50), 
			script_name  VARCHAR(500),
			holding_type VARCHAR(200),
			flag_script_name  VARCHAR(500),
			flag_holding_type VARCHAR(200),
			opening_date VARCHAR(10),opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
			purchase_date VARCHAR(10),purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
			sold_date VARCHAR(10),sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
			gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
			closing_qty FLOAT DEFAULT 0, 
			closing_rate FLOAT DEFAULT 0,
			closing_value FLOAT DEFAULT 0,
			short_term FLOAT DEFAULT 0,
			long_term FLOAT DEFAULT 0, 
			speculation FLOAT DEFAULT 0, 
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			consultant_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			Other_amt FLOAT DEFAULT 0,
			ServTax_Amt FLOAT DEFAULT 0,
			Stt_amt FLOAT DEFAULT 0,
			sort   VARCHAR(5),
			isintradaycol  INT 
        ) 


		IF(@ConsultantCode = '0')
			BEGIN
						
					SELECT DISTINCT p.member_code,p.year_code,
						STUFF((	SELECT distinct ',' + p1.Consultant_Code
								FROM Mst_Consultant p1
								--WHERE p.member_code = p1.member_code AND p.year_code = p1.year_code
								FOR XML PATH(''), TYPE
								).value('.', 'NVARCHAR(MAX)')
						,1,1,'') ConsultantCode
					into #temoConsultant
					FROM Mst_Consultant p

					SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant)-- WHERE member_code = @memcode AND year_code = @yearcode)
					DROP table #temoConsultant
	
			END

		INSERT INTO #mainoutputtable_1_Final_Summary
		EXEC proc_Stockholdingposition_Equity   @status,@Investmenttype,@Ac_Type,@memcode,@yearcode,@Fromdate,@Todate,@ScriptCode,@ConsultantCode,@BSE_NSE_Code,@Is_BFCF,@IsIntraDay,@short_Long_Term,'ALLData',0,@IsWithTax
		
		Select * INTO #DailyRates from DailyRate Where Trans_Dt = @Todate

		SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
		T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
		T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
		T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
		T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
		T1.consultant_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,
		T1.Ac_type,T1.Broker_Code,
		T1.Consultant_Code,T1.ScriptCode,
		ISNULL(Dr.BSE_Rate,0)  AS 'bse_rate', /**/
		ISNULL(Dr.NSE_Rate,0) AS  'nse_rate' /**/
		INTO #alldata 
		FROM #mainoutputtable_1_Final_Summary  T1 /**/
		LEFT JOIN BrokerBill T2 ON T1.Trans_No=T2.Trans_no /**/
		LEFT JOIN #DailyRates DR ON DR.Script_Code = T1.ScriptCode  --and Dr.Trans_Dt = @Todate /**/
		
		--Select * from #alldata

		TRUNCATE TABLE #mainoutputtable_1_Final_Summary
		
		INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,
		Ac_type,Broker_Code,--dematecode,
		Consultant_Code,ScriptCode) 

		SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		convert(VARCHAR(10), opening_date,103),opening_qty,opening_rate,opening_amount,
		convert(VARCHAR(10),purchase_date,103),purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		convert(VARCHAR(10),sold_date,103),sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,
		Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt,
		Ac_type,Broker_Code,
		Consultant_Code,ScriptCode    
		FROM #alldata  
		GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		Ac_type,Broker_Code,
		Consultant_Code,ScriptCode,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 

		
		IF(@RecordOnlyhavingClosingbalanceZero = 0)
			BEGIN
				IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN
								SELECT  MAX(id+1)id,holding_type,script_name AS 'Script Name', 
								ROUND(SUM(closing_value),2) AS 'Closing Value',
								SUM(closing_qty) AS 'Closing Qty', 
								ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', 
								SUM(gain_loss) AS  'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',bse_rate  AS  'BSERATE',bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END AS 'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',	nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS 'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
							  -- Select 'test'
								SELECT   holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', 
								ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								sum(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								sum(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)> 0 THEN (SUM(ISNULL(closing_value,0)) +  abs(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0) > 0  THEN (SUM(ISNULL(closing_value,0)) - abs( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  abs(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) - abs( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,
										Ac_type,Broker_Code,
										ScriptCode,Consultant_Code,	CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END,
										--gain_loss,
										bse_rate,nse_rate,
									bse_rate,nse_rate,consultant_name
										--HAVING SUM(closing_qty) != 0
								HAVING SUM(closing_qty) != 0
							END
					END
				ELSE IF(@WithActualAvgRate = 1 OR @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  MAX(id+1)id,holding_type,script_name AS 'Script Name', 
								ROUND(SUM(closing_value),2) AS 'Closing Value',
								SUM(closing_qty) AS 'Closing Qty', 
								ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', 
								SUM(gain_loss) AS  'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',bse_rate  AS  'BSERATE',bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END AS 'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',	nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS 'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								IF(@WithActualAvgRate = 0 AND @DateWiseClosinStock=1)
									BEGIN
									--Select 'test'
										SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', SUM(gain_loss) AS  'Gain/Loss',
										Ac_type,Broker_Code,
										ScriptCode,Consultant_Code,
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END  AS  'Closing Date',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
												ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
												0 END 
												END AS 'Avg. Rate',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
												ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
												0 END 
												END AS 'Value After Profit/Loss',
										SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY holding_type,script_name,
										Ac_type,Broker_Code,
										ScriptCode,Consultant_Code,
										bse_rate,nse_rate,
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END,bse_rate,nse_rate,consultant_name
										HAVING SUM(closing_qty) != 0
									END
								ELSE
									BEGIN
										
										SELECT   holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) + ABS( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0)>0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
											0 END 
											END AS 'Avg. Rate',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) - ABS( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) + ABS( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
											0 END 
											END AS 'Value After Profit/Loss',
										0 Other_amt, '' consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY holding_type,script_name,bse_rate,nse_rate 
								
										HAVING SUM(closing_qty) != 0
									END
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT   max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(gain_loss) AS  'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name 
							END
						ELSE
							BEGIN
								SELECT   holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty',
								 ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					END
			END
		ELSE IF(@RecordOnlyhavingClosingbalanceZero = 1)
			BEGIN
				IF (@WithActualAvgRate = 1 OR @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN 
								SELECT  MAX(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate', 0 'Closing Value',
								Ac_type,''Broker_Code,
								ScriptCode,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0))  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss','' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,Ac_type,script_name,ScriptCode,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
							END
					END

				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE',SUM(gain_loss) AS  'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name

							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE',SUM(gain_loss) AS  'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt,'' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) = 0
							END
					END
			END
			DROP TABLE #alldata

END




































GO
/****** Object:  StoredProcedure [dbo].[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency] AS' 
END
GO




--[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency] 0,1,'0','Y0001','1120172018','2017-04-01 12:00:00:00','2018-03-31','','','','', '0' ,'0','Details'
--[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency] 0,1,'0','30001','1120182019','2017-02-01 12:00:00:00','2019-03-31 03:50:37:50','','','','', '0' ,'0','details'
ALTER PROCEDURE [dbo].[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency] --0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','ScriptWiseTotal'
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,
@OUTPUT_Flag VARCHAR(MAX),@IsWithTax bit = 0,
@Script_Name varchar(max) = '')
AS 
  BEGIN  
  SET NOCOUNT ON;
		DECLARE @StartYearDate VARCHAR(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101)
		CREATE TABLE #mainoutputtable_1
          ( 
			pkid INT identity(1,1),
			Dup_pkid INT,
			Trans_No VARCHAR(20),
			id INT,
			sr_no  INT,
			prioritys INT,
			Trans_Type  VARCHAR(50),
		    Split_Type VARCHAR(50),
			Flag_Type VARCHAR(10),
			Flag_Type_Sold VARCHAR(10),
			flag_script_name  VARCHAR(500),
			flag_holding_type VARCHAR(200), 
			script_name  VARCHAR(500),
			holding_type VARCHAR(200), 
			opening_bill_no VARCHAR(10),		    
			opening_date DATETIME,
			opening_qty  FLOAT DEFAULT 0,
			opening_rate  FLOAT DEFAULT 0,
			opening_amount AS( [opening_qty] * [opening_rate] ), 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount AS( purchase_qty * purchase_rate ), 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount AS ( sold_qty * sold_rate ), 
			gain_loss float,
			closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 AND (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 
			closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
			closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
			short_term FLOAT DEFAULT 0,
			long_term  FLOAT DEFAULT 0,
			speculation  FLOAT DEFAULT 0,
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			consultant_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			dayscount FLOAT DEFAULT 0,
			isintradaycol INT,
			[type] VARCHAR(20) ,
			ScriptCode VARCHAR(50) ,
			 Exp_Rate float DEFAULT 0,
			Strike_Price float DEFAULT 0,
			OptionType VARCHAR(100),
			MonthYear VARCHAR(100),
			Last_Date VARCHAR(100),
			Broker_Code VARCHAR(100),dp_code VARCHAR(100),Consultant_code VARCHAR(500)
        )  

		CREATE TABLE #mainoutputtable_1_Final
        ( 
			pkid int,
			Dup_pkid int, 
			OrderBy varchar(100),
			Trans_No VARCHAR(20),
			id INT,
			sr_no  INT,
			prioritys INT   ,
			Split_Type VARCHAR(50),
			Flag_Type VARCHAR(10),
			Flag_Type_Sold VARCHAR(10),
			flag_script_name  VARCHAR(500),
			flag_holding_type VARCHAR(200), 
			script_name  VARCHAR(500),
			holding_type VARCHAR(200), 
		    opening_bill_no VARCHAR(10),		    
			opening_date DATETIME,
			opening_qty  FLOAT DEFAULT 0,
			opening_rate  FLOAT DEFAULT 0,
			opening_amount FLOAT DEFAULT 0, 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount FLOAT DEFAULT 0 , 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount FLOAT DEFAULT 0, 
			gain_loss FLOAT DEFAULT 0,
			gain AS CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
			loss AS CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
			closing_qty FLOAT DEFAULT 0, 
			closing_rate FLOAT DEFAULT 0,
			closing_value FLOAT DEFAULT 0,
			short_term FLOAT DEFAULT 0,
			long_term FLOAT DEFAULT 0, 
			speculation FLOAT DEFAULT 0, 
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			consultant_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			dayscount FLOAT DEFAULT 0,
			isintradaycol INT,
			[type] VARCHAR(20),
			sort VARCHAR(5),
			ScriptCode VARCHAR(50) ,
			Strike_Price float DEFAULT 0,
			Exp_Rate float DEFAULT 0,
			OptionType VARCHAR(100),
			MonthYear VARCHAR(100),
			Last_Date VARCHAR(100),
			Broker_Code VARCHAR(100),
			dp_code VARCHAR(100),Consultant_code VARCHAR(500)
        ) 

		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty INT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT  
		DECLARE @tablerowscount INT,@sr_no  INT 
      IF(@status = 0)
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(max),
				@openingDate VARCHAR(50),@openingRate FLOAT,@openingQty INT,@openingAmount FLOAT,
				@purchaseDate VARCHAR(50),@PurchaseBillNo  VARCHAR(50),@purchaseRate FLOAT,@purchaseQty INT,@purchaseAmount FLOAT,
				@soldDate VARCHAR(50),@soldBillNo  VARCHAR(50),@soldRate FLOAT,@soldQty INT,@soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50),@Consultant_Name  VARCHAR(MAX), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(10),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,
				@PurchaseIntraFlag VARCHAR(100),@SaleIntraFlag VARCHAR(10), @Dup_pkid varchar(50), @Pkid varchar(50),@idcount int   

				DECLARE @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@ScriptId VARCHAR(MAX),
				@Strike_Price FLOAT,@OptionType VARCHAR(50),@Last_Date VARCHAR(50),@MonthYear VARCHAR(50),
				@Exp_Rate VARCHAR(50),@Broker_Code VARCHAR(50),@dp_code VARCHAR(50),@Consultant_code  VARCHAR(MAX)

				CREATE TABLE #SCriptName
				(
					ScriptName varchar(MAX)
				)

				IF(@Script_Name != '')
					INSERT INTO #SCriptName SELECT value FROM Fn_split(@Script_Name, ',') 
				ELSE 
					BEGIN
						INSERT INTO #SCriptName 
						Select distinct (Ms.script_name 
								+ '/' + CONVERT(VARCHAR(10),t.Last_Date,103) 
								+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
								+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' END) 
						from brokerbill_Trans t
						Left Join mst_Script ms on ms.script_Code = t.script_Code 
					END

				CREATE TABLE #ConsultantCodes
				(
					ConsultantCodes varchar(MAX)
				)

				IF(@ConsultantCode = '0')	
					BEGIN
						SELECT DISTINCT p.member_code,p.year_code,
							STUFF((	SELECT distinct ',' + p1.Consultant_Code
									FROM Mst_Consultant p1
									FOR XML PATH(''), TYPE
									).value('.', 'NVARCHAR(MAX)')
							,1,1,'') ConsultantCode
						into #temoConsultant
						FROM Mst_Consultant p

						SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant) --WHERE member_code = @memcode AND year_code = @yearcode)
						DROP table #temoConsultant
					END
				 
				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes select Consultant_Code from Mst_Consultant
				
				SELECT	ROW_NUMBER ( ) OVER (ORDER BY t.script_code,t.trans_dt ) AS NameId,t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,t.TransType, '' Ac_Type,
				t.Script_Code, t.Qty,
				Case When @IsWithTax=0 Then t.Rate Else t.Exp_Rate END As 'Rate',
				t.Member_code,t.YearCode,t.Consultant_code,t.isFNOBill,t.Strike_Price,t.OptionType,MonthYear,Last_Date,t.isIntraDay,t.Exp_Rate,t.FrmNm,t.ID,Ms.bse_code,Ms.nse_code,
				Ms.script_name 
					+ '/' + CONVERT(VARCHAR(10),t.Last_Date,103) 
					+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
					+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' END 
				script_name,
				'Empty' AS 'Holding Type',
				CASE WHEN (((t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101))AND t.TransType='Bought') THEN 'Opening'
							WHEN t.TransType='Bought' AND  t.Bill_no != 'Opening'  THEN 'Bought' 
							WHEN TransType='Sold' THEN 'Sold' 
					END AS 'Flag_Type',
					cm.Consultant_Name,ISNULL(BB.Broker_Code,'') Broker_Code,ISNULL(BBD.dp_code,'') dp_code   ,t.isstock
				INTO #alldata 
				FROM brokerbill_trans t WITH(NOLOCK)
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN  Mst_Consultant cm ON t.Consultant_code = cm.Consultant_code  
				LEFT JOIN BrokerBill_DmatInfo BBD ON BBD.Trans_No=t.Trans_No 
				LEFT JOIN BrokerBill BB ON BB.Trans_No=t.Trans_No 
				WHERE  t.isfnobill = @Investmenttype AND t.trans_dt <= @Todate AND t.member_code = @memcode AND t.yearcode = @yearcode  
				AND  (Ms.script_name 
					+ '/' + CONVERT(VARCHAR(10),t.Last_Date,103) 
					+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
					+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' END ) 
				IN (SELECT * FROM #SCriptName)
				AND	 t.Consultant_code IN (SELECT * FROM #ConsultantCodes)
				AND  isnull(t.isIntraDay,0) =(CASE WHEN @IsIntraDay=0 THEN  isnull(isIntraDay,0) ELSE ISNULL(@IsIntraDay,0) END)
				AND t.isstock = (select case when @Is_BFCF = 1 then  '' else  t.isstock end)
				
				GROUP BY t.Script_Code,script_name,t.Consultant_code,cm.Consultant_Name , t.Trans_Dt,t.Bill_no,t.Trans_No,t.Sr_No,BB.Broker_Code,BBD.dp_code,
				TransType,MonthYear,Last_Date,t.Qty,Rate,t.Amount,t.Member_Code,t.YearCode,
				t.EntrySource,t.Ref_TransNo,Ref_SrNo,t.MergedEntry,t.isFNOBill,Strike_Price,OptionType,isIntraDay,Exp_Rate,FrmNm,ID,bse_code,nse_code ,t.isstock
		
				--SELECT * FROM #SCriptName
		    --	select * from #alldata


				DECLARE @isIntradayCol INT 
				DECLARE  @COUNT INT = 0	 

				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT id,sr_no,Trans_No,script_name,  [holding type],bill_no,CONVERT(DATETIME,trans_dt,103),
				Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,
				qty,rate,ISNULL(qty, 0) * ISNULL(rate, 0),ISNULL(isintraday, 0),consultant_name,Consultant_code   
				FROM #alldata
				WHERE ((TransType != 'Sold' AND #alldata.bill_no IN('Opening')) OR  CONVERT(date,trans_dt,101)  < CONVERT(date ,@StartYearDate,101) AND #alldata.TransType='Bought')
				
				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@sr_no,@Trans_No, @scriptname, @holding_type, @billno,@dates,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@Consultant_code
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
						IF(@Investmenttype=2)
							SET @holding_type='Mutual Fund'
						SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE script_name = @scriptname)-- AND ID = @ID)
						SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
						SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
						SET @Dup_pkid = ISNULL(@Dup_pkid,0)
						SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
						SET @Dup_pkid = @Dup_pkid + 1

						DECLARE @IDs INT=0
						DECLARE @Flag_Types VARCHAR(10)
						SET @Flag_Types = (SELECT CASE WHEN @billno = 'Opening' THEN 'Opening' ELSE 'Bought' END)
						IF(@Flag_Types='Opening'  OR (@billno IN('Split') AND CONVERT(DATE,@dates,101)  < CONVERT(DATE ,@StartYearDate,101))
							OR (@billno NOT IN('Bought','Sold') AND CONVERT(date,@dates,101)  < CONVERT(date ,@StartYearDate,101)))
							BEGIN
								INSERT INTO #mainoutputtable_1   
								(
									opening_bill_no ,sr_no,id,Dup_pkid,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Consultant_code,ScriptCode,Trans_No,   
									Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,consultant_name
								) 
								SELECT @billno,@sr_no,@ID,@Dup_pkid, @Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,
								@dp_code,@Consultant_code, @ScriptId, @Trans_No, 'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Consultant_Name
						
								SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),0) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
								IF(@idcount>0)
									BEGIN
										UPDATE #MainOutputtable_1 
										SET Dup_pkid = Dup_pkid + 1 
										WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
									END
							END
							
						FETCH NEXT FROM alldatacursor INTO @ID,@sr_no,@Trans_No, @scriptname,@holding_type,@billno,@dates,
						@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,	@qty,@rate,@amount,@isIntradayCol, @Consultant_Name,@Consultant_code
					END 

				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 		
				DECLARE @salecount INT=0,@Boughtcount INT=0,@Flag_Type VARCHAR(20)
				
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 

				SELECT id,sr_no,Bill_no,Flag_Type,TransType,Script_Code, script_name,[holding type],
				Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,
				Trans_No,CONVERT(DATETIME, trans_dt,103), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name,Consultant_code
				FROM #alldata WHERE 
				(TransType in ('Bought','Sold')  OR CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening')  
				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@sr_no,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Strike_Price,@OptionType,
				@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name,@Consultant_code 
				
				
				WHILE (@@FETCH_STATUS = 0) 
						BEGIN
							SET @COUNT									=	0
							DECLARE @IsOpening			INT				=	0
							DECLARE @prioritysId		INT				=	0
							DECLARE @str				VARCHAR(MAX)	=	''	
							DECLARE @purchase_Op_Qty	FLOAT			=	0
							DECLARE @purchase_Op_Bill	VARCHAR(20)		=	''
							DECLARE @purchase_Op_Date	VARCHAR(20)		=	''
							DECLARE @purchase_Op_Rate	FLOAT			=	0
							DECLARE	@PurQTY				FLOAT			=	0
							DECLARE	@BalPurQTY			FLOAT			=	0
							DECLARE @BalSoldQTY			FLOAT			=	0
							DECLARE @Balpurchase_Op_Qty FLOAT			=	0
							DECLARE @BalOpeningQTY		FLOAT			=	0
							DECLARE	@Sold_Qty			FLOAT			=	0
							DECLARE @tempID				int				=	0

							IF(@isIntradayCol = 0)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE   script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and   Flag_Type ='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=0 AND Consultant_Name = (CASE WHEN @ConsultantCode <> '' THEN @Consultant_Name ELSE consultant_name END))
										
											IF (@COUNT > 0)
												BEGIN
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  script_name, case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId, 
													* INTO #tempSoldValExists 
													FROM
													#MainOutputtable_1 
													WHERE script_name=@scriptname AND holding_type=@holding_type  AND isintradaycol=0 AND 
													consultant_name = (CASE WHEN @ConsultantCode <> '' THEN @Consultant_Name ELSE consultant_name END)
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold ='Sold'  and  Flag_Type ='Sold' AND isintradaycol=0
													ORDER BY NameId


													DECLARE @R_Sold_COUNT INT=(SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty INT 
												
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists ORDER BY Dup_pkid,NameId)
															SET @str = @TransType

															SELECT TOP 1	@Sold_Qty		= sold_qty,
																			@soldDate		= sold_date,
																			@soldRate		= sold_Rate,
																			@soldBillNo		= sold_bill_no,
																			@Pkid			= Pkid
																	
															FROM #tempSoldValExists
															WHERE id  = @tempSaleID 
															
															SET @purchase_Op_Qty = @qty

									
															IF(@TransType='Opening')
																BEGIN
																
																	UPDATE #MainOutputtable_1  
																	SET	opening_date	=	@dates,
																		opening_rate	=	@rate,																	 
																		opening_qty		=	CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	purchase_date	=	@dates,
																		purchase_rate	=	@rate,
																		purchase_bill_no=   @PurchaseBillNo,
																		purchase_qty		=	CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid

																END
															
															IF(@Sold_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET sold_qty = @purchase_Op_Qty 
																	WHERE  id  = @tempSaleID AND Flag_Type_Sold='Sold' AND pkid = @pkid
																END

															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND pkid = @pkid
														
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempSoldValExists )
															DECLARE @Balancedval   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)
										
															IF(@Balancedval  < 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE script_name = @scriptname)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty=ABS(@Balancedval) 
																	SET @prioritysId  =(SELECT MAX(prioritys) FROM #MainOutputtable_1) 
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	INSERT INTO #MainOutputtable_1(Dup_pkid,sr_no, ID,Consultant_code,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No,ScriptCode, Flag_Type,Flag_Type_Sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name)
																	VALUES(@Dup_pkid,@sr_no,@tempSaleID ,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No,@ScriptId,'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name)
																	
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			where Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																		SET @Balancedval=0
																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE script_name = @scriptname)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																	IF(@TransType='Opening')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,sr_no,Consultant_code,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No,ScriptCode, Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@sr_no,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No,@ScriptId, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name)

																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	ELSE IF(@TransType='Bought')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,sr_no,Consultant_code,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@sr_no,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No,@ScriptId, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name)

																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																END
															ELSE IF(@Balancedval=0)
															BEGIN
																break;
															END
															
															SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
															SET @qty = @Balancedval
														END
													
													DROP TABLE #tempSoldValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
												 
													INSERT INTO #mainoutputtable_1 (Dup_pkid,id,sr_no,Consultant_code,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No,ScriptCode, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name) 
													VALUES ( @Dup_pkid,@ID,@sr_no,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No,@ScriptId, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name) 
												END
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE   script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Transfer') AND ISNULL(sold_qty,0)=0  AND isintradaycol=0  AND Consultant_Name = (CASE WHEN @ConsultantCode <> '' THEN @Consultant_Name ELSE consultant_name END))
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  script_name ,case when opening_date <> NULL then opening_date else purchase_date end ) AS NameId, 
													* INTO #tempValExists 
													FROM
													#MainOutputtable_1 WHERE --holding_type=@holding_type AND 
													script_name =@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') 
													AND consultant_name = (CASE WHEN isnull(@ConsultantCode,'') != '' THEN @Consultant_Name ELSE consultant_name END) 
													AND ISNULL(sold_qty,0)=0  AND isintradaycol=0 
													ORDER BY NameId
												 
													DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty int 
													
													--SET @Sold_Qty = @qty
													WHILE(@RCOUNT > 0)
														BEGIN 
															SET @Sold_Qty = @qty
															SET @tempID = (SELECT TOP(1) id FROM #tempValExists ORDER BY Dup_pkid)
															SET @str = (SELECT TOP(1) Flag_Type FROM #tempValExists WHERE id  = @tempID)
														
															IF(@str = 'Opening')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= opening_qty,
																					@openingDate	= opening_date,
																					@openingrate	= opening_rate,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID

																END
															ELSE IF(@str='Bought')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= purchase_qty,
																					@PurchaseDate	= purchase_date,
																					@Purchaserate	= purchase_rate,
																					@PurchaseBillNo = purchase_bill_no,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID

																END
															    
															IF(@Sold_Qty > 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	UPDATE #MainOutputtable_1  
																		SET	
																			opening_qty = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							END,
																			purchase_qty  = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							END,
																			sold_date=@dates,
																			sold_bill_no=@billno,
																			sold_rate=@rate,
																			sold_qty= CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold='Sold',
																			prioritys       = @prioritysId
																	WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND pkid = @pkid
																	
																	SET @Balanceval = ABS(@Sold_Qty) - ABS(@TempSoldQty)
																END
															
														DELETE FROM #tempValExists WHERE id = @tempID AND pkid = @pkid
														SET @tablerowscount=(SELECT COUNT(*) FROM  #tempValExists )
														SET @RCOUNT = @RCOUNT - 1
													
													IF(@Balanceval  < 0)
														BEGIN
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1
															--SET @prioritysId  =(SELECT MAX(isnull(prioritys,0))+1 FROM #MainOutputtable_1) 

															IF(@str='Opening')
																BEGIN
																	SET @openingQty=ABS(@Balanceval) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	INSERT INTO #MainOutputtable_1(Dup_pkid,
																	ID,sr_no,Consultant_code,  Strike_Price, OptionType, MonthYear, Last_Date, Exp_Rate, Broker_Code, dp_code,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@tempID,@sr_no,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No,@ScriptId, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name)

																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  WHERE prioritys >=  @prioritysId 
																	AND ID <> @tempID
																END
															ELSE 
																BEGIN
																	SET @PurchaseQty = ABS(@Sold_Qty) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																		
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,sr_no,Consultant_code,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@ID,@sr_no,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name)
																	UPDATE #MainOutputtable_1 SET prioritys=@prioritysId  WHERE prioritys > @prioritysId AND ID <> @tempID

																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																			
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId    
																	WHERE prioritys >= @prioritysId AND ID <> @tempID

																END
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),1) FROM #MainOutputtable_1)) END)  
															IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
																set @Balanceval=0;
															BREAK;
														END
													ELSE IF(@Balanceval  > 0 AND @tablerowscount = 0)
														BEGIN
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1
															SET @prioritysId  = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1)

															INSERT INTO #MainOutputtable_1(Dup_pkid,ID,sr_no,Consultant_code,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
															VALUES(@Dup_pkid,@ID,@sr_no,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name)

															UPDATE #MainOutputtable_1 
															SET prioritys=@prioritysId+1  
															WHERE prioritys > @prioritysId AND ID<>@tempSaleID 

															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
														
															IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1 
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																	FROM Fn_split(@Pkid, ',') ) 
																END
														ENd
														ELSE IF(ISNULL(@Balanceval,0) =0)
																BEGIN
																	SET @Balanceval=0
																	BREAK;
																END
															SET @qty = @Balanceval
													END
													DROP TABLE #tempValExists
												END
											
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
													INSERT INTO #MainOutputtable_1(Dup_pkid,ID,sr_no,Consultant_code,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No,ScriptCode , Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
													VALUES(@Dup_pkid,@ID,@sr_no,@Consultant_code,@Strike_Price,@OptionType,@MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No, @ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name)
												END
											SET @purchase_Op_Date	=	''
											SET @purchase_Op_Rate	=	''
											SET @purchase_Op_Qty	=	''
											SET @purchase_Op_Bill	=	''
										END
								END
							 
							FETCH NEXT FROM purchaseANDSaledatacursor 
							INTO @ID,@sr_no,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Strike_Price,@OptionType,
								 @MonthYear,@Last_Date,@Exp_Rate,@Broker_Code,@dp_code,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name,@Consultant_code 
				
						END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
	     	END 

	  --	Select * from #mainoutputtable_1
		
				INSERT INTO #mainoutputtable_1_Final (OrderBy,id,sr_no,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No, prioritys,ScriptCode ,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss , closing_qty ,closing_rate ,closing_value ,
				short_term,
				long_term,
				speculation,
				gain_speculation,
				loss_speculation,
				consultant_name,nse_rate,bse_rate, sort,isintradaycol,Consultant_code )

				SELECT 
				ROW_NUMBER ( ) OVER (ORDER BY  
				Script_name,
				--dup_pkid, 
				case   WHEN  Dup_pkid is Null Then Pkid
					   WHEN  Dup_pkid is NOt Null then Dup_pkid 
				       ELSE  Dup_pkid end,
				prioritys,
				case when CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
				else CONVERT(DATE,purchase_date,103) END,prioritys DESC, sold_date DESC ) AS NameId,

				id,sr_no,Strike_Price,OptionType,MonthYear,Last_Date,Exp_Rate,Broker_Code,dp_code,Trans_No, prioritys,ScriptCode ,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,
				   Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) < 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				 closing_qty ,closing_rate ,closing_value ,
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365) --short term for purchase
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
						
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365) --short term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) = 0) 
							AND (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol ,Consultant_code
				FROM #mainoutputtable_1 
				order by NameId
		
		IF(@OUTPUT_Flag='Details')
			BEGIN
				IF(@ConsultantCode!='')
					BEGIN
						SELECT  ISNULL(opening_bill_no,' ') opening_bill_no ,id,prioritys,ScriptCode ,script_name 'Script Name',Holding_Type,
						CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',ISNULL(gain,0) 'Gain',ISNULL(loss,0) 'Loss',ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0) short_term,
						ISNULL(long_term,0) long_term,
						ISNULL(speculation,0) speculation,
						CASE WHEN isintradaycol=1 and gain!=0 THEN gain  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 and loss!=0  THEN loss  ELSE '' END loss_speculation,consultant_name,
						ISNULL(nse_rate,0) nse_rate,ISNULL(bse_rate,0) bse_rate,ISNULL(isintradaycol,0) isintradaycol,1 sort 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)
						ORDER BY  consultant_name,Holding_Type,script_name--,id
					END
				ELSE
					BEGIN
					
						UPDATE #mainoutputtable_1_Final SET prioritys=0
						DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
						UPDATE #mainoutputtable_1_Final
						SET prioritys  = @i , @i = @i + 1

						SELECT  isnull(opening_bill_no,' ') opening_bill_no , id,prioritys,ScriptCode ,script_name 'Script Name',Holding_Type,CONVERT(DATE, opening_date,103) 'Opening Date',
						ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',
						ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',
						ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,
						ISNULL(long_term,0)long_term,
						ISNULL(speculation,0)speculation,
				
						CASE WHEN ((isintradaycol=1) OR(isintradaycol=0)) AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN ((isintradaycol=1) OR(isintradaycol=0)) AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						consultant_name,nse_rate,bse_rate,isintradaycol,1 sort 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)
						--ORDER BY  script_name,id
					END
			END
		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
				SELECT  0 id ,  0 prioritys, '' opening_bill_no, '' ScriptCode , script_name 'Script Name', '' Holding_Type,'' AcType ,
				NULL 'Opening Date', SUM(ISNULL(opening_qty,0)) 'Opening Qty',  ISNULL((ISNULL(SUM(ISNULL(opening_amount,0)),0)  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate', SUM(ISNULL(opening_amount,0)) 'Opening Amount',
				NULL 'Purchase Date','' 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty',ISNULL((ISNULL(SUM(purchase_amount),0)  / SUM(NULLIF(purchase_qty,0))),0)  'Purchase Rate', SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
				NULL 'Sold Date', '' 'Sold BillNo', SUM(ISNULL(sold_qty,0)) 'Sold Qty', ISNULL((ISNULL(SUM(ISNULL(sold_amount,0)),0) / NULLIF (SUM(ISNULL(sold_qty,0)),0)),0)'Sold Rate', SUM(ISNULL(sold_amount,0)) 'Sold Amount',
				SUM(ISNULL(gain_loss ,0)) 'Gain/Loss', SUM(ISNULL(gain,0))  'Gain', SUM(ISNULL(loss,0))  'Loss',
				SUM(ISNULL(closing_qty,0))  'Closing Qty',  ISNULL((ISNULL(SUM(ISNULL(closing_value,0)),0) / NULLIF(SUM(ISNULL(closing_qty,0)),0)),0)   'Closing Rate', SUM(ISNULL(closing_value,0))  'Closing Value', SUM(ISNULL(short_term,0))  short_term, SUM(ISNULL(long_term,0))  long_term,
				SUM(ISNULL(speculation,0))speculation, SUM(ISNULL(gain_speculation,0))gain_speculation, SUM(ISNULL(loss_speculation,0))loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort 
				FROM
					(
						SELECT MAX(id+0)id ,MAX (prioritys + 0) prioritys, '' opening_bill_no, '' ScriptCode , script_name  ,'' Holding_Type,'' AcType ,
						'' 'Opening Date',SUM(opening_qty) 'Opening_Qty',sum(ISNULL(opening_rate,0)) opening_rate ,SUM(ISNULL(opening_amount,0)) 'Opening_Amount',
						'' 'Purchase Date','' purchase_bill_no,SUM(ISNULL(purchase_qty,0)) 'Purchase_Qty', SUM(ISNULL(purchase_rate,0)) purchase_rate,SUM(ISNULL(purchase_amount,0)) 'Purchase_Amount',
						'' 'Sold Date','' sold_bill_no ,SUM(ISNULL(sold_qty,0)) 'Sold_Qty', SUM(ISNULL(sold_rate,0))sold_rate  , SUM(ISNULL(sold_amount,0)) 'Sold_Amount',SUM(ISNULL(gain_loss,0)) 'Gain_Loss',SUM(ISNULL(gain,0)) 'Gain',SUM(ISNULL(loss,0)) 'Loss',
						SUM(ISNULL(closing_qty,0)) 'Closing_Qty',SUM(ISNULL(closing_rate,0)) 'Closing_Rate',SUM(ISNULL(closing_value,0)) 'Closing_Value',SUM(ISNULL(short_term,0)) short_term,SUM(ISNULL(long_term,0)) long_term,
						SUM(ISNULL(speculation,0)) speculation,SUM(ISNULL(gain_speculation,0)) gain_speculation,SUM(ISNULL(loss_speculation,0)) loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort 
						FROM #mainoutputtable_1_Final 
						GROUP BY script_name,Holding_Type,purchase_bill_no,sold_bill_no 
					)a
				GROUP BY  script_name  
				
				ORDER BY  Holding_Type,script_name,id
				
			END
		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN
				SELECT  prioritys ,Trans_No,id ,ScriptCode ,Broker_Code,dp_code,Consultant_code, script_name ,'Empty' Holding_Type, 
				flag_script_name,flag_Holding_Type,
				opening_date,ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),
				purchase_date,purchase_bill_no,ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount ,0),
				sold_date ,sold_bill_no ,ISNULL(sold_qty,0) ,ISNULL(sold_rate,0),ISNULL(sold_amount ,0),
				ISNULL(gain_loss,0) ,ISNULL(gain,0) ,ISNULL(loss,0),ISNULL(closing_qty,0) ,ISNULL(closing_rate,0) ,ISNULL(closing_value,0) ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,
				ISNULL(nse_rate,0),ISNULL(bse_rate,0),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,ISNULL(isintradaycol,0),Last_Date,ISNULL(Strike_Price,0),OptionType
				FROM #mainoutputtable_1_Final
			END
		ELSE IF(@OUTPUT_Flag='StoskTransfer_BrokerBillTrans')
			BEGIN
				SELECT id,sr_no,prioritys,ScriptCode,Strike_Price,OptionType as 'Option Type',MonthYear,Last_Date,''  Ac_type,  DP_Code, ISNULL(Broker_Code,'')Broker_Code,  Consultant_code,
				script_name 'Script Name','' Holding_Type, 
				CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount', 
				CONVERT(DATE,purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ROUND(ISNULL(purchase_qty,0),4) 'Purchase Qty',ROUND(ISNULL(purchase_rate,0),4) 'Purchase Rate',ROUND(ISNULL(purchase_amount,0),4) 'Purchase Amount',
				CONVERT(DATE,sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ROUND(ISNULL(sold_qty,0),4) 'Sold Qty',ROUND(ISNULL(sold_rate,0),4) 'Sold Rate',ROUND(ISNULL(sold_amount,0),4) 'Sold Amount',
				ROUND(ISNULL(gain_loss,0),4) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ROUND(ISNULL(gain_loss,0),4) ELSE 0 END  AS  'Loss',
				ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
				CASE
									WHEN ISNULL(closing_qty,0) < 0 THEN CONVERT(date,sold_date,101)
									WHEN ISNULL(opening_date,'') != '' THEN  CONVERT(date,opening_date,101)
									WHEN ISNULL(purchase_date,'') != '' THEN CONVERT(date,purchase_date,101)
								END  AS  'Closing Date',
				ISNULL(short_term,0) short_term,ISNULL(long_term,0) long_term,ISNULL(speculation,0) speculation,
				CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
				CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
				'' consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),ISNULL(isintradaycol,0),1 sort 
				FROM #mainoutputtable_1_Final
				WHERE ISNULL(closing_qty,0) <> 0
				ORDER BY Broker_Code
				
			END
		ELSE IF(@OUTPUT_Flag='StoskTransfer_BrokerBill')
			BEGIN
				SELECT 0 id,0 prioritys,'' Strike_Price,'' as 'Option Type','' MonthYear,'' Last_Date,'' ScriptCode,  '' Ac_type,''  DP_Code,  
				ISNULL(Broker_Code,'') Broker_Code,'' Consultant_code,
				'' 'Script Name','' Holding_Type, '' 'Opening Date',
				0 'Opening Qty',0 'Opening Rate',0 'Opening Amount', '' 'Purchase Date','' 'Purchase BillNo',
				0 'Purchase Qty',0 'Purchase Rate',0 'Purchase Amount',
				'' 'Sold Date','' 'Sold BillNo',0 'Sold Qty',
				0 'Sold Rate',0 'Sold Amount',0 'Gain/Loss',
				0 'Gain',0  'Loss',0 'Closing Qty',0 'Closing Rate',SUM(ISNULL(closing_value,0)) 'Closing Value',
				'' 'Closing Date',
				0 short_term,0 long_term,0 speculation,
				0 gain_speculation,
				0 loss_speculation,
				'' consultant_name,0 nse_rate,0 bse_rate,0 isintradaycol,1 sort 
				FROM #mainoutputtable_1_Final
				WHERE ISNULL(closing_qty,0) <> 0
				GROUP BY Broker_Code
				ORDER BY Broker_Code
			END
		ELSE IF(@OUTPUT_Flag='ClosingBalTransfer_Mst_Ac')
			BEGIN
				SELECT  MAX(prioritys+1) ,'' Trans_No,'' id ,'' Ac_type, '' Broker_Code,  '' Consultant_code ,
				'' ScriptCode,'' script_name ,'' Holding_Type,'' flag_script_name,'' flag_Holding_Type,'' opening_date,
				0 opening_qty , 0 opening_Rate,0 opening_amount,'' purchase_date ,'' purchase_bill_no,
				0 purchase_qty ,0 purchase_rate ,0 purchase_amount ,'' sold_date  ,'' sold_bill_no ,0 sold_qty ,
				0 sold_rate,0 sold_amount ,0 gain_loss ,0 gain ,0 loss,SUM(ISNULL(closing_qty,0)) closing_qty,0 closing_rate , 
				SUM(closing_value) closing_value,
				0 short_term,0 long_term,0 speculation,0 gain_speculation,0 loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,
				0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort , @Investmenttype as Investmenttype,isintradaycol--,holding_type + space(5) + '1'
				FROM #mainoutputtable_1_Final
				GROUP BY isintradaycol
			END
		ELSE IF(@output_Flag='ClosingStocks')
			BEGIN
		--	Select * from #mainoutputtable_1_Final
				 SELECT id,
						sr_no,
						Trans_No ,
						script_name,
						ScriptCode,
						Holding_Type,
						CASE
							WHEN ISNULL(closing_qty,0) < 0		THEN sold_bill_no
							WHEN ISNULL(opening_date,'') != ''   OR  ISNULL(purchase_date,'') != '' THEN  purchase_bill_no
							ELSE ''
						END  AS  'bill_no',
						CASE
							WHEN ISNULL(closing_qty,0) < 0		THEN CONVERT(DATE,sold_date,101)
							WHEN ISNULL(opening_date,'') != ''	THEN  CONVERT(DATE,opening_date,101)
							WHEN ISNULL(purchase_date,'') != '' THEN CONVERT(DATE,purchase_date,101)
						END  AS  'trans_dt',
						Strike_Price,
						OptionType,
						MonthYear,
						Last_Date,
						Exp_Rate,
						Broker_Code,
						DP_Code,
						ABS(ISNULL(closing_qty,0)) 'Qty',
						ISNULL(closing_rate,0) 'rate',
						ISNULL(closing_value,0) 'amount',
						isintradaycol,
						consultant_name,
						ISNULL(Consultant_code,'') Consultant_code,
						CASE
							WHEN ISNULL(closing_qty,0)    < 0		THEN 'Sold'
							WHEN ISNULL(opening_date,'')  != ''		THEN 'Opening'
							WHEN ISNULL(purchase_date,'') != ''		THEN  'Bought'
							ELSE ''
						END  AS  'Type'
				from #mainoutputtable_1_Final 
				WHERE ISNULL(closing_qty,0) <> 0
				ORDER BY Trans_No
			
			END
		ELSE IF(@output_Flag='WholeMainTableData')
			BEGIN
				 SELECT pkid ,Dup_pkid , Trans_No ,'' as 'Ac_type'  ,id  ,script_name   ,holding_type  ,
				 opening_bill_no  ,opening_date  ,ISNULL(opening_qty ,0) opening_qty ,ISNULL(opening_rate ,0) opening_rate ,ISNULL(opening_amount ,0)opening_amount , 
				 purchase_date ,purchase_bill_no ,ISNULL(purchase_qty,0) purchase_qty,ISNULL(purchase_rate,0) purchase_rate,ISNULL(purchase_amount,0) purchase_amount,
				 sold_date ,sold_bill_no ,ISNULL(sold_qty,0) sold_qty,ISNULL(sold_rate,0) sold_rate,ISNULL(sold_amount,0) sold_amount, 
				 ISNULL(gain_loss,0) gain_loss,ISNULL(gain,0) gain,ISNULL(loss,0) loss,ISNULL(closing_qty,0) closing_qty, ISNULL(closing_rate,0) closing_rate,ISNULL(closing_value,0) closing_value,
				 ISNULL(short_term,0) short_term,ISNULL(long_term,0) long_term, ISNULL(speculation,0) speculation, ISNULL(gain_speculation,0) gain_speculation,ISNULL(loss_speculation,0) loss_speculation,ISNULL(isintradaycol,0) isintradaycol,ScriptCode 
			from #mainoutputtable_1_Final 
			END

		DROP TABLE #mainoutputtable_1  
		DROP TABLE #alldata 
	 
  END  































GO
/****** Object:  StoredProcedure [dbo].[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary] AS' 
END
GO



--Execute  proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary    0,1,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-02-01 03:50:37:50','','','','', '0' ,'0',0,0,0
--Execute  proc_Stockholdingposition_Equity_Summary    0,0,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0',1,1,1
ALTER PROCEDURE [dbo].[proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency_Summary]  --''
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate datetime,@Todate datetime, 
@ScriptCode VARCHAR(MAX),@ConsultantCode  VARCHAR(MAX),@BSE_NSE_Code VARCHAR(MAX),@Is_BFCF VARCHAR(MAX),@IsIntraDay VARCHAR(MAX),@short_Long_Term INT,
@RecordOnlyhavingClosingbalanceZero AS BIT,@WithActualAvgRate AS BIT, @DateWiseClosinStock AS BIT,@IsWithTax bit = 0,
@Script_Name varchar(max) = '')
AS
BEGIN
SET NOCOUNT ON;
		CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
			prioritys INT,
			Trans_No VARCHAR(50),
			id INT,
			ScriptCode VARCHAR(50), 
			Broker_Code VARCHAR(100),
			dematcode VARCHAR(100),
			Consultant_code  VARCHAR(100),
			script_name  VARCHAR(500),
			holding_type VARCHAR(200),
			flag_script_name  VARCHAR(500),
			flag_holding_type VARCHAR(200),
			opening_date DATETIME,opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
			purchase_date DATETIME,purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
			sold_date DATETIME,sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
			gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
			closing_qty FLOAT DEFAULT 0, 
			closing_rate FLOAT DEFAULT 0,
			closing_value FLOAT DEFAULT 0,
			short_term FLOAT DEFAULT 0,
			long_term FLOAT DEFAULT 0, 
			speculation FLOAT DEFAULT 0, 
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			consultant_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			Other_amt FLOAT DEFAULT 0,
			ServTax_Amt FLOAT DEFAULT 0,
			Stt_amt FLOAT DEFAULT 0,
			sort   VARCHAR(5),
			isintradaycol  INT,
			Last_Date dateTime,
			Strike_Price float,
			OptionType varchar(max)
        ) 
		
		
		IF(@ConsultantCode = '0')	
			BEGIN
						
					SELECT DISTINCT p.member_code,p.year_code,
						STUFF((	SELECT distinct ',' + p1.Consultant_Code
								FROM Mst_Consultant p1
								FOR XML PATH(''), TYPE
								).value('.', 'NVARCHAR(MAX)')
						,1,1,'') ConsultantCode
					into #temoConsultant
					FROM Mst_Consultant p

					SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant WHERE member_code = @memcode AND year_code = @yearcode)
					DROP table #temoConsultant
			END

		INSERT INTO #mainoutputtable_1_Final_Summary
		EXEC proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency   @status,@Investmenttype,@Ac_Type,@memcode,@yearcode,@Fromdate,@Todate,@ScriptCode,@ConsultantCode,@BSE_NSE_Code,@Is_BFCF,@IsIntraDay,@short_Long_Term,'ALLData',@IsWithTax,@Script_Name

		SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
		T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
		T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
		T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
		T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
		T1.consultant_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,
		Max(Isnull(Dr.Bse_FO_Rate,0)) AS 'bse_rate', /**/
		MAX(Isnull(Dr.Nse_FO_Rate,0)) AS 'nse_rate' /**/
		INTO #alldata_Summary 
		FROM #mainoutputtable_1_Final_Summary  T1
		LEFT JOIN BrokerBill T2  ON T1.Trans_No=T2.Trans_no
		LEFT JOIN DailyRate  DR  
		ON 
			DR.InvestmentType != 0 and Dr.InvestmentType != 2 AND
			DR.Script_Code = T1.ScriptCode and  Convert(varchar,dr.Trans_Dt,101) =  Convert(varchar,@Todate,101) AND 
			Convert(varchar,DR.Expir_Date ,101) =  Convert(varchar,T1.Last_Date,101) AND
			ISNULL(Substring(RTRIM(LTRIM(T1.OptionType)),0,3),'') = ISNULL( DR.OptionType,'') AND
			ISNULL(DR.Strike_Price,0) = ISNULL(T1.Strike_Price,'')
	
		
		  

		TRUNCATE TABLE #mainoutputtable_1_Final_Summary
		INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt) 

		SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,
		Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 
		
		FROM #alldata_Summary  

		GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 


		IF(@RecordOnlyhavingClosingbalanceZero = 0)
			BEGIn
				IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE 
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END  AS  'Closing Date',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0)>0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
											0 END 
											END AS 'Avg. Rate',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
											0 END 
											END AS 'Value After Profit/Loss',
										SUM(ISNULL(Other_amt,0))Other_amt, '' consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY script_name,holding_type,bse_rate,nse_rate,
										  CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END 
										HAVING SUM(closing_qty) != 0
							END
					END
				ELSE IF(@WithActualAvgRate = 1 OR @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								IF(@WithActualAvgRate=0 AND @DateWiseClosinStock=1)
									BEGIN
										SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END  AS  'Closing Date',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',
										SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
										SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
										SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY holding_type,script_name,bse_rate,nse_rate,
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END, consultant_name
										HAVING SUM(closing_qty) != 0
									END
								ELSE IF(@WithActualAvgRate=1 AND @DateWiseClosinStock=0)
									BEGIN
										SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
										'' 'Closing Date',
										bse_rate  AS  'BSERATE',
										bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
										CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
										nse_rate AS  'NSERATE',
										nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
										CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
										SUM(gain_loss) AS 'Profit/Loss',
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  AND NULLIF(SUM(closing_qty),0) > 0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0 AND NULLIF(SUM(closing_qty),0) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
											0 END 
											END AS 'Avg. Rate',

										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) < 0  AND NULLIF(SUM(closing_qty),0) > 0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
											ELSE
										CASE WHEN 
												SUM(ISNULL(gain_loss,0)) >= 0  AND NULLIF(SUM(closing_qty),0) > 0 THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
											0 END 
											END AS 'Value After Profit/Loss',
										SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name
										FROM #mainoutputtable_1_Final_Summary
										GROUP BY holding_type,script_name,bse_rate,nse_rate,
										 bse_rate,nse_rate,consultant_name
										HAVING SUM(closing_qty) != 0
									END
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN
								SELECT   MAX(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(NULLIF(closing_value,0)),2) AS 'Closing Value',SUM(NULLIF(closing_qty,0)) AS 'Closing Qty',
								NULLIF(ROUND( ABS(SUM(NULLIF(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date','' 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(ISNULL(closing_qty,0))  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE ISNULL(bse_rate,0) * ISNULL(SUM(NULLIF(closing_qty,0)),0) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(ISNULL(closing_qty,0)) AS  'NSE_Valuation',
								CASE WHEN ISNULL(nse_rate,0) = 0 THEN 0 ELSE  NULLIF(nse_rate,0) * SUM(NULLIF(closing_qty,0)) - SUM(NULLIF(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(NULLIF(gain_loss,0)) AS 'Profit/Loss',
								SUM(NULLIF(closing_value,0)) - SUM(NULLIF(gain_loss,0)) AS 'Value After Profit/Loss',
								SUM(NULLIF(closing_value,0)) - SUM(NULLIF(gain_loss,0)) / SUM(NULLIF(closing_qty,0)) as 'Avg. Rate',
								SUM(NULLIF(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',
								SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0)) / nullif(SUM(closing_qty),0)),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					END
			END
		ELSE IF(@RecordOnlyhavingClosingbalanceZero = 1)
			BEGIN
				IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE 
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
										CASE
											WHEN closing_qty < 0 THEN sold_date
											WHEN ISNULL(opening_date,'') != '' THEN opening_date
											WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
										END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0)>0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY script_name,holding_type,bse_rate,nse_rate,
									CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
							END 
										--HAVING SUM(closing_qty) != 0
						END
					END
				ELSE IF (@WithActualAvgRate = 1 OR @DateWiseClosinStock = 1)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  MAX(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE if(@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1)
								BEGIN
									IF(@ConsultantCode<>'')
										BEGIN
											SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
											bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
											bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
											CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
											nse_rate AS  'NSERATE',
											nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
											CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
											SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
											SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) AS 'Value After Profit/Loss',
											SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) / NULLIF(SUM(ISNULL(closing_qty,0)),0) AS 'Avg. Rate',
											SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
											FROM #mainoutputtable_1_Final_Summary
											GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
											HAVING SUM(closing_qty) != 0
											ORDER BY consultant_name

										END
									ELSE
										BEGIN
											SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
											CASE
												WHEN closing_qty < 0 THEN sold_date
												WHEN ISNULL(opening_date,'') != '' THEN opening_date
												WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
											END  AS  'Closing Date',
											bse_rate  AS  'BSERATE',
											bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
											CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
											nse_rate AS  'NSERATE',
											nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
											CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
											SUM(gain_loss) AS 'Profit/Loss',
											SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
											SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate'
											FROM #mainoutputtable_1_Final_Summary
											GROUP BY holding_type,script_name,bse_rate,nse_rate ,
											CASE
												WHEN closing_qty < 0 THEN sold_date
												WHEN ISNULL(opening_date,'') != '' THEN opening_date
												WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
											END
											HAVING SUM(closing_qty) = 0
									END
								END
						ELSE if(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0)
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0 and NULLIF(SUM(closing_qty),0)>0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) >= 0  and NULLIF(SUM(closing_qty),0)>0 THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY script_name,holding_type,bse_rate,nse_rate
						 END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) AS 'Value After Profit/Loss',
								SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) / NULLIF(SUM(ISNULL(closing_qty,0)),0) AS 'Avg. Rate',
								SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name

							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / nullif(SUM(closing_qty),0) AS 'Avg. Rate',
								0 Other_amt,'' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) = 0
							END
					END
			END
			DROP TABLE #alldata_Summary
END


































GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_FamilyWise_Equity]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_FamilyWise_Equity]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_Equity] AS' 
END
GO



  -- exec[proc_StockholdingPosition_FamilyWise_Equity]  0,0,'0','Y0001','1120172018','2015-02-01 12:00:00:00','2018-03-31 03:50:37:50','','','','', '0' ,'0','ClosingStocks',''
  -- exec[proc_StockholdingPosition_FamilyWise_Equity]  0,0,'0','S0001','1120172018','2017-04-01 12:00:00:00','2018-03-31 03:50:37:50','Y0011','','','', '0' ,'0','Details',''
ALTER PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_Equity] --
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(Max),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(MAX),@ConsultantCode  VARCHAR(MAX),@BSE_NSE_Code VARCHAR(MAX),@Is_BFCF VARCHAR(MAX),@IsIntraDay VARCHAR(MAX),@short_Long_Term INT,
@OUTPUT_Flag VARCHAR(MAX),@FamilyCode VARCHAR(MAX),@IsFromMonthWise bit = 0)
AS 
  BEGIN 
  SET NOCOUNT ON;
		DECLARE @StartYearDate varchar(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101)

		CREATE TABLE #mainoutputtable_1
        ( 
			pkid INT identity(1,1),
			Dup_pkid  INT,
			Family_Name VARCHAR(Max),
			Member_Name VARCHAR(Max),
			Family_Code VARCHAR(Max),
			Member_Code VARCHAR(Max),
			Trans_No VARCHAR(20),
			id INT,
			prioritys INT,
			Trans_Type  VARCHAR(50),
		    Split_Type VARCHAR(50), 
			Flag_Type VARCHAR(50),
			Flag_Type_Sold VARCHAR(50),
			flag_script_name  VARCHAR(Max),
			flag_holding_type VARCHAR(Max), 
			script_name  VARCHAR(Max),
			holding_type VARCHAR(Max), 
			opening_bill_no VARCHAR(100),		    
			opening_date DATETIME,
			opening_qty  FLOAT DEFAULT 0,
			opening_rate  FLOAT DEFAULT 0,
			opening_amount AS( [opening_qty] * [opening_rate] ), 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount AS( purchase_qty * purchase_rate ), 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount AS ( sold_qty * sold_rate ), 
			gain_loss float,
			closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 
			closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
		   closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
		   short_term FLOAT DEFAULT 0,
		   long_term  FLOAT DEFAULT 0,
           speculation  FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(Max), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(100) ,
		   ScriptCode  VARCHAR(Max),
		   Broker_Code  VARCHAR(Max)
        )  

		CREATE TABLE #mainoutputtable_1_Final
        ( 
		   OrderBy varchar(100),
		   Dup_pkid  INT,
           Family_Name VARCHAR(Max),
		   Member_Name VARCHAR(Max),
		   Family_Code VARCHAR(Max),
		   Member_Code VARCHAR(Max),
		   Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT,
		   Split_Type VARCHAR(50),
		   Flag_Type VARCHAR(50),
		   Flag_Type_Sold VARCHAR(50),
		   flag_script_name  VARCHAR(Max),
		   flag_holding_type VARCHAR(Max), 
		   script_name  VARCHAR(Max),
		   holding_type VARCHAR(Max), 
		   opening_bill_no VARCHAR(100),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
		   gain_loss FLOAT DEFAULT 0,
		   gain AS CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss AS CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, gain_speculation FLOAT DEFAULT 0,loss_speculation FLOAT DEFAULT 0,consultant_name VARCHAR(Max), 
           nse_rate FLOAT DEFAULT 0,bse_rate FLOAT DEFAULT 0,dayscount FLOAT DEFAULT 0,isintradaycol INT,[type] VARCHAR(100),sort   VARCHAR(5),ScriptCode  VARCHAR(Max),
		   Broker_Code  VARCHAR(MAX)
        ) 

		CREATE TABLE #Members
		(
			Member_Code varchar(MAX)
		)
			
		CREATE TABLE #Family
		(
			Family_Code varchar(MAX)
		)

		DECLARE @tmp VARCHAR(MAX)
				
		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty FLOAT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT  ,  @Broker_Code  VARCHAR(MAX)
		DECLARE @tablerowscount INT

      IF(@status = 0) 
			BEGIN
				DECLARE @holding_type VARCHAR(100), @scriptcd VARCHAR(Max), @billno VARCHAR(100), @scriptname VARCHAR(Max),
				@openingDate DATE , @openingRate FLOAT, @openingQty FLOAT, @openingAmount FLOAT,
				@purchaseDate DATE, @PurchaseBillNo  VARCHAR(50), @purchaseRate FLOAT, @purchaseQty FLOAT,@purchaseAmount FLOAT,
				@soldDate DATE, @soldBillNo  VARCHAR(50), @soldRate FLOAT, @soldQty FLOAT, @soldAmount FLOAT,
				@purchaseScriptId VARCHAR(Max), @Consultant_Name  VARCHAR(Max), 
				@SoldScriptId VARCHAR(Max), @pendingSoldDate VARCHAR(50), @pendingSoldBillNo VARCHAR(10), @pendingSoldQty FLOAT,
				@pendingSoldRate FLOAT, @PurchaseIntraFlag VARCHAR(100), @SaleIntraFlag VARCHAR(10) 
				DECLARE @TransTypes VARCHAR(200), @Trans_No VARCHAR(20), @ScriptId  VARCHAR(Max), @Fam_Code VARCHAR(MAx), @Mem_Code VARCHAR(Max)
				DECLARE @salecount INT=0, @Boughtcount INT=0, @Flag_Type VARCHAR(20)
				DECLARE @isIntradayCol INT ,@Family_Name VARCHAR(Max),@Member_Name VARCHAR(Max) 
				
				DECLARE @IDs INT=0
				DECLARE @Flag_Types VARCHAR(10), @Dup_pkid int, @Pkid VARCHAR(MAX), @idcount int  

				---- For Getting SCriptCodes
				CREATE TABLE #SCriptCodes
				(
					ScriptCode varchar(MAX)
				)

				IF(@ScriptCode != '')
					INSERT INTO #SCriptCodes SELECT value FROM Fn_split(@ScriptCode, ',') 
				ELSE 
					INSERT INTO #SCriptCodes select Script_Code from mst_script 
				---- Getting SCriptCodes END
				
				---- For Getting Consultant Code
				CREATE TABLE #ConsultantCodes
				(
					ConsultantCodes varchar(MAX)
				)
				 
				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes select Consultant_Code from Mst_Consultant						
				
				IF(@memcode = '' AND @familycode != '')
					BEGIN
						INSERT INTO #Members
						SELECT Member_Code 
						FROM Mst_Member WHERE Family_Code IN (SELECT Value FROM membercodestable(@familycode,','))
						SET @tmp = ''
						SELECT @tmp = @tmp + Member_Code + ',' FROM #Members
						SET @memcode = 	IsNULL((select SUBSTRING(@tmp, 0, LEN(@tmp))),'')
					END
				
				ELSE IF(@memcode != '' AND @familycode = '')
					BEGIN
						INSERT INTO #Family
						SELECT Family_Code 
						FROM Mst_Member WHERE Member_Code IN (SELECT Value FROM membercodestable(@memcode,','))
						SET @tmp = ''
						SELECT @tmp = @tmp + Family_Code + ',' FROM #Family
						SET @familycode = 	IsNULL((SELECT SUBSTRING(@tmp, 0, LEN(@tmp))),'')
					END
			 
				SELECT  ROW_NUMBER ( ) OVER (ORDER BY MF.Family_Code,t.Member_Code, t.script_code,t.Ac_Type,t.trans_dt ) AS NameId,
						t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,t.TransType,t.Ac_Type,t.Script_Code,t.Last_Date,t.Qty,t.Rate,
						t.Member_code,t.YearCode,t.Consultant_code,t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,t.Exp_Rate,t.FrmNm,t.ID,
						Ms.bse_code,Ms.nse_code,Ms.script_name,UPPER(ma.ac_name) AS 'Holding Type',
						CASE	WHEN TransType	= 'Sold' THEN 'Sold' 
						        WHEN (((t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101))AND t.TransType='Bought') THEN 'Opening'
								WHEN TransType  = 'Bought' AND t.Bill_no = 'Bonus' THEN 'Bonus' 
								WHEN TransType  = 'Bought' AND t.Bill_no ='Rights'THEN 'Rights' 
								WHEN TransType  = 'Bought' AND  t.Bill_no ='Split' THEN 'Split' 
								WHEN TransType  = 'Bought' AND  t.Bill_no ='Transfer' THEN 'Transfer' 								
								WHEN TransType  = 'Bought' AND Frmnm = 'IPO' THEN 'IPO'  
								WHEN t.TransType ='Bought' AND t.Bill_no != 'Opening' THEN 'Bought' 
						END AS 'Flag_Type',
						cm.Consultant_Name,mm.Member_Name,MF.Family_Name,MF.Family_Code,bb.Broker_Code --,t.isstock --,mm.Member_Code
						INTO #alldata 
				FROM brokerbill_trans t 
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN mst_account ma ON t.ac_type = ma.ac_code AND ma.member_code =t .member_code
				LEFT JOIN  Mst_Consultant  cm ON t.Consultant_code = cm.Consultant_code  
				LEFT JOIN Mst_Member MM ON mm.Member_Code=t.Member_code
				LEFT JOIN Mst_Family MF ON MF.Family_Code =MM.Family_Code
				LEFT JOIN brokerbill bb on bb.trans_no = t.Trans_No 
				WHERE  ISNULL(t.isfnobill,0) = @Investmenttype 
				AND t.trans_dt <= CONVERT(DATETIME,@Todate,101) 
				AND t.member_code IN (SELECT value FROM Fn_split(@memcode, ',') )
				AND t.yearcode = @yearcode  
				AND t.Ac_Type =(CASE WHEN  @Ac_Type='0' THEN t.Ac_Type  ELSE  @Ac_Type END)
				AND t.script_code IN (SELECT * FROM #SCriptCodes)
				AND	t.Consultant_code IN (SELECT * FROM #ConsultantCodes)
				AND	t.Member_Code IN (SELECT value FROM Fn_split(@memcode, ',') )
				AND	MF.Family_Code IN (SELECT value FROM Fn_split(@FamilyCode, ',') )
				AND isnull(t.isIntraDay,0) =(CASE WHEN @IsIntraDay=0 THEN  isnull(isIntraDay,0) ELSE @IsIntraDay END) 
				 AND t.MergedEntry =0  AND ISNULL( t.Ref_SrNo,0) != 1
				AND (IsSLBS=0 OR IsSLBS IS NUll) 
				GROUP BY t.Trans_Dt,t.Trans_No,t.Sr_No,t.Bill_no,t.TransType,t.Ac_Type,t.Script_Code,script_name,MF.Family_Code,t.Member_Code, BB.Broker_Code,t.MonthYear,t.Last_Date,t.LotSize,t.Qty,t.LotQty,t.Disp_qty,
				t.Bal_qty,t.G_Rate,t.Brok_Amt,ServTax_Amount,Rate,t.Amount,t.Stt_Amount,t.YearCode,t.Consultant_code,
				t.EntrySource,t.Ref_TransNo,t.Ref_SrNo,t.MergedEntry,t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,t.Brok_PerUnit,t.lockedbymerger,
				t.frac_Qty,t.Org_Trans_No,t.Org_SrNo,t.isDeleteMerger,t.isstock,t.ScripwiseExpense,t.isClient_code,t.isClient_Brokrage,t.c_Qty,t.C_Gross_Rate,
				t.C_Net_Rate,t.C_Amount,t.C_STT,t.C_STax,t.C_MisChg,t.TransactionChg,t.C_StampDuty,t.Exp_Rate,t.PerExp_Unit,t.FrmNm,t.ID,bse_code,nse_code,ma.AC_Name,cm.Consultant_Name,mm.Member_Name,MF.Family_Name--,t.isstock
				ORDER  BY NameId

				--Select * from #alldata 
		
				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT id,Trans_No,Broker_Code,script_name,Script_Code,Family_Name,Member_Name,Family_Code, Member_Code,[holding type],bill_no,CONVERT(DATETIME,trans_dt,103),qty,rate,ISNULL(qty, 0) * ISNULL(rate, 0),ISNULL(isintraday, 0),consultant_name   
				FROM #alldata 
				WHERE ((TransType != 'Sold' AND #alldata.bill_no IN('Opening')) OR  CONVERT(date,trans_dt,101)  < CONVERT(date ,@StartYearDate,101)AND #alldata.TransType='Bought')
				OPEN alldatacursor 
			 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No,@Broker_Code, @scriptname,@ScriptId ,@Family_Name,@Member_Name ,@Fam_Code, @Mem_Code,  @holding_type, @billno, @dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
						-- Insert All Openings
							IF(@Investmenttype=2)
								SET @holding_type='Mutual Fund'

							SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId and Member_Name=@Member_Name and Family_Name=@Family_Name)  -- AND ID = @ID)
							SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
							SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
							SET @Dup_pkid = ISNULL(@Dup_pkid,0)
							SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
							SET @Dup_pkid = @Dup_pkid + 1
 
							INSERT INTO #mainoutputtable_1   (Dup_pkid, id,Broker_Code,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code,   Trans_No,  Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,consultant_name,Trans_Type) 
							SELECT @Dup_pkid,@ID,@Broker_Code,@ScriptId, @Family_Name,@Member_Name,@Fam_Code,@Mem_Code,  @Trans_No, 'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Consultant_Name,'Opening'

							
							SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
								IF(@idcount>0)
								  BEGIN	
										 UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
								  END

			 			FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No,@Broker_Code, @scriptname,@ScriptId ,@Family_Name,@Member_Name ,@Fam_Code, @Mem_Code, @holding_type, @billno,      @dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name
			 	    END 

				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
				SELECT id, Broker_Code,Script_Code,Family_Code,Family_Name,Member_Code,Member_Name,  Bill_no,Flag_Type,TransType,script_name,[holding type],Trans_No,CONVERT(DATETIME, trans_dt,103), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name
				FROM #alldata WHERE  
				(TransType in('Bought','Sold')  OR CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Broker_Code,@ScriptId ,@Fam_Code,@Family_Name,@Mem_Code,@Member_Name, @billno,@Flag_Type , @TransType, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
				
				WHILE (@@FETCH_STATUS = 0) 
						BEGIN
					
							if(@Investmenttype=2)
								set @holding_type='Mutual Fund'

							DECLARE @IsOpening INT =0
							DECLARE @prioritysId INT=0
							DECLARE @str VARCHAR(MAX)=''	

							DECLARE @purchase_Op_Qty FLOAT =0
							DECLARE @purchase_Op_Bill VARCHAR(20) = ''
							DECLARE @purchase_Op_Date VARCHAR(20) = ''
							DECLARE @purchase_Op_Rate FLOAT=0
							DECLARE	@PurQTY FLOAT=0
							DECLARE	@BalPurQTY FLOAT=0

							DECLARE @BalSoldQTY FLOAT=0
							DECLARE @Balpurchase_Op_Qty FLOAT=0
							DECLARE @BalOpeningQTY FLOAT=0
							DECLARE	@Sold_Qty FLOAT=0
							DECLARE @tempID int = 0
							
							IF(@isIntradayCol=0)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN

											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, Holding_type,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,* 
													INTO #tempSoldValExists 
													FROM
													#MainOutputtable_1 
													WHERE script_name=@scriptname 
													AND holding_type=@holding_type  
													AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
													AND Family_Name=@Family_Name 
													AND Member_Name=@Member_Name
													AND ISNULL(sold_qty,0)!=0 
													AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold = ('Sold')  
													AND Flag_Type  ='Sold'  
													AND isintradaycol=0
													ORDER BY NameId

											IF ((Select Count(*) FROM #tempSoldValExists) > 0 )
												BEGIN
													
													DECLARE @R_Sold_COUNT FLOAT=(SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty FLOAT 
													
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists  ORDER BY Dup_pkid,NameId)
															SET @str = @TransType

															
															SELECT TOP 1	@Sold_Qty		= sold_qty,
																			@soldDate		= sold_date,
																			@soldRate		= sold_Rate,
																			@soldBillNo		= sold_bill_no,
																			@Pkid			= Pkid
																
															FROM #tempSoldValExists
															WHERE id  = @tempSaleID 
															SET @purchase_Op_Qty = @qty

															
															IF(@TransType='Opening')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	opening_date	= @dates,
																		opening_rate	= @rate,
																		opening_qty		= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type		= 'Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	purchase_date		= @dates,
																		purchase_bill_no	= @billno,
																		purchase_rate		= @rate,
																		purchase_qty		= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type			='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(purchase_qty,0)=0 AND pkid = @pkid
																END
															

															IF(@Sold_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET sold_qty	=	@purchase_Op_Qty 
																	WHERE Flag_Type_Sold='Sold' AND   id = @tempSaleID  AND Pkid=@Pkid
																END

															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND Pkid=@Pkid
															SET @tablerowscount=(  SELECT COUNT(*) FROM  #tempSoldValExists )
															DECLARE @Balancedval   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)
															
															IF(@Balancedval  < 0)
																BEGIN
																--	SET @Pkid		  = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId and holding_type=@holding_type and Member_Name=@Member_Name and Family_Name=@Family_Name)
																	SET @Dup_pkid	  = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid	  = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid	  = ISNULL(@Dup_pkid,0)
																	SET @idcount	  = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid	  = @Dup_pkid + 1
																	SET @soldQty	  = ABS(@Balancedval) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1) 
																	SET @prioritysId  = ISNULL(@prioritysId,0) + 1

																	INSERT INTO #MainOutputtable_1(Dup_pkid, Broker_Code,ID,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code, Trans_No, Flag_Type,Flag_Type_Sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name,Trans_Type)
																	VALUES(@Dup_pkid,@Broker_Code, @tempSaleID , @ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name,'sold')
																	
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID <> @tempSaleID 

																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																		IF(@idcount>0)
																		  BEGIN	
																				UPDATE #MainOutputtable_1 
																				SET Dup_pkid = Dup_pkid + 1 
																				WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		  END
																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId  and holding_type=@holding_type and Member_Name=@Member_Name and Family_Name=@Family_Name)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	IF(@TransType='Opening')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid ,Broker_Code,ID,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name,Trans_Type)
																			VALUES(@Dup_pkid, @Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																		END
																	ELSE if(@TransType='Bought')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,Broker_Code, ID,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																			VALUES(@Dup_pkid, @Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																		END
															
																		SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																		IF(@idcount>0)
																			BEGIN	
																				UPDATE #MainOutputtable_1 
																				SET Dup_pkid = Dup_pkid + 1
																				WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																			END
																		END
																	ELSE IF(@Balancedval=0)
																		BEGIN
																			break;
																		ENd	
																	SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
																	SET @qty = @Balancedval
														END
												

													
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
												 
													INSERT INTO #mainoutputtable_1 (id,Broker_Code,ScriptCode,Dup_pkId, Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name,Trans_Type) 
													VALUES ( @ID, @Broker_Code,@ScriptId,@Dup_pkid,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name,@Flag_Type) 
												END
												DROP TABLE #tempSoldValExists
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */

											SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, Holding_type,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,* 
													INTO #tempValExists 
													FROM #MainOutputtable_1 
													WHERE holding_type=@holding_type 
													AND script_name=@scriptname 
													AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split') 												
													AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
													AND ISNULL(sold_qty,0)=0  
													AND isintradaycol=0 
													AND Family_Name=@Family_Name 
													AND Member_Name=@Member_Name
													order by NameId

											IF ((Select count(*) From #tempValExists) > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty FLOAT 
													
													WHILE(@RCOUNT > 0)
														BEGIN 
															SET @Sold_Qty= @qty
															SET @tempID = (Select top(1) id from #tempValExists  ORDER BY Dup_pkid,NameId)
															SET @str = (Select top(1) Flag_Type From #tempValExists Where id  = @tempID)
														
															IF(@str='Opening')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= opening_qty,
																					@openingDate	= opening_date,
																					@openingrate	= opening_rate,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID

																END
															ELSE IF(@str='Bought')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= purchase_qty,
																					@PurchaseDate	= purchase_date,
																					@Purchaserate	= purchase_rate,
																					@PurchaseBillNo = purchase_bill_no,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID

																END
															    
															IF(@Sold_Qty > 0)
																BEGIN
																	UPDATE #MainOutputtable_1  
																		SET	
																			opening_qty = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							END,
																			purchase_qty  = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							END,
																			sold_date	  = @dates,
																			sold_bill_no  = @billno,
																			sold_rate     = @rate,
																			sold_qty      = CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold='Sold'
																	WHERE  id = @tempID and ISNULL(sold_qty,0)= 0 AND Pkid = @Pkid
																	SET @Balanceval = ABS(@Sold_Qty) - ABS(@TempSoldQty)
																END
															
														DELETE FROM #tempValExists WHERE id = @tempID AND Pkid=@Pkid
														SET @tablerowscount = (SELECT COUNT(*) FROM  #tempValExists )
														SET @RCOUNT = @RCOUNT - 1
														
														 
													
													IF(@Balanceval  < 0)
														BEGIN
															--SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId and holding_type=@holding_type and Member_Name=@Member_Name and Family_Name=@Family_Name)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1
															IF(@str='Opening')
																BEGIN
																	SET @openingQty=ABS(@Balanceval) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1

																	INSERT INTO #MainOutputtable_1(Dup_pkid,Broker_Code, ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@Dup_pkid,@Broker_Code,@tempID,@ScriptId, @Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name,@Flag_Type)

																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys >= @prioritysId AND ID <> @tempID
																END
															ELSE 
																BEGIN
																	SET @PurchaseQty=ABS(@Sold_Qty) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	INSERT INTO #MainOutputtable_1(Dup_pkid,Broker_Code,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@Dup_pkid,@Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	
																	SET @prioritysId = ISNULL(@prioritysId,0)+1

																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId  
																	WHERE prioritys > @prioritysId AND ID<>@tempID
																END
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																IF(@idcount>0)
																	BEGIN	
																		UPDATE #MainOutputtable_1 
																		SET Dup_pkid = Dup_pkid + 1 
																		WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																	END
																SET @Balanceval=0;
																break;
														END
													ELSE IF(@Balanceval  > 0 AND @tablerowscount = 0)
														BEGIN
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															SET @prioritysId  =(SELECT MAX(ISNULL(prioritys,0)+1) FROM #MainOutputtable_1)

															INSERT INTO #MainOutputtable_1(Dup_pkid,Broker_Code,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
															VALUES(@Dup_pkid,@Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)

															UPDATE #MainOutputtable_1 
															SET		prioritys	=	@prioritysId+1  
															WHERE	prioritys > @prioritysId AND ID<>@tempSaleID 
															
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
															IF(@idcount>0)
																BEGIN	
																	UPDATE #MainOutputtable_1 
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
														ENd
													ELSE IF(ISNULL(@Balanceval,0) =0)
														BEGIN
															SET @Balanceval=0
															BREAK;
														END
														SET @qty = @Balanceval
													END
													
												END
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
													SET @prioritysId = ISNULL(@prioritysId,0)+1
													INSERT INTO #MainOutputtable_1(Dup_pkid,Broker_Code, ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
													VALUES(@Dup_pkid,@Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No,  'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
												END
											DROP TABLE #tempValExists
											SET @purchase_Op_Date = ''
											SET @purchase_Op_Rate = ''
											SET @purchase_Op_Qty  = ''
											SET @purchase_Op_Bill = ''
										END
								END
							ELSE IF(@isIntradayCol=1)
									BEGIN
								IF(@TransType LIKE '%Bought%')
									BEGIN
										/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
										SELECT  ROW_NUMBER ( ) OVER (ORDER BY   scriptcode,Holding_type,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
										* INTO #tempBought	
										FROM	#MainOutputtable_1 
										WHERE isintradaycol		=	1 
										AND Flag_Type			=	'Sold'  
										AND Flag_Type_Sold		=	'Sold'
										AND	script_name			=	@scriptname 
										AND holding_type		=	@holding_type  
										AND consultant_name		=	@Consultant_Name 
										AND Family_Name			=	@Family_Name 
										AND Member_Name			=	@Member_Name
										AND ISNULL(sold_qty,0)	!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))  
										ORDER BY NameId
										IF ((Select Count(*) FROM #tempBought) > 0)
											BEGIN
																										 
												DECLARE @Bought_COUNT INT = ( SELECT COUNT(*) FROM #tempBought )
												DECLARE @Temppurchase_Qty FLOAT 
												SET @purchase_Op_Qty = @qty
												DECLARE @Balance_val FLOAT
												WHILE(@Bought_COUNT  > 0)
													BEGIN 
														DECLARE @tempSale_ID INT = (SELECT TOP(1) id FROM #tempBought ORDER BY Dup_pkid)

														SET @str=@TransType

														SELECT	@Temppurchase_Qty		= sold_qty,
																@soldDate				= sold_date,
																@soldRate				= sold_rate,
																@soldBillNo				= sold_bill_no,
																@pkid					= pkid
														FROM #tempBought 
														WHERE id  = @tempSale_ID 

														SET @Sold_Qty= ABS(@Temppurchase_Qty)
															 
														IF(@TransType='Bought')
															BEGIN
																UPDATE #MainOutputtable_1  
																SET	purchase_date		=	@dates,
																	purchase_bill_no	=	@billno,
																	purchase_rate		=	@rate,
																	purchase_qty		= CASE	WHEN @Temppurchase_Qty > @purchase_Op_Qty 
																								THEN ABS(@purchase_Op_Qty) 
																								ELSE ABS(@Temppurchase_Qty) 
																					   	    END,
																	Flag_Type='Bought'
																WHERE  id = @tempSale_ID  and pkid=@pkid
															END
														IF(@Temppurchase_Qty > @purchase_Op_Qty )
															BEGIN
																UPDATE #MainOutputtable_1  
																SET sold_qty = ABS(@purchase_Op_Qty) 
																WHERE Flag_Type_Sold = 'Sold' 
																AND   id = @tempSale_ID   and pkid=@pkid
															END
															
														DELETE FROM #tempBought  WHERE id = @tempSale_ID 
														SET @Balance_val = isnull(@purchase_Op_Qty,0) - (@Sold_Qty)
														SET @tablerowscount = (SELECT COUNT(*) FROM  #tempBought)
															
														SET @Bought_COUNT  = @Bought_COUNT  - 1
														SET @qty = @Balance_val

														IF(@Balance_val  < 0)
															BEGIN
																
																--SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1

																SET @soldQty = ABS(@Balance_val) 
																SET @prioritysId  =(SELECT MAX(prioritys) FROM #MainOutputtable_1 )--WHERE id=@tempSale_ID )
																SET @prioritysId = ISNULL(@prioritysId,0)+1
															
																INSERT INTO #MainOutputtable_1(Dup_pkid, Broker_Code,ID,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code, Trans_No, Flag_Type,Flag_Type_sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name,Trans_Type)
																VALUES(@Dup_pkid,@Broker_Code, @tempSale_ID , @ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balance_val),@soldRate,@isIntradayCol,@Consultant_Name,'sold')
																	
																--Select @Pkid
																UPDATE #MainOutputtable_1 
																SET prioritys=@prioritysId+1  
																WHERE prioritys >= @prioritysId AND ID<>@tempSale_ID 
																
																SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	

																IF(@idcount>0)
																	BEGIN
 																		UPDATE #MainOutputtable_1
																		SET Dup_pkid = Dup_pkid + 1 
																		WHERE  Dup_pkid >= @Dup_pkid 
																		and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																	END

																BREAK;
															END
														ELSE IF(@Balance_val  > 0 and @tablerowscount = 0)
															BEGIN
																IF(@TransType='Bought')
																	BEGIN
																		SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																		SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																		SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																		SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																		SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																		SET @Dup_pkid = @Dup_pkid + 1

																		SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																			
																		INSERT INTO #MainOutputtable_1(Dup_pkid,Broker_Code, ID,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																		VALUES(@Dup_pkid, @Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balance_val)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	
																		UPDATE #MainOutputtable_1 
																		SET prioritys=@prioritysId+1  
																		WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																			
																		SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																		IF(@idcount>0)
																			BEGIN
																				UPDATE #MainOutputtable_1 
																				SET Dup_pkid = Dup_pkid + 1 
																				WHERE  Dup_pkid >= @Dup_pkid and   
																				CONVERT(VARCHAR(200),pkid) NOT IN ( SELECT value FROM Fn_split(@Pkid, ',') ) 
																			END
																	END
															ENd
														SET @purchase_Op_Qty= (@Balance_val)
													END

													
													
											END
										/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
										ELSE
											BEGIN
												
												SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
												SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0) + 1 from #mainoutputtable_1)

												INSERT INTO #mainoutputtable_1 (id,Broker_Code,ScriptCode,Dup_pkId, Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name,Trans_Type) 
												VALUES ( @ID, @Broker_Code,@ScriptId,@Dup_pkid,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name,@Flag_Type) 
						
											END
											DROP TABLE #tempBought
									END	
								ELSE IF(@TransType LIKE '%Sold%')
									BEGIN
										/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
										SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,Holding_type,case when opening_date <> NULL then opening_date else purchase_date end ) AS NameId,* 
										INTO #tempSold 
										FROM #MainOutputtable_1
										WHERE isintradaycol		=	1 
										AND Flag_Type			IN	('Bought','Rights','Bonus','Ipo','Opening','Split') 
										AND	script_name			=	@scriptname 
										AND holding_type		=	@holding_type  
										AND consultant_name		=	@Consultant_Name 
										AND Member_Name			=	@Member_Name
										AND Family_Name			=	@Family_Name 										
										AND ISNULL(sold_qty,0)	=	0  
								
										ORDER BY NameId

										IF ((Select count(*)  From #tempSold) > 0)
									 		BEGIN
												DECLARE @Balanceval_sold FLOAT																					
												DECLARE @RSoldCOUNT INT = (SELECT COUNT(*) FROM #tempSold)
												DECLARE @TempQty_Sold FLOAT 
												    
												WHILE(@RSoldCOUNT > 0 )
													BEGIN 
														SET @Sold_Qty = @qty
														SET @tempID  =   (SELECT TOP(1) id FROM #tempSold)
														SET @str     =   (SELECT TOP(1) Flag_Type FROM #tempSold WHERE id = @tempID  ORDER BY Dup_pkid,NameId)
														SET @pkid    =   (SELECT TOP(1) pkid  FROM #tempSold WHERE id  = @tempID )
															
														IF(@str='Bought')
															BEGIN
																SELECT	@TempQty_Sold	=	purchase_qty,
																		@PurchaseDate	=	purchase_date,
																		@Purchaserate	=	purchase_rate,
																		@PurchaseBillNo	=	purchase_bill_no
																FROM #tempSold 
																WHERE id  = @tempID 
															END
														IF(@Sold_Qty > 0)
															BEGIN
																SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																SET @prioritysId = ISNULL(@prioritysId,0)+1
																UPDATE #MainOutputtable_1  
																	SET	
																		purchase_qty  = CASE WHEN @str ='Bought'
																								THEN CASE	WHEN  @TempQty_Sold >= @Sold_Qty 
																										THEN @Sold_Qty 
																										ELSE @TempQty_Sold 
																								    END
																							END,
																		sold_date      = @dates,
																		sold_bill_no   = @billno,
																		sold_rate      = @rate,
																		sold_qty       = CASE WHEN @TempQty_Sold > @Sold_Qty THEN @Sold_Qty ELSE @TempQty_Sold END,
																		Flag_Type_Sold = 'Sold',
																		prioritys      = @prioritysId
																WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND pkid = @pkid
																SET @Balanceval_sold = ABS(@Sold_Qty) - ABS(@TempQty_Sold)
															END
															
														DELETE FROM #tempSold WHERE id = @tempID
														SET @RSoldCOUNT = @RSoldCOUNT - 1
														SET @tablerowscount = (SELECT COUNT(*) FROM  #tempSold)
														
														IF(@Balanceval_sold < 0)
															BEGIN
															--	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1

																SET @PurchaseQty=ABS(@Sold_Qty) 
																SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																INSERT INTO #MainOutputtable_1(Dup_pkid,Broker_Code,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																VALUES(@Dup_pkid,@Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval_sold)  ,@Purchaserate,@isIntradayCol,@Consultant_Name,@Flag_Type)
															
																	
																SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																UPDATE #MainOutputtable_1 
																SET prioritys=@prioritysId    
																WHERE prioritys >= @prioritysId AND ID <> @tempID
																	
																SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																IF(@idcount>0)
																	BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																	END
																BREAK;
															END
														ELSE IF(ISNULL(@Balanceval_sold,0) > 0 AND @tablerowscount=0)
															BEGIN
																SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1

																SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)

																INSERT INTO #MainOutputtable_1(Dup_pkid,Broker_Code,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
																VALUES(@Dup_pkid,@Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval_sold)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)

																UPDATE #MainOutputtable_1 
																SET prioritys=@prioritysId+1  
																WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
																SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																IF(@idcount>0)
																	BEGIN
																		UPDATE #MainOutputtable_1 
																		SET Dup_pkid = Dup_pkid + 1 
																		WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																	END
															END
														SET @qty = @Balanceval_sold
													END	
													
											END
											
										/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
										ELSE
											BEGIN
												SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
												SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0) +1 from #mainoutputtable_1)

												INSERT INTO #MainOutputtable_1(Dup_pkid,Broker_Code, ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
												VALUES(@Dup_pkid,@Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No,  'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
											END
										DROP TABLE #tempSold
										SET @purchase_Op_Date	=	''
										SET @purchase_Op_Rate	=	''
										SET @purchase_Op_Qty	=	''
										SET @purchase_Op_Bill	=	''
									END

								END

						FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Broker_Code,@ScriptId ,@Fam_Code,@Family_Name,@Mem_Code,@Member_Name, @billno,@Flag_Type , @TransType, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
						END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 
		 
		IF(@IsIntraDay = 0 AND @short_Long_Term != 0  )
			BEGIN
				IF(@short_Long_Term = 1)  -- Long Term
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss  ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type])

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						CASE WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN   CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
							 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId, opening_bill_no,id,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						 Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						0,
						Round(ISNULL( CASE	WHEN   isintradaycol = 0 and opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
											WHEN   isintradaycol = 0 and purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4),
						0,
						0,
						0,consultant_name,nse_rate,bse_rate,1 sort ,isintradaycol,Trans_Type
						FROM #mainoutputtable_1 
						WHERE (@IsFromMonthWise = 1 OR ISNULL(closing_qty,0) = 0)
						AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
									(
										DATEDIFF(DAY,CONVERT(DATETIME,opening_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) > 365 
									)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									(
										DATEDIFF(DAY,CONVERT(DATETIME, purchase_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) > 365
									)
								)
							)
							order by NameId
					END

				ELSE If(@short_Long_Term = 2)  -- Short Term
					BEGIN

						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type])

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4) as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						Round(ISNULL(
								CASE	WHEN   isintradaycol = 0 and opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN    isintradaycol = 0 and purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4) ,
						0,
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,Trans_Type 
						FROM #mainoutputtable_1 
						WHERE  (@IsFromMonthWise = 1 OR ISNULL(closing_qty,0) = 0)
						AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
										(		
											DATEDIFF(DAY,CONVERT(DATETIME,opening_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) < 365 
										)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									  (		
										DATEDIFF(DAY,CONVERT(DATETIME, purchase_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) < 365
									  )
								)
							)
						order by NameId
					END

				ELSE If(@short_Long_Term = 4)  -- Short Term + Long Term
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type])

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						
						opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) < 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) < 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						(CASE  WHEN   isintradaycol = 0 and ( (ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
								    (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
							  THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						(CASE WHEN  isintradaycol = 0 and ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365) OR
								   (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365))  
							  THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,Trans_Type 
						FROM #mainoutputtable_1 
						WHERE  (@IsFromMonthWise = 1 OR ISNULL(closing_qty,0) = 0)
						 AND ISNULL(isintradaycol,0)=0
						order by NameId
					END

			END

		ELSE If(@short_Long_Term = 3 AND @IsIntraDay = 1 )  -- Only Speculation
			BEGIN
				INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss  ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type])

				SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
				case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
				opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
				ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),purchase_date,ISNULL(purchase_bill_no,0),
				ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,sold_date ,sold_bill_no ,isnull(sold_qty,0) ,
				ISNULL(sold_rate,0),ISNULL(sold_amount,0) , 
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4) as gain_loss,

				closing_qty ,closing_rate ,closing_value ,
				0,
				0,
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4) ,
				0,
				0,consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,Trans_Type 
				FROM #mainoutputtable_1 
				WHERE  (ISNULL(closing_qty,0) = 0)  AND (ISNULL(isintradaycol,0)=1) AND (ISNULL(purchase_qty,0)! = 0 AND  ISNULL(sold_qty,0) ! = 0) 
				order by NameId
			END

		ELSE
			BEGIN
			        --Select * from #mainoutputtable_1
			  
				INSERT INTO #mainoutputtable_1_Final (OrderBy,   opening_bill_no, Broker_Code,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss , closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type])

				SELECT 
				ROW_NUMBER ( ) OVER (ORDER BY  Family_Name,Family_Code,Member_Name,Member_Code,consultant_name,holding_type,ScriptCode,script_name,--pkid,
			    case WHEN  Dup_pkid is Null Then Pkid
				     WHEN  Dup_pkid is NOt Null then Dup_pkid 
				     else Dup_pkid end,prioritys, 
				case when CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
				else CONVERT(DATE,purchase_date,103) END,
				prioritys DESC, sold_date DESC ) AS NameId,
				 opening_bill_no,Broker_Code,
				id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,
				  Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) < 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN isintradaycol = 0 AND  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365)     -- short term for openings
						THEN  ISNULL(sold_rate ,0)* ISNULL(sold_qty ,0)- ISNULL(opening_rate,0)*ISNULL(opening_qty ,0)
					 WHEN isintradaycol = 0 AND (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365)  -- short term for purchase
						THEN  ISNULL(sold_rate ,0)* ISNULL(sold_qty ,0)- ISNULL(purchase_rate,0)*ISNULL(purchase_qty ,0)
					 ELSE 0.0 END,

						
				CASE WHEN  isintradaycol = 0 and ((opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)     -- long term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365))						 -- long term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  isintradaycol = 1 AND (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,Trans_Type 
				FROM #mainoutputtable_1 
				order by NameId
			END
		 
			UPDATE #mainoutputtable_1_Final SET prioritys=0
			DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
			UPDATE #mainoutputtable_1_Final
			SET prioritys  = @i , @i = @i + 1

	IF(@OUTPUT_Flag='Details')
		BEGIN
			IF(@Investmenttype != 2)
				BEGIN
					IF(@ConsultantCode !='')
						BEGIN
							SELECT id,prioritys,ScriptCode, Family_Name,Member_Name,script_name 'Script Name',Holding_Type,opening_bill_no,
							CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
							CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
							CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',
							ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',ISNULL(gain_loss,0) 'Gain/Loss',
							CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
							ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
							ISNULL(short_term,0) short_term,ISNULL(long_term,0) long_term,ISNULL(speculation,0) speculation,
							CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
							CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
							consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,ISNULL(isintradaycol,0),1 sort,[type] 
							FROM #mainoutputtable_1_Final
							WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)   
							ORDER By   consultant_name, script_name,Holding_Type
						END
					ELSE
						BEGIN
							SELECT id,prioritys,ScriptCode, Family_Name,Member_Name,script_name 'Script Name',Holding_Type,opening_bill_no,
							CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
							CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
							CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
							ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
							ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
							ISNULL(short_term,0) short_term,ISNULL(long_term,0) long_term,ISNULL(speculation,0) speculation,
							CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE 0 END gain_speculation,
							CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE 0 END loss_speculation,
							consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,isintradaycol,1 sort,[type] 
							FROM #mainoutputtable_1_Final
							WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
							ORDER By  Family_Name, Member_Name,Holding_Type, script_name, consultant_name--,CONVERT(date, purchase_date,103) 

				
						END
				END
			ELSE
				IF(@ConsultantCode!='')
					BEGIN
						SELECT id,prioritys,ScriptCode, Family_Name,Member_Name,script_name 'Script Name',Holding_Type,opening_bill_no,
						CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty ,0)'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
						ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,
						ISNULL(long_term,0)long_term,
						ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,isintradaycol,1 sort,[type] 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0) 
						ORDER By  consultant_name,  sort,Family_Name,  Member_Name ,script_name
					END
				ELSE
					BEGIN
						select * from (
						SELECT id,prioritys,ScriptCode, Family_Name,Member_Name,script_name 'Script Name',Holding_Type,opening_bill_no,
						CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',
						CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
						ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,isintradaycol,1 sort,[type] 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  

						 
						) T
						ORDER By   T.sort,T.Family_Name,  T.Member_Name ,T.consultant_name,T.[script name]
					 
											
					END
			END

		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
			 --select * FROM #mainoutputtable_1_Final
				IF(@ConsultantCode !='')
					BEGIN					
						SELECT  '' Opening_bill_no,
						0 id ,  
						0 prioritys, 
						ScriptCode, 
						Family_Name,
						Member_Name,
						Family_Code,
						Member_Code, 
						script_name 'Script Name',  
						Holding_Type,
						NULL 'Opening Date', 
						SUM(ISNULL(opening_qty,0)) 'Opening Qty',
						ISNULL((ISNULL(SUM(ISNULL(opening_amount,0)),0)  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate', 
					    SUM(ISNULL(opening_amount,0)) 'Opening Amount',
						NULL 'Purchase Date',
						'' 'Purchase BillNo', 
						SUM(ISNULL(purchase_qty,0))  'Purchase Qty',
					    ISNULL((ISNULL(SUM(purchase_amount),0)  / SUM(NULLIF(purchase_qty,0))),0)  'Purchase Rate',
						SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
						NULL 'Sold Date', 
						'' 'Sold BillNo', 
						SUM(ISNULL(sold_qty,0)) 'Sold Qty',  
						CASE WHEN SUM(sold_qty) != 0 THEN SUM(sold_amount)/nullif(SUM(sold_qty),0) ELSE 0 END  'Sold Rate',
						SUM(ISNULL(sold_amount,0)) 'Sold Amount',
						SUM(ISNULL(gain_loss ,0)) 'Gain/Loss',
						 SUM(ISNULL(gain,0))  'Gain', 
						SUM(ISNULL(loss,0))  'Loss',
						SUM(ISNULL(closing_qty,0))  'Closing Qty',
						CASE WHEN SUM(closing_qty) != 0 THEN (SUM(closing_value) / SUM(NULLIF(closing_qty,0))) ELSE 0 END  'Closing Rate',					
						CASE WHEN SUM(closing_qty) != 0	THEN SUM(ISNULL(closing_value,0))  ELSE 0 END  'Closing Value', 
						SUM(ISNULL(short_term,0))  short_term,
						SUM(ISNULL(long_term,0))  long_term,
						SUM(ISNULL(speculation,0))speculation,
					    SUM(gain_speculation)gain_speculation,
						SUM(ISNULL(loss_speculation,0))loss_speculation,  
						consultant_name,
						0 nse_rate,
						0 bse_rate,
						1 sort,
						'' broker_code --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
						FROM
							(
								SELECT '' Opening_bill_no,MAX(id+0)id ,MAX (prioritys+0) prioritys,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code, script_name  , Holding_Type,
								NULL 'Opening Date',
								SUM(isNull(opening_qty,0)) 'Opening_Qty',
								sum(isNull(opening_rate,0)) 'opening_rate' ,
								SUM(isNull(opening_amount,0)) 'Opening_Amount',
								NULL 'Purchase Date',purchase_bill_no,
								SUM(isNull(purchase_qty,0)) 'Purchase_Qty', 
								SUM(isnull(purchase_rate,0)) 'purchase_rate',
								SUM(isNull(purchase_amount,0)) 'Purchase_Amount',
								NULL 'Sold Date',sold_bill_no ,
								SUM(isNull(sold_qty,0)) 'Sold_Qty', 
								SUM(isNull(sold_rate,0))'sold_rate'  ,
								SUM(isNull(sold_amount,0)) 'Sold_Amount',
								SUM(isNull(gain_loss,0)) 'Gain_Loss',
								SUM(isNull(gain,0)) 'Gain',
								SUM(isNull(loss,0)) 'Loss',
								SUM(isNull(closing_qty,0)) 'Closing_Qty',						
						    	(SUM(ISNULL(closing_value,0)) / SUM(NULLIF(closing_qty,0))) 'Closing_Rate',
								SUM(isNull(closing_value,0)) 'Closing_Value',
								SUM(isNull(short_term,0)) 'short_term',
								SUM(isNull(long_term,0)) 'long_term',
								SUM(isNull(speculation,0)) 'speculation',
								SUM(isNull(gain_speculation,0)) gain_speculation,
								SUM(isnull(loss_speculation,0)) loss_speculation,  consultant_name,0 nse_rate,0 bse_rate,1 sort,'' broker_code--,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
								FROM #mainoutputtable_1_Final 
								GROUP BY  Family_Name,Family_Code,Member_Name,Member_Code,consultant_name,ScriptCode,script_name,Holding_Type,purchase_bill_no,sold_bill_no 
							)a
						GROUP BY   Family_Name,Family_Code,Member_Name,Member_Code,consultant_name,Holding_Type,script_name  ,ScriptCode
						ORDER BY   consultant_name,Family_Name,Family_Code,Member_Name,Member_Code ,Holding_Type, script_name,ScriptCode
					 END
				ELSE
					BEGIN
						SELECT  '' Opening_bill_no,0 id ,  0 prioritys, ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code, script_name 'Script Name',  Holding_Type,
						NULL 'Opening Date',
						SUM(ISNULL(opening_qty,0)) 'Opening Qty',   ISNULL((ISNULL(SUM(ISNULL(opening_amount,0)),0)  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate',
						SUM(ISNULL(opening_amount,0)) 'Opening Amount',
						NULL 'Purchase Date',MAX(purchase_bill_no) 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty', ISNULL((ISNULL(SUM(purchase_amount),0)  / 
						SUM(NULLIF(purchase_qty,0))),0)  'Purchase Rate',
						SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
						NULL 'Sold Date', MAX(sold_bill_no) 'Sold BillNo',
						SUM(ISNULL(sold_qty,0)) 'Sold Qty',   ISNULL((ISNULL(SUM(sold_amount),0) / NULLIF (SUM(ISNULL(sold_qty,0)),0)),0)'Sold Rate',
						SUM(ISNULL(sold_amount,0)) 'Sold Amount',
						SUM(ISNULL(gain_loss ,0)) 'Gain/Loss', 
						SUM(ISNULL(gain,0))  'Gain', 
						SUM(ISNULL(loss,0))  'Loss',
						SUM(ISNULL(closing_qty,0))  'Closing Qty',
						ISNULL((ISNULL(SUM(ISNULL(closing_value,0)),0) / NULLIF(SUM(ISNULL(closing_qty,0)),0)),0)   'Closing Rate', 
						CASE WHEN SUM(closing_qty) != 0
							THEN SUM(ISNULL(closing_value,0))   
					    ELSE 0
				        END  'Closing Value', 
						SUM(ISNULL(short_term,0))  short_term,
						SUM(ISNULL(long_term,0))  long_term,
						SUM(ISNULL(speculation,0))speculation, 
						SUM(ISNULL(gain_speculation,0))gain_speculation,
						SUM(ISNULL(loss_speculation,0))loss_speculation,  consultant_name,0 nse_rate,0 bse_rate,1 sort,''   broker_code  
						FROM
							(
								SELECT '' Opening_bill_no,MAX(id+0)id ,MAX (prioritys+0) prioritys,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code, script_name  , Holding_Type,
								NULL 'Opening Date',
								SUM(isNull(opening_qty,0)) 'Opening_Qty',
								sum(isNull(opening_rate,0)) opening_rate ,
								SUM(isNull(opening_amount,0)) 'Opening_Amount',
								NULL 'Purchase Date',purchase_bill_no,
								SUM(isNull(purchase_qty,0)) 'Purchase_Qty', 
								SUM(isNull(purchase_rate,0)) 'purchase_rate',
								SUM(isNull(purchase_amount,0)) 'Purchase_Amount',
								NULL 'Sold Date',sold_bill_no ,
								SUM(sold_qty) 'Sold_Qty',
								SUM(sold_rate)sold_rate  , 
							    SUM(sold_amount) 'Sold_Amount',
								SUM(gain_loss) 'Gain_Loss',
								SUM(gain) 'Gain',SUM(loss) 'Loss',
								SUM(closing_qty) 'Closing_Qty',

								--SUM(closing_rate) 'Closing_Rate',
								(SUM(ISNULL(closing_value,0)) / SUM(NULLIF(closing_qty,0))) 'Closing_Rate',

								SUM(closing_value) 'Closing_Value',SUM(short_term) short_term,SUM(long_term) long_term,
								SUM(speculation) speculation,SUM(gain_speculation) gain_speculation,SUM(loss_speculation) loss_speculation,  consultant_name,0 nse_rate,0 bse_rate,1 sort,''   broker_code  --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
								FROM #mainoutputtable_1_Final 
								GROUP BY  Family_Name,Family_Code,Member_Name,Member_Code,consultant_name,ScriptCode,script_name,Holding_Type,purchase_bill_no,sold_bill_no 
							)a
						GROUP BY   Family_Name,Family_Code,Member_Name,Member_Code,consultant_name,Holding_Type,script_name  ,ScriptCode
						ORDER BY  Family_Name,Family_Code,Member_Name,Member_Code , Holding_Type, script_name,ScriptCode, 	 consultant_name 
					END
			END

		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN		
				SELECT  prioritys ,Trans_No,id ,ScriptCode, Family_Name,Member_Name, script_name ,Holding_Type, flag_script_name,flag_Holding_Type,
				CONVERT(DATE, opening_date,103),ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),
				CONVERT(DATE, purchase_date,103),purchase_bill_no,ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,
				CONVERT(DATE, sold_date,103) ,sold_bill_no ,ISNULL(sold_qty,0),ISNULL(sold_rate,0),ISNULL(sold_amount ,0),
				ISNULL(gain_loss ,0),ISNULL(gain,0) ,ISNULL(loss,0),ISNULL(closing_qty ,0),ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
				ISNULL(short_term,0),ISNULL(long_term,0),ISNULL(speculation,0),ISNULL(gain_speculation,0),ISNULL(loss_speculation,0),
				consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol
				FROM #mainoutputtable_1_Final
				ORDER BY  Family_Name,Member_Name,consultant_name, script_name  
			END
		
		ELSE IF(@OUTPUT_Flag='BrokerWiseData')
			BEGIN			
				SELECT  '' Opening_bill_no, 0 id ,  0 prioritys, ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code, script_name 'Script Name',  Holding_Type,
						NULL 'Opening Date', 
						SUM(ISNULL(opening_qty,0)) 'Opening Qty',   ISNULL((ISNULL(SUM(ISNULL(opening_amount,0)),0)  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate', 
						SUM(ISNULL(opening_amount,0)) 'Opening Amount',
						NULL 'Purchase Date',MAX(purchase_bill_no) 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty', ISNULL((ISNULL(SUM(purchase_amount),0)  / SUM(NULLIF(purchase_qty,0))),0)  'Purchase Rate', 
						SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
						NULL 'Sold Date', MAX(sold_bill_no) 'Sold BillNo',
						SUM(ISNULL(sold_qty,0)) 'Sold Qty',   ISNULL((ISNULL(SUM(sold_amount),0) / NULLIF (SUM(ISNULL(sold_qty,0)),0)),0)'Sold Rate', 
						SUM(ISNULL(sold_amount,0)) 'Sold Amount', 
						SUM(ISNULL(gain_loss ,0)) 'Gain/Loss', 
						SUM(ISNULL(gain,0))  'Gain', 
						SUM(ISNULL(loss,0))  'Loss',
						SUM(ISNULL(closing_qty,0))  'Closing Qty',ISNULL((ISNULL(SUM(closing_value),0) / NULLIF(SUM(closing_qty),0)),0)   'Closing Rate',
						SUM(ISNULL(closing_value,0))  'Closing Value',
						SUM(ISNULL(short_term,0))  short_term, 
						SUM(ISNULL(long_term,0))  long_term,
						SUM(ISNULL(speculation,0))speculation,
						SUM(gain_speculation)gain_speculation, 
						SUM(ISNULL(loss_speculation,0))loss_speculation,  consultant_name,0 nse_rate,0 bse_rate,1 sort, broker_code --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
						FROM
							(
								SELECT '' Opening_bill_no, MAX(id+0)id ,MAX (prioritys+0) prioritys,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code, script_name  , Holding_Type,
								NULL 'Opening Date',
								SUM(isNull(opening_qty,0)) 'Opening_Qty',
								sum(isNull(opening_rate,0)) opening_rate ,
								SUM(isNull(opening_amount,0)) 'Opening_Amount',
								NULL 'Purchase Date',purchase_bill_no,
								SUM(isNull(purchase_qty,0)) 'Purchase_Qty', 
								SUM(isNull(purchase_rate,0)) purchase_rate,
								SUM(isNull(purchase_amount,0)) 'Purchase_Amount',
								NULL 'Sold Date',sold_bill_no ,
								SUM(isNull(sold_qty,0)) 'Sold_Qty', 
								SUM(isNull(sold_rate,0))sold_rate  , 
								SUM(isNull(sold_amount,0)) 'Sold_Amount',
								SUM(isNull(gain_loss,0)) 'Gain_Loss',
								SUM(isNull(gain,0)) 'Gain',
								SUM(isNull(loss,0)) 'Loss',
								SUM(isNull (closing_qty,0)) 'Closing_Qty',
								SUM(isNull(closing_rate,0)) 'Closing_Rate',
								SUM(isNull(closing_value,0)) 'Closing_Value',
								SUM(isNull(short_term,0)) short_term,
								SUM(isNull(long_term,0)) long_term,
								SUM(isNull(speculation,0)) speculation,
								SUM(isNull(gain_speculation,0)) gain_speculation,
								SUM(isNull(loss_speculation,0)) loss_speculation, 
								 consultant_name,0 nse_rate,0 bse_rate,1 sort, broker_code --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
								FROM #mainoutputtable_1_Final 
								GROUP BY  Family_Name,Family_Code,Member_Name,Member_Code,consultant_name,broker_code,ScriptCode,script_name,Holding_Type,purchase_bill_no,sold_bill_no 
							)a
						GROUP BY  Family_Name,Family_Code,Member_Name,Member_Code,consultant_name,Holding_Type,broker_code,script_name  ,ScriptCode
						ORDER BY  Family_Name,Family_Code,Member_Name,Member_Code , Holding_Type, consultant_name, 	broker_code , script_name,ScriptCode			 
			END

		ELSE IF(@output_Flag='ClosingStocks')
			BEGIN
		--	Select * from #mainoutputtable_1
				 SELECT id,
						Trans_No ,
						Broker_Code,
						script_name,
						ScriptCode,
						Family_Name,
						Member_Name,
						Family_Code,
						Member_Code,
						holding_type,
						CASE
							WHEN ISNULL(closing_qty,0) < 0		THEN sold_bill_no
							WHEN ISNULL(opening_date,'') != ''   OR  ISNULL(purchase_date,'') != '' THEN  purchase_bill_no
							ELSE ''
						END  AS  'bill_no',
						CASE
							WHEN ISNULL(closing_qty,0) < 0		THEN CONVERT(DATE,sold_date,101)
							WHEN ISNULL(opening_date,'') != ''	THEN  CONVERT(DATE,opening_date,101)
							WHEN ISNULL(purchase_date,'') != '' THEN CONVERT(DATE,purchase_date,101)
						END  AS  'trans_dt',
						ABS(ISNULL(closing_qty,0)) 'Qty',
						ISNULL(closing_rate,0) 'rate',
						ISNULL(closing_value,0) 'amount',
						isintradaycol,
						consultant_name,
						CASE
							WHEN ISNULL(closing_qty,0)    < 0		THEN 'Sold'
							WHEN ISNULL(opening_date,'')  != ''		THEN 'Opening'
							WHEN ISNULL(purchase_date,'') != ''		THEN 'Bought'
							ELSE ''
						END  AS  'Type'
				from #mainoutputtable_1_Final 
				WHERE ISNULL(closing_qty,0) <> 0
				ORDER BY  trans_dt,Trans_No			
			END
		DROP TABLE #mainoutputtable_1 	 
		DROP TABLE #alldata 	 
		DROP TABLE #Family
		DROP TABLE #Members

  END  




































GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_FamilyWise_Equity_Monthwise]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_FamilyWise_Equity_Monthwise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_Equity_Monthwise] AS' 
END
GO


-- exec[proc_StockholdingPosition_FamilyWise_Equity_Monthwise]  0,0,'0','D0003','1120162017','2016-04-01 12:00:00:00','2017-03-31 03:50:37:50','A0418','','','', '0' ,'0','Details',''
ALTER PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_Equity_Monthwise] --
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(MAX),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(MAX),@ConsultantCode  VARCHAR(MAX),@BSE_NSE_Code VARCHAR(MAX),@Is_BFCF VARCHAR(MAX),@IsIntraDay VARCHAR(MAX),@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX),@FamilyCode VARCHAR(MAX),
@IsWithTax bit = 0,@IsScripWise bit = 1,@RecordOnlyhavingClosingbalanceZero bit = 0,@WithActualAvgRate bit = 0, @DateWiseClosinStock  bit = 0,@IsBSEISIN bit=0)
AS 
  BEGIN
  SET NOCOUNT ON; 
		DECLARE @StartYearDate varchar(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101)
		DECLARE @IsMmberSelected bit =  (CASE WHEN @memcode = '' OR @memcode IS NULL THEN 0 ELSE 1 END)
		CREATE TABLE #mainoutputtable_1_MonthWise
        ( 
			pkid INT identity(1,1),
			Dup_pkid  INT,
			Family_Name VARCHAR(MAX),
			Member_Name VARCHAR(MAx),
			Family_Code VARCHAR(MAx),
			Member_Code VARCHAR(MAx),
			Trans_No VARCHAR(20),
			id INT,
			prioritys INT,
			Trans_Type  VARCHAR(50),
		    Split_Type VARCHAR(50), 
			Flag_Type VARCHAR(50),
			Flag_Type_Sold VARCHAR(10),
			flag_script_name  VARCHAR(MAx),
			flag_holding_type VARCHAR(Max), 
			script_name  VARCHAR(Max),
			holding_type VARCHAR(200), 
			opening_bill_no VARCHAR(100),		    
			opening_date DATETIME,
			opening_qty  FLOAT DEFAULT 0,
			opening_rate  FLOAT DEFAULT 0,
			opening_amount AS( [opening_qty] * [opening_rate] ), 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount AS( purchase_qty * purchase_rate ), 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount AS ( sold_qty * sold_rate ), 
			gain_loss float,
			closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 
			closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
		   closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
		   short_term FLOAT DEFAULT 0,
		   long_term  FLOAT DEFAULT 0,
           speculation  FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(Max), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(200) ,
		   ScriptCode  VARCHAR(Max),
		   Broker_Code  VARCHAR(MAX)
        )  
		CREATE TABLE #mainouttable_1_Monthwise_BSEISINO
		(
		     pkid INT,
			 Dup_pkid  INT,
		     Family_Name VARCHAR(MAX),
			 Member_Name VARCHAR(MAx),
			 Family_Code VARCHAR(MAx),
			 Member_Code VARCHAR(MAx),
			 Trans_No VARCHAR(20),
		     id INT,
			 prioritys INT,
			 Trans_Type  VARCHAR(50),
			 Split_Type VARCHAR(50), 
			 Flag_Type VARCHAR(50),
			 Flag_Type_Sold VARCHAR(10),
			 flag_script_name  VARCHAR(MAx),
			 flag_holding_type VARCHAR(Max),
			 script_name  VARCHAR(Max),
			 holding_type VARCHAR(200), 
			 opening_bill_no VARCHAR(100),		    
			 opening_date DATETIME,
			 opening_qty  FLOAT DEFAULT 0,
			 opening_rate  FLOAT DEFAULT 0,
			 opening_amount FLOAT DEFAULT 0,
			 purchase_date DATETIME,
			 purchase_bill_no VARCHAR(100),
			 purchase_qty FLOAT DEFAULT 0,
			 purchase_rate FLOAT DEFAULT 0,
			 purchase_amount FLOAT DEFAULT 0,
			 sold_date DATETIME,
			 sold_bill_no VARCHAR(100),
			 sold_qty FLOAT DEFAULT 0,
			 sold_rate FLOAT DEFAULT 0,
			 sold_amount FLOAT DEFAULT 0,
			 gain_loss FLOAT DEFAULT 0,
			 closing_qty FLOAT DEFAULT 0,
			 closing_rate FLOAT DEFAULT 0,
			 closing_value FLOAT DEFAULT 0,
			 short_term FLOAT DEFAULT 0,
		     long_term  FLOAT DEFAULT 0,
             speculation  FLOAT DEFAULT 0,
		     gain_speculation FLOAT DEFAULT 0,
		     loss_speculation FLOAT DEFAULT 0,
		     consultant_name VARCHAR(500), 
             nse_rate FLOAT DEFAULT 0,
		     bse_rate FLOAT DEFAULT 0,
		     dayscount FLOAT DEFAULT 0,
		     isintradaycol INT,
		     [type] VARCHAR(200) ,
		     ScriptCode  VARCHAR(Max),
		     Broker_Code  VARCHAR(MAX)
		)

		CREATE TABLE #mainoutputtable_1_Final_MonthWise
        ( 
		   OrderBy varchar(100),
		   Dup_pkid  INT,
           Family_Name VARCHAR(MAx),
		   Member_Name VARCHAR(MAx),
		   Family_Code VARCHAR(MAx),
		   Member_Code VARCHAR(MAx),
		   Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT,
		   Split_Type VARCHAR(50),
		   Flag_Type VARCHAR(50),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name  VARCHAR(Max),
		   flag_holding_type VARCHAR(Max), 
		   script_name  VARCHAR(Max),
		   holding_type VARCHAR(Max), 
		   opening_bill_no VARCHAR(100),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
		   gain_loss FLOAT DEFAULT 0,
		   gain AS CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss AS CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, gain_speculation FLOAT DEFAULT 0,loss_speculation FLOAT DEFAULT 0,consultant_name VARCHAR(Max), 
           nse_rate FLOAT DEFAULT 0,bse_rate FLOAT DEFAULT 0,dayscount FLOAT DEFAULT 0,isintradaycol INT,[type] VARCHAR(200),sort   VARCHAR(5),ScriptCode  VARCHAR(Max),
		   Broker_Code  VARCHAR(MAX)
        ) 

		CREATE TABLE #Openings
        (
		   id								INT, 
		   Trans_No							VARCHAR(20),
		   Broker_Code						VARCHAR(Max),
		   script_name						VARCHAR(Max),
		   Script_Code						VARCHAR(Max),
		   Family_Name						VARCHAR(Max),
		   Member_Name						VARCHAR(Max),
		   Family_Code						VARCHAR(MAx),
		   Member_Code						VARCHAR(MAx),
		   holding_type						VARCHAR(200),
		   bill_no							VARCHAR(100),		     
           trans_dt							Datetime,
		   qty								FLOAT DEFAULT 0,
		   rate								FLOAT DEFAULT 0,
		   amount							FLOAT DEFAULT 0, 
           isintraday						bit DEFAULT 0, 
		   consultant_name					VARCHAR(Max),
		   BillType							varchar(200)
	   ) 

	   CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
            prioritys INT,
			Trans_No VARCHAR(100),
			id INT,
			ScriptCode VARCHAR(Max), 
			Family_Name VARCHAR(Max),
			Member_Name VARCHAR(Max),
			script_name  VARCHAR(Max),
			holding_type VARCHAR(200),
			flag_script_name  VARCHAR(Max),
			flag_holding_type VARCHAR(200),
            opening_date VARCHAR(50),
		    opening_qty  FLOAT DEFAULT 0,
		    opening_rate  FLOAT DEFAULT 0,
		    opening_amount FLOAT DEFAULT 0, 
            purchase_date VARCHAR(50),
		    purchase_bill_no VARCHAR(100),
		    purchase_qty FLOAT DEFAULT 0,
		    purchase_rate FLOAT DEFAULT 0,
		    purchase_amount FLOAT DEFAULT 0 , 
            sold_date VARCHAR(50),
		    sold_bill_no VARCHAR(100),
		    sold_qty FLOAT DEFAULT 0,
		    sold_rate FLOAT DEFAULT 0,
		    sold_amount FLOAT DEFAULT 0, 
            gain_loss FLOAT DEFAULT 0,
		    gain FLOAT DEFAULT 0,
		    loss FLOAT DEFAULT 0,
		    closing_qty FLOAT DEFAULT 0, 
            closing_rate FLOAT DEFAULT 0,
		    closing_value FLOAT DEFAULT 0,
		    short_term FLOAT DEFAULT 0,
		    long_term FLOAT DEFAULT 0, 
            speculation FLOAT DEFAULT 0, 
		    gain_speculation FLOAT DEFAULT 0,
		    loss_speculation FLOAT DEFAULT 0,
		    consultant_name VARCHAR(Max), 
            nse_rate FLOAT DEFAULT 0,
		    bse_rate FLOAT DEFAULT 0,
		    Other_amt FLOAT DEFAULT 0,
		    ServTax_Amt FLOAT DEFAULT 0,
		    Stt_amt FLOAT DEFAULT 0,
		    sort   VARCHAR(5),
		    isintradaycol  INT 
        ) 

		CREATE TABLE #Members
		(
			Member_Code varchar(MAX)
		)
			
		CREATE TABLE #Family
		(
			Family_Code varchar(MAX)
		)

		DECLARE @tmp VARCHAR(MAX)
				
		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty FLOAT,@rate FLOAT,@amount FLOAT,@ID INT,
		@isIntradayCol_Sold INT,@TransType VARCHAR(100)
		DECLARE @showIntraday INT  ,  @Broker_Code  VARCHAR(MAX)
		DECLARE @tablerowscount INT

      IF(@status = 0) 
			BEGIN
				DECLARE @holding_type VARCHAR(100), @scriptcd VARCHAR(Max), @billno VARCHAR(100), @scriptname VARCHAR(Max),
				@openingDate DATE , @openingRate FLOAT, @openingQty FLOAT, @openingAmount FLOAT,
				@purchaseDate DATE, @PurchaseBillNo  VARCHAR(50), @purchaseRate FLOAT, @purchaseQty FLOAT,@purchaseAmount FLOAT,
				@soldDate DATE, @soldBillNo  VARCHAR(50), @soldRate FLOAT, @soldQty FLOAT, @soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50), @Consultant_Name  VARCHAR(Max), @BillType varchar(20),
				@SoldScriptId VARCHAR(Max), @pendingSoldDate VARCHAR(50), @pendingSoldBillNo VARCHAR(10), @pendingSoldQty FLOAT, @pendingSoldRate FLOAT,
			    @PurchaseIntraFlag VARCHAR(100), @SaleIntraFlag VARCHAR(10) 
				DECLARE @TransTypes VARCHAR(200), @Trans_No VARCHAR(20), @ScriptId  VARCHAR(Max), @Fam_Code VARCHAR(Max), @Mem_Code VARCHAR(Max)
				DECLARE @salecount INT=0, @Boughtcount INT=0, @Flag_Type VARCHAR(20)
				DECLARE @isIntradayCol INT ,@Family_Name VARCHAR(Max),@Member_Name VARCHAR(Max) 
				DECLARE  @COUNT INT = 0
				DECLARE @IDs INT=0
				DECLARE @Flag_Types VARCHAR(10), @Dup_pkid int, @Pkid VARCHAR(MAX), @idcount int  

				---- For Getting SCriptCodes
				CREATE TABLE #SCriptCodes
				(
					ScriptCode varchar(MAX)
				)

				IF(@ScriptCode != '')
					INSERT INTO #SCriptCodes SELECT value FROM Fn_split(@ScriptCode, ',') 
				ELSE 
					INSERT INTO #SCriptCodes select Script_Code from mst_script 
				
				CREATE TABLE #ConsultantCodes
				(
					ConsultantCodes varchar(MAX)
				)
				 
				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes select Consultant_Code from Mst_Consultant						
				
				IF(@memcode = '' AND @familycode != '')
					BEGIN
						INSERT INTO #Members
						SELECT Member_Code 
						FROM Mst_Member WHERE Family_Code IN (SELECT Value FROM membercodestable(@familycode,','))
						SET @tmp = ''
						SELECT @tmp = @tmp + Member_Code + ',' FROM #Members
						SET @memcode = 	IsNULL((select SUBSTRING(@tmp, 0, LEN(@tmp))),'')
					END
				
				ELSE IF(@memcode != '' AND @familycode = '')
					BEGIN
						INSERT INTO #Family
						SELECT Family_Code 
						FROM Mst_Member WHERE Member_Code IN (SELECT Value FROM membercodestable(@memcode,','))
						SET @tmp = ''
						SELECT @tmp = @tmp + Family_Code + ',' FROM #Family
						SET @familycode = 	IsNULL((SELECT SUBSTRING(@tmp, 0, LEN(@tmp))),'')
					END
			 
				SELECT	ROW_NUMBER ( ) OVER (ORDER BY MF.Family_Code,t.Member_Code, t.script_code,t.Ac_Type,t.trans_dt ) AS NameId,
						t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,t.TransType,t.Ac_Type,t.Script_Code,t.Last_Date,t.Qty,t.Rate,
						t.Member_code,t.YearCode,t.Consultant_code,t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,t.Exp_Rate,t.FrmNm,t.ID,
						Ms.bse_code,Ms.nse_code,Ms.script_name,UPPER(ma.ac_name) AS 'Holding Type',
						CASE	WHEN TransType	= 'Sold' THEN 'Sold' 
						        WHEN (((t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101))AND t.TransType='Bought') THEN 'Opening'
								WHEN TransType  = 'Bought' AND t.Bill_no = 'Bonus' THEN 'Bonus' 
								WHEN TransType  = 'Bought' AND t.Bill_no ='Rights'THEN 'Rights' 
								WHEN TransType  = 'Bought' AND  t.Bill_no ='Split' THEN 'Split' 
								WHEN TransType  = 'Bought' AND  t.Bill_no ='Transfer' THEN 'Transfer' 								
								WHEN TransType  = 'Bought' AND Frmnm = 'IPO' THEN 'IPO'  
								WHEN t.TransType ='Bought' AND t.Bill_no != 'Opening' THEN 'Bought' 
						END AS 'Flag_Type',
						cm.Consultant_Name,mm.Member_Name,MF.Family_Name,MF.Family_Code,bb.Broker_Code --,t.isstock --,mm.Member_Code
						INTO #alldata 
				FROM brokerbill_trans t 
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN mst_account ma ON t.ac_type = ma.ac_code AND ma.member_code =t .member_code
				LEFT JOIN  Mst_Consultant  cm ON t.Consultant_code = cm.Consultant_code  
				LEFT JOIN Mst_Member MM ON mm.Member_Code=t.Member_code
				LEFT JOIN Mst_Family MF ON MF.Family_Code =MM.Family_Code
				LEFT JOIN brokerbill bb on bb.trans_no = t.Trans_No 
				WHERE  ISNULL(t.isfnobill,0) = @Investmenttype 
				AND t.trans_dt >=  @Fromdate AND t.trans_dt <= @Todate 
				AND t.member_code IN (SELECT value FROM Fn_split(@memcode, ',') )
				AND t.yearcode = @yearcode  
				AND t.Ac_Type =(CASE WHEN  @Ac_Type='0' THEN t.Ac_Type  ELSE  @Ac_Type END)
				AND t.script_code IN (SELECT * FROM #SCriptCodes)
				AND	t.Consultant_code IN (SELECT * FROM #ConsultantCodes)
				AND	t.Member_Code IN (SELECT value FROM Fn_split(@memcode, ',') )
				AND	MF.Family_Code IN (SELECT value FROM Fn_split(@FamilyCode, ',') )
				AND isnull(t.isIntraDay,0) =(CASE WHEN @IsIntraDay=0 THEN  isnull(isIntraDay,0) ELSE @IsIntraDay END) 
				AND t.MergedEntry = 0  AND ISNULL( t.Ref_SrNo,0) != 1
				AND (IsSLBS=0 OR IsSLBS IS NUll) 
				GROUP BY t.Trans_Dt,t.Trans_No,t.Sr_No,t.Bill_no,t.TransType,t.Ac_Type,t.Script_Code,script_name,MF.Family_Code,t.Member_Code, BB.Broker_Code,t.MonthYear,t.Last_Date,t.LotSize,t.Qty,t.LotQty,t.Disp_qty,
				t.Bal_qty,t.G_Rate,t.Brok_Amt,ServTax_Amount,Rate,t.Amount,t.Stt_Amount,t.YearCode,t.Consultant_code,
				t.EntrySource,t.Ref_TransNo,t.Ref_SrNo,t.MergedEntry,t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,t.Brok_PerUnit,t.lockedbymerger,
				t.frac_Qty,t.Org_Trans_No,t.Org_SrNo,t.isDeleteMerger,t.isstock,t.ScripwiseExpense,t.isClient_code,t.isClient_Brokrage,t.c_Qty,t.C_Gross_Rate,
				t.C_Net_Rate,t.C_Amount,t.C_STT,t.C_STax,t.C_MisChg,t.TransactionChg,t.C_StampDuty,t.Exp_Rate,t.PerExp_Unit,t.FrmNm,t.ID,bse_code,nse_code,ma.AC_Name,cm.Consultant_Name,mm.Member_Name,MF.Family_Name--,t.isstock
				ORDER  BY NameId

				DECLARE @ToDATEfORcLOSIng VARCHAR(15) =  CONVERT(Varchar,CONVERT(DATETime,@fROMdATE,101) - 1,101)
				INSERT INTO #Openings
				EXECUTE proc_StockholdingPosition_FamilyWise_Equity 0,@Investmenttype,@Ac_Type,@memcode,@Yearcode,@FromDate,@ToDATEfORcLOSIng,@ScriptCode,@ConsultantCode,@BSE_NSE_Code,@Is_BFCF,'0', '' ,'ClosingStocks',@FamilyCode,1
	
	        --	Select * from #alldata

				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT	*
				FROM #Openings 
				WHERE BillType = 'Opening'
			    UNION ALL
				SELECT id,Trans_No,Broker_Code,script_name,Script_Code,Family_Name,Member_Name,Family_Code, Member_Code ,[holding type],bill_no,CONVERT(DATETIME,trans_dt,101),qty,rate,ISNULL(qty, 0) * ISNULL(rate, 0),ISNULL(isintraday, 0),consultant_name,'Opening'   
				FROM #alldata WHERE  
				Flag_Type = 'Opening'

				--Select * from #Openings

				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No,@Broker_Code, @scriptname,@ScriptId ,@Family_Name,@Member_Name ,@Fam_Code, @Mem_Code,  @holding_type, @billno, @dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@BillType
				WHILE(@@FETCH_STATUS = 0)
					BEGIN

							IF(@Investmenttype=2)
								SET @holding_type='Mutual Fund'
						-- Insert All Openings
							SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId and Member_Name=@Member_Name and Family_Name=@Family_Name)  -- AND ID = @ID)
							SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
							SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
							SET @Dup_pkid = ISNULL(@Dup_pkid,0)
							SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
							SET @Dup_pkid = @Dup_pkid + 1
						 	
							INSERT INTO #mainoutputtable_1_MonthWise   (Dup_pkid, id,Broker_Code,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code,   Trans_No,  Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,consultant_name,Trans_Type) 
							SELECT @Dup_pkid,@ID,@Broker_Code,@ScriptId, @Family_Name,@Member_Name,@Fam_Code,@Mem_Code,  @Trans_No, 'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Consultant_Name,'Opening'
							
							SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
								IF(@idcount>0)
								  BEGIN	
										 UPDATE #mainoutputtable_1_MonthWise SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
								  END

			 			         FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No,@Broker_Code, @scriptname,@ScriptId ,@Family_Name,@Member_Name ,@Fam_Code, @Mem_Code, @holding_type, @billno,      @dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@BillType
			 	    END 

				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 
			
			
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
				Select id, Broker_Code,Script_Code,Family_Code,Family_Name,Member_Code,Member_Name,  Bill_no, BillType, BillType,script_name,holding_type,Trans_No,CONVERT(DATETIME, trans_dt,103), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name
				from #Openings
				WHERE BillType != 'Opening'
				UNION ALL
				SELECT id, Broker_Code,Script_Code,Family_Code,Family_Name,Member_Code,Member_Name,  Bill_no,Flag_Type,TransType,script_name,[holding type],Trans_No,CONVERT(DATETIME, trans_dt,103), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name
				FROM #alldata WHERE  
				(TransType in('Bought','Sold')  AND CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
			
			
				OPEN purchaseANDSaledatacursor 			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Broker_Code,@ScriptId ,@Fam_Code,@Family_Name,@Mem_Code,@Member_Name, @billno,@Flag_Type , @TransType, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
				
				WHILE (@@FETCH_STATUS = 0) 
						BEGIN
					--Select * from #mainoutputtable_1_MonthWise
							if(@Investmenttype=2)
								set @holding_type='Mutual Fund'

							SET @COUNT = 0
							DECLARE @IsOpening INT =0
							DECLARE @prioritysId INT=0
							DECLARE @str VARCHAR(MAX)=''	

							DECLARE @purchase_Op_Qty FLOAT =0
							DECLARE @purchase_Op_Bill VARCHAR(20) = ''
							DECLARE @purchase_Op_Date VARCHAR(20) = ''
							DECLARE @purchase_Op_Rate FLOAT=0
							DECLARE	@PurQTY FLOAT=0
							DECLARE	@BalPurQTY FLOAT=0

							DECLARE @BalSoldQTY FLOAT=0
							DECLARE @Balpurchase_Op_Qty FLOAT=0
							DECLARE @BalOpeningQTY FLOAT=0
							DECLARE	@Sold_Qty FLOAT=0
							DECLARE @tempID int = 0
							
							IF(@isIntradayCol=0)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
										
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #mainoutputtable_1_MonthWise WHERE holding_type = @holding_type AND script_name=@scriptname AND Flag_Type_Sold ='Sold'  and Flag_Type  = 'Sold'  AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=0 AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END) AND Family_Name=@Family_Name AND Member_Name=@Member_Name)
											IF (@COUNT > 0)
												BEGIN
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  Holding_type,scriptcode ,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,* 
													INTO #tempSoldValExists 
													FROM
													#mainoutputtable_1_MonthWise 
													WHERE script_name = @scriptname 
													AND holding_type = @holding_type  
													AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
													AND isintradaycol = 0
													AND Family_Name = @Family_Name 
													AND Member_Name = @Member_Name
													AND ISNULL(sold_qty,0)!=0 
													AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold = 'Sold'  
													AND Flag_Type  = 'Sold'  
													ORDER BY NameId

													--Select * from #tempSoldValExists

													DECLARE @R_Sold_COUNT FLOAT=(SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty FLOAT 
													
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists  ORDER BY Dup_pkid,NameId)
															SET @str = @TransType

															
															SELECT TOP 1	@Sold_Qty		= sold_qty,
																			@soldDate		= sold_date,
																			@soldRate		= sold_Rate,
																			@soldBillNo		= sold_bill_no,
																			@Pkid			= Pkid
																
															FROM #tempSoldValExists
															WHERE id  = @tempSaleID 
															SET @purchase_Op_Qty = @qty

															
															IF(@TransType='Opening')
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise  
																	SET	opening_date	= @dates,
																		opening_rate	= @rate,
																		opening_qty		= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type		= 'Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise  
																	SET	purchase_date		= @dates,
																		purchase_bill_no	= @billno,
																		purchase_rate		= @rate,
																		purchase_qty		= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type			='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(purchase_qty,0)=0 AND pkid = @pkid
																END
															

															IF(@Sold_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise  
																	SET sold_qty	=	@purchase_Op_Qty 
																	WHERE Flag_Type_Sold='Sold' AND   id = @tempSaleID  AND Pkid=@Pkid
																END

															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND Pkid=@Pkid
															SET @tablerowscount=(  SELECT COUNT(*) FROM  #tempSoldValExists )
															DECLARE @Balancedval   FLOAT = Round((ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)),6)

															IF(@Balancedval  < 0)
																BEGIN
																	--SET @Pkid		  = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId and holding_type=@holding_type and Member_Name=@Member_Name and Family_Name=@Family_Name)
																	SET @Dup_pkid	  = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid	  = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid	  = ISNULL(@Dup_pkid,0)
																	SET @idcount	  = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid	  = @Dup_pkid + 1
																
																	SET @soldQty	  = ABS(@Balancedval) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise) 
																	SET @prioritysId = ISNULL(@prioritysId,0) + 1

																	INSERT INTO #mainoutputtable_1_MonthWise(Dup_pkid, Broker_Code,ID,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code, Trans_No, Flag_Type,Flag_Type_Sold,prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name,Trans_Type)
																	VALUES(@Dup_pkid,@Broker_Code, @tempSaleID , @ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Sold','sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name,'sold')
																	
																	UPDATE #mainoutputtable_1_MonthWise 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID <> @tempSaleID 

																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
																		IF(@idcount>0)
																		  BEGIN	
																				UPDATE #mainoutputtable_1_MonthWise 
																				SET Dup_pkid = Dup_pkid + 1 
																				WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		  END
																		  SET @Balancedval = 0
																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
																BEGIN
																	--SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId  and holding_type=@holding_type and Member_Name=@Member_Name and Family_Name=@Family_Name)
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId and  Member_Name=@Member_Name and Family_Name=@Family_Name)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId = (SELECT MAX(prioritys+1) FROM #mainoutputtable_1_MonthWise)
																	IF(@TransType='Opening')
																		BEGIN
																			INSERT INTO #mainoutputtable_1_MonthWise(Dup_pkid ,Broker_Code,ID,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name,Trans_Type)
																			VALUES(@Dup_pkid, @Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)

																			UPDATE #mainoutputtable_1_MonthWise 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 

																		END
																	ELSE if(@TransType='Bought')
																		BEGIN
																			INSERT INTO #mainoutputtable_1_MonthWise(Dup_pkid,Broker_Code, ID,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																			VALUES(@Dup_pkid, @Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)

																			UPDATE #mainoutputtable_1_MonthWise 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
															
																		SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
																		IF(@idcount>0)
																			BEGIN	
																				UPDATE #mainoutputtable_1_MonthWise 
																				SET Dup_pkid = Dup_pkid + 1
																				WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																			END
																		END
																	ELSE IF(@Balancedval=0)
																		BEGIN
																			break;
																		ENd	
																	SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
																	SET @qty = @Balancedval
														END
												

													DROP TABLE #tempSoldValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													--SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise)
													--SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1_MonthWise)
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise)
													SET @Dup_pkid =(select isnull(max(Dup_pkid),0)+1 from #mainoutputtable_1_MonthWise)
												 
													INSERT INTO #mainoutputtable_1_MonthWise (id,Broker_Code,ScriptCode,Dup_pkId, Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name,Trans_Type) 
													VALUES ( @ID, @Broker_Code,@ScriptId,@Dup_pkid,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name,@Flag_Type) 
												END
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */

											SET @COUNT = (SELECT Count(*) FROM #mainoutputtable_1_MonthWise WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split') AND ISNULL(sold_qty,0)=0  AND isintradaycol=0 AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END) AND Family_Name=@Family_Name AND Member_Name=@Member_Name)
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, Holding_type,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,* 
													INTO #tempValExists 
													FROM
													#mainoutputtable_1_MonthWise WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split') 
													--AND consultant_name= @Consultant_Name
													AND (consultant_name = CASE WHEN  @ConsultantCode <> '' THEN  @Consultant_Name ELSE consultant_name END)
												    AND ISNULL(sold_qty,0)=0  AND isintradaycol=0 
													AND Family_Name=@Family_Name AND Member_Name=@Member_Name
													order by NameId
													
													DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty FLOAT 
													
													WHILE(@RCOUNT > 0)
														BEGIN 
															SET @Sold_Qty= @qty
															SET @tempID = (Select top(1) id from #tempValExists  ORDER BY Dup_pkid)
															SET @str = (Select top(1) Flag_Type From #tempValExists Where id  = @tempID)
														
															IF(@str='Opening')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= opening_qty,
																					@openingDate	= opening_date,
																					@openingrate	= opening_rate,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID

																END
															ELSE IF(@str='Bought')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= purchase_qty,
																					@PurchaseDate	= purchase_date,
																					@Purchaserate	= purchase_rate,
																					@PurchaseBillNo = purchase_bill_no,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID

																END
															    
															IF(@Sold_Qty > 0)
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise  
																		SET	
																			opening_qty = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							END,
																			purchase_qty  = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							END,
																			sold_date	  = @dates,
																			sold_bill_no  = @billno,
																			sold_rate     = @rate,
																			sold_qty      = CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold='Sold'
																	WHERE  id = @tempID and ISNULL(sold_qty,0)= 0 AND Pkid = @Pkid
																	SET @Balanceval = Round((ABS(@Sold_Qty) - ABS(@TempSoldQty)),6)
																END
															
														DELETE FROM #tempValExists WHERE id = @tempID AND Pkid=@Pkid
														SET @tablerowscount = (SELECT COUNT(*) FROM  #tempValExists )
														SET @RCOUNT = @RCOUNT - 1
														
														 
													
													IF(@Balanceval  < 0)
														BEGIN
															--SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId and holding_type=@holding_type and Member_Name=@Member_Name and Family_Name=@Family_Name)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															--SET @prioritysId  =(SELECT MAX(isnull(prioritys,0)) + 1 FROM #mainoutputtable_1_MonthWise) 

															IF(@str='Opening')
																BEGIN
																	SET @openingQty=ABS(@Balanceval) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1

																	INSERT INTO #mainoutputtable_1_MonthWise(Dup_pkid,Broker_Code, ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@Dup_pkid,@Broker_Code,@tempID,@ScriptId, @Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name,@Flag_Type)

																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	UPDATE #mainoutputtable_1_MonthWise 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys >= @prioritysId AND ID <> @tempID
																END
															ELSE 
																BEGIN
																	SET @PurchaseQty=ABS(@Sold_Qty) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	INSERT INTO #mainoutputtable_1_MonthWise(Dup_pkid,Broker_Code,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@Dup_pkid,@Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	
																	SET @prioritysId = ISNULL(@prioritysId,0)+1

																	UPDATE #mainoutputtable_1_MonthWise 
																	SET prioritys=@prioritysId  
																	WHERE prioritys > @prioritysId AND ID<>@tempID
																END
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
																IF(@idcount>0)
																	BEGIN	
																		UPDATE #mainoutputtable_1_MonthWise 
																		SET Dup_pkid = Dup_pkid + 1 
																		WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																	END
																SET @Balanceval = 0
																break;
														END
													ELSE IF(@Balanceval  > 0 AND @tablerowscount = 0)
														BEGIN
															--SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId and holding_type=@holding_type and Member_Name=@Member_Name and Family_Name=@Family_Name)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															SET @prioritysId  =(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise)

															INSERT INTO #mainoutputtable_1_MonthWise(Dup_pkid,Broker_Code,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
															VALUES(@Dup_pkid,@Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)

															UPDATE #mainoutputtable_1_MonthWise 
															SET		prioritys	=	@prioritysId+1  
															WHERE	prioritys > @prioritysId AND ID<>@tempSaleID 
															
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
															IF(@idcount>0)
																BEGIN	
																	UPDATE #mainoutputtable_1_MonthWise 
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
														ENd
													ELSE IF(ISNULL(@Balanceval,0) =0)
														BEGIN
															SET @Balanceval=0
															BREAK;
														END
														SET @qty = @Balanceval
													END
													DROP TABLE #tempValExists
												END
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													--SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #mainoutputtable_1_MonthWise)
													--SET @prioritysId = ISNULL(@prioritysId,0)+1
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise)
													SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0)+1 from #mainoutputtable_1_MonthWise)

													INSERT INTO #mainoutputtable_1_MonthWise(Dup_pkid,Broker_Code, ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
													VALUES(@Dup_pkid,@Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No,  'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
												END
											SET @purchase_Op_Date = ''
											SET @purchase_Op_Rate = ''
											SET @purchase_Op_Qty  = ''
											SET @purchase_Op_Bill = ''
										END
								END
							ELSE IF(@isIntradayCol=1)
								 BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
										
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, Holding_type,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
											* INTO #tempBought 
											FROM
											#mainoutputtable_1_MonthWise 
											WHERE isintradaycol		=	1 
											AND script_name			=	@scriptname 
											AND holding_type		=	@holding_type  
											AND Flag_Type_Sold		=  'Sold'
											AND Flag_Type			=  'Sold'  
											AND consultant_name		=   @Consultant_Name 
											AND Family_Name			=   @Family_Name 
											AND Member_Name			=	@Member_Name
											AND ISNULL(sold_qty,0) !=0  AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
											ORDER BY NameId
											IF ((Select Count(*) from #tempBought ) > 0)
												BEGIN
													DECLARE @Bought_COUNT INT = ( SELECT COUNT(*) FROM #tempBought )
													DECLARE @Temppurchase_Qty FLOAT 
													SET @purchase_Op_Qty = @qty
													DECLARE @Balance_val FLOAT
													WHILE(@Bought_COUNT  > 0)
														BEGIN 
															DECLARE @tempSale_ID INT = (SELECT TOP(1) id FROM #tempBought ORDER BY Dup_pkid)
															SET @str=@TransType
													
															SELECT	@Temppurchase_Qty		= sold_qty,
																	@soldDate				= sold_date,
																	@soldRate				= sold_rate,
																	@soldBillNo				= sold_bill_no,
																	@pkid					= pkid
															FROM #tempBought 
															WHERE id  = @tempSale_ID 
															SET @Sold_Qty= ABS(@Temppurchase_Qty)
															IF(@TransType='Bought')
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise  
																	SET	purchase_date		=	@dates,
																		purchase_bill_no	=	@billno,
																		purchase_rate		=	@rate,
																		purchase_qty		=	CASE	WHEN @Temppurchase_Qty > @purchase_Op_Qty 
																										THEN ABS(@purchase_Op_Qty) 
																										ELSE ABS(@Temppurchase_Qty) 
																								END,
																		Flag_Type			=	'Bought'
																	WHERE  id = @tempSale_ID  and pkid=@pkid
																END
															IF(@Temppurchase_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise  
																	SET sold_qty = ABS(@purchase_Op_Qty) 
																	WHERE Flag_Type_Sold = 'Sold' 
																	AND   id = @tempSale_ID   and pkid=@pkid
																END
															
															DELETE FROM #tempBought  WHERE id = @tempSale_ID 
															
															SET @Balance_val = Round((isnull(@purchase_Op_Qty,0) - (@Sold_Qty)),6)
															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempBought)
															SET @Bought_COUNT  = @Bought_COUNT  - 1
															SET @qty = @Balance_val

															IF(@Balance_val  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty = ABS(@Balance_val) 
																	SET @prioritysId  =(SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise )
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	INSERT INTO #mainoutputtable_1_MonthWise( Dup_pkid,Broker_Code,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code, Trans_No, Flag_Type,Flag_Type_sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@Dup_pkid,@Broker_Code,@tempSale_ID ,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balance_val),@soldRate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	
																	UPDATE #mainoutputtable_1_MonthWise 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys >= @prioritysId AND ID<>@tempSale_ID 
																	
																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
																	IF(@idcount>0)
																		BEGIN	
																			UPDATE #mainoutputtable_1_MonthWise 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																	BREAK;
																END
															ELSE IF(@Balance_val  > 0 AND @tablerowscount = 0)
																BEGIN
																if(@TransType='Bought')
																	BEGIN
																			SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																			SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																			SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																			SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																			SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																			SET @Dup_pkid = @Dup_pkid + 1

																			SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #mainoutputtable_1_MonthWise)
																	
																		INSERT INTO #mainoutputtable_1_MonthWise(Dup_pkid,Broker_Code,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																		VALUES(@Dup_pkid,@Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balance_val)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)

																		UPDATE #mainoutputtable_1_MonthWise 
																		SET prioritys=@prioritysId+1  
																		WHERE prioritys > @prioritysId AND ID<>@tempSaleID 

																		SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
																			IF(@idcount>0)
																				BEGIN
																					UPDATE #mainoutputtable_1_MonthWise 
																					SET Dup_pkid = Dup_pkid + 1 
																					WHERE  Dup_pkid >= @Dup_pkid and   
																					CONVERT(VARCHAR(200),pkid) NOT IN ( SELECT value FROM Fn_split(@Pkid, ',') ) 
																				END
																	END
																ENd
															SET @purchase_Op_Qty = @Balance_val
														END

													
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise)
													SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0) + 1 from #mainoutputtable_1_MonthWise)
									
													INSERT INTO #mainoutputtable_1_MonthWise (Dup_pkid,Broker_Code,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name,Trans_Type) 
													VALUES ( @Dup_pkid,@Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name,@Flag_Type) 
												END
											DROP TABLE #tempBought
										END	

									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Enry Already if Purchase or Opening Exists with Same Script And Holding Type */
											DECLARE @Balanceval_sold FLOAT
											SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, Holding_type,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
											* 
											INTO #tempValExists_intraBought 
											FROM #mainoutputtable_1_MonthWise 
											WHERE isintradaycol		=	1
											AND holding_type		=	@holding_type 
											AND script_name			=	@scriptname 
											AND Flag_Type			IN	('Bought','Rights','Bonus','Ipo','Opening','Transfer') 
											AND Consultant_Name		=	@Consultant_Name
											AND Family_Name			=	@Family_Name 
											AND Member_Name			=	@Member_Name
											AND ISNULL(sold_qty,0)=0  
											order by NameId 

											IF ((Select Count(*) from #tempValExists_intraBought) > 0)
												BEGIN
													DECLARE @RCOUNT_intraBought INT=(SELECT COUNT(*) FROM #tempValExists_intraBought)
													DECLARE @TempSoldQty_intra FLOAT
													
													WHILE(@RCOUNT_intraBought > 0)
														BEGIN 
															SET @Sold_Qty= @qty
															DECLARE @tempID_intraBought INT = (SELECT TOP(1) id FROM #tempValExists_intraBought)
															SET @str	= (SELECT TOP(1) Flag_Type From #tempValExists_intraBought WHERE id  = @tempID_intraBought ORDER BY Dup_pkid,NameId)
															SET @pkid   =   (SELECT TOP(1) pkid  FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought )
															 
															 
																IF(@str ='Bought')
																BEGIN
																	SELECT	@TempSoldQty_intra	=	purchase_qty,
																			@PurchaseDate		=	purchase_date,
																			@Purchaserate		=	purchase_rate,
																			@PurchaseBillNo		=	purchase_bill_no
																	FROM #tempValExists_intraBought 
																	WHERE id  = @tempID_intraBought 
																END
															IF(@Sold_Qty > 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																		UPDATE #mainoutputtable_1_MonthWise  
																		SET	
																			purchase_qty  = CASE WHEN @str ='Bought'
																								 THEN CASE	WHEN  @TempSoldQty_intra >= @Sold_Qty 
																											THEN @Sold_Qty 
																											ELSE @TempSoldQty_intra 
																								      END
																							 END,
																			sold_date      = @dates,
																			sold_bill_no   = @billno,
																			sold_rate      = @rate,
																			sold_qty       = CASE WHEN @TempSoldQty_intra > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty_intra END,
																			Flag_Type_Sold = 'Sold',
																			prioritys      = @prioritysId
																	WHERE  id = @tempID_intraBought and ISNULL(sold_qty,0)=0 AND pkid = @pkid

																	SET @Balanceval_sold = Round((ABS(@Sold_Qty) - ABS(@TempSoldQty_intra)),6)
																END

															DELETE FROM #tempValExists_intraBought WHERE id = @tempID_intraBought

															SET @RCOUNT_intraBought = @RCOUNT_intraBought - 1
															
															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempValExists_intraBought )
															IF(@Balanceval_sold  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @PurchaseQty=ABS(@Sold_Qty) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1

																	INSERT INTO #mainoutputtable_1_MonthWise(ID,Broker_Code,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@tempID_intraBought,@Broker_Code,@scriptId ,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval_sold)  ,@Purchaserate,@isIntradayCol,@Consultant_Name,@Flag_Type)

																	UPDATE #mainoutputtable_1_MonthWise 
																	SET prioritys=@prioritysId  
																	WHERE prioritys > @prioritysId AND ID <> @tempID_intraBought
																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
																		IF(@idcount>0)
																			BEGIN	
																				UPDATE #mainoutputtable_1_MonthWise 
																				SET Dup_pkid = Dup_pkid + 1 
																				WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																			END

																	BREAK;
																END
															ELSE IF(@Balanceval_sold  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE ScriptCode = @ScriptId and holding_type=@holding_type and Member_Name=@Member_Name and Family_Name=@Family_Name)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #mainoutputtable_1_MonthWise)
																	
																	INSERT INTO #mainoutputtable_1_MonthWise(Dup_pkid ,Broker_Code,ScriptCode,ID,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@Dup_pkid ,@Broker_Code,@scriptId,@ID,@Family_Name,@Member_Name,@Fam_Code,@Mem_Code,@Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval_sold)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)

																	UPDATE #mainoutputtable_1_MonthWise 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID <> @tempID_intraBought 
																	

																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
																	IF(@idcount>0)
																		BEGIN	
																			UPDATE #mainoutputtable_1_MonthWise 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END

																END
															SET @qty=@Balanceval_sold
														END
													

													
												END
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise)
													SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0) +1 from #mainoutputtable_1_MonthWise)

													INSERT INTO #mainoutputtable_1_MonthWise(Dup_pkid ,Broker_Code,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
													VALUES(@Dup_pkid ,@Broker_Code,@ID,@ScriptId,@Family_Name,@Member_Name, @Fam_Code,@Mem_Code,@Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
												END
											SET @purchase_Op_Date	=	''
											SET @purchase_Op_Rate   =	''
											SET @purchase_Op_Qty	=	''
											SET @purchase_Op_Bill	=	''
											DROP TABLE #tempValExists_intraBought
										END
								END
								FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Broker_Code,@ScriptId ,@Fam_Code,@Family_Name,@Mem_Code,@Member_Name, @billno,@Flag_Type , @TransType, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
							--FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@ScriptId ,@Family_Name,@Member_Name,@billno,@Flag_Type , @TransType, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
						END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 
		 
		IF(@IsBSEISIN =1)
	    BEGIN
		
		     INSERT INTO #mainouttable_1_Monthwise_BSEISINO 
			 SELECT mab.pkid,mab.Dup_pkid,mab.Family_Name,mab.Member_Name,mab.Family_Code,mab.Member_Code,mab.Trans_No,mab.id,mab.prioritys,mab.Trans_Type,mab.Split_Type,mab.Flag_Type,mab.Flag_Type_Sold, 
			        mab.flag_script_name, mab.flag_holding_type,
					mab.script_name + '[' +ms.BSE_Code + ']' + '[' +ms.ISIN_No+ ']',mab.holding_type,mab.opening_bill_no ,mab.opening_date,mab.opening_qty,mab.opening_rate,
					mab.opening_amount,mab.purchase_date,mab.purchase_bill_no,mab.purchase_qty,mab.purchase_rate,mab.purchase_amount,mab.sold_date ,mab.sold_bill_no,mab.sold_qty,
					mab.sold_rate,mab.sold_amount,mab.gain_loss,mab.closing_qty,mab.closing_rate,mab.closing_value,mab.short_term,mab.long_term,mab.speculation,mab.gain_speculation,
					mab.loss_speculation,mab.consultant_name,mab.nse_rate,mab.bse_rate,mab.dayscount,mab.isintradaycol,mab.[type],mab.ScriptCode,mab.Broker_Code 
					from #mainoutputtable_1_MonthWise mab
					INNER JOIN Mst_Script Ms On  mab.ScriptCode=Ms.Script_Code
		END
		ELSE if(@IsBSEISIN=0)
		BEGIN		
		     INSERT INTO #mainouttable_1_Monthwise_BSEISINO 
			 SELECT mab.pkid,mab.Dup_pkid,mab.Family_Name,mab.Member_Name,mab.Family_Code,mab.Member_Code,mab.Trans_No,mab.id,mab.prioritys,mab.Trans_Type,mab.Split_Type,mab.Flag_Type,mab.Flag_Type_Sold, 
			        mab.flag_script_name, mab.flag_holding_type,
					mab.script_name,mab.holding_type,mab.opening_bill_no ,mab.opening_date,mab.opening_qty,mab.opening_rate,
					mab.opening_amount,mab.purchase_date,mab.purchase_bill_no,mab.purchase_qty,mab.purchase_rate,mab.purchase_amount,mab.sold_date ,mab.sold_bill_no,mab.sold_qty,
					mab.sold_rate,mab.sold_amount,mab.gain_loss,mab.closing_qty,mab.closing_rate,mab.closing_value,mab.short_term,mab.long_term,mab.speculation,mab.gain_speculation,
					mab.loss_speculation,mab.consultant_name,mab.nse_rate,mab.bse_rate,mab.dayscount,mab.isintradaycol,mab.[type],mab.ScriptCode,mab.Broker_Code 
					from #mainoutputtable_1_MonthWise mab 				
		END
	
		IF(@IsIntraDay = 0 AND @short_Long_Term != 0  )
			BEGIN
				IF(@short_Long_Term = 1)  -- Long Term
					BEGIN
						INSERT INTO #mainoutputtable_1_Final_MonthWise (OrderBy, opening_bill_no,id,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss  ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type])

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						CASE WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN   CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
							 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId, opening_bill_no,id,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						 Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						0,
						Round(ISNULL( CASE	WHEN   isintradaycol = 0 and opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
											WHEN   isintradaycol = 0 and purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4),
						0,
						0,
						0,consultant_name,nse_rate,bse_rate,1 sort ,isintradaycol,Trans_Type
						FROM #mainouttable_1_Monthwise_BSEISINO 
						WHERE ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
									(
										DATEDIFF(DAY,CONVERT(DATETIME,opening_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) > 365 
									)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									(
										DATEDIFF(DAY,CONVERT(DATETIME, purchase_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) > 365
									)
								)
							)
							order by NameId
					END

				ELSE If(@short_Long_Term = 2)  -- Short Term
					BEGIN

						INSERT INTO #mainoutputtable_1_Final_MonthWise (OrderBy, opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type])

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  Family_Name,Family_Code,Member_Name,Member_Code,consultant_name,holding_type,ScriptCode,script_name,--pkid,
						case WHEN  Dup_pkid is Null Then Pkid
							 WHEN  Dup_pkid is NOt Null then Dup_pkid 
							 else Dup_pkid end,prioritys, 
						case when CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
						else CONVERT(DATE,purchase_date,103) END,
						prioritys DESC, sold_date DESC ) AS NameId,
						opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4) as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						Round(ISNULL(
								CASE	WHEN   isintradaycol = 0 and opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN    isintradaycol = 0 and purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4) ,
						0,
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,Trans_Type 
						FROM #mainouttable_1_Monthwise_BSEISINO 
						WHERE  ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
										(		
											DATEDIFF(DAY,CONVERT(DATETIME,opening_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) <= 365 
										)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									  (		
										DATEDIFF(DAY,CONVERT(DATETIME, purchase_date,103),CONVERT(DATETIME,ISNULL(sold_date,0),103)) <= 365
									  )
								)
							)
						order by NameId
					END

				ELSE If(@short_Long_Term = 4)  -- Short Term + Long Term
					BEGIN
						INSERT INTO #mainoutputtable_1_Final_MonthWise (OrderBy, opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type])

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						
						opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) <= 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) <= 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						(CASE  WHEN   isintradaycol = 0 and ( (ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
								    (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
							  THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						(CASE WHEN  isintradaycol = 0 and ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365) OR
								   (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365))  
							  THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <=365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,Trans_Type 
						FROM #mainouttable_1_Monthwise_BSEISINO 
						WHERE  ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						order by NameId
					END

			END

		ELSE If(@short_Long_Term = 3 AND @IsIntraDay = 1 )  -- Only Speculation
			BEGIN
				INSERT INTO #mainoutputtable_1_Final_MonthWise (OrderBy, opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss  ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type])

				SELECT ROW_NUMBER ( ) OVER (ORDER BY  case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END,  ScriptCode,holding_type desc)  AS NameId,
				opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type,opening_date,
				ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),purchase_date,ISNULL(purchase_bill_no,0),
				ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,sold_date ,sold_bill_no ,isnull(sold_qty,0) ,
				ISNULL(sold_rate,0),ISNULL(sold_amount,0) , 
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4) as gain_loss,

				closing_qty ,closing_rate ,closing_value ,
				0,
				0,
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4) ,
				0,
				0,consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,Trans_Type 
				FROM #mainouttable_1_Monthwise_BSEISINO 
				WHERE  (ISNULL(closing_qty,0) = 0)  AND (ISNULL(isintradaycol,0)=1) AND (ISNULL(purchase_qty,0)! = 0 AND  ISNULL(sold_qty,0) ! = 0) 
				order by NameId
			END

		ELSE
			BEGIN
			        --Select * from #mainoutputtable_1_MonthWise
			  
				INSERT INTO #mainoutputtable_1_Final_MonthWise (OrderBy,   opening_bill_no, Broker_Code,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss , closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type])

				SELECT 
				ROW_NUMBER ( ) OVER (ORDER BY  Family_Name,Family_Code,Member_Name,Member_Code,consultant_name,holding_type,ScriptCode,script_name,--pkid,
			    case WHEN  Dup_pkid is Null Then Pkid
				     WHEN  Dup_pkid is NOt Null then Dup_pkid 
				     else Dup_pkid end,prioritys, 
				case when CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
				else CONVERT(DATE,purchase_date,103) END,
				prioritys DESC, sold_date DESC ) AS NameId,
				 opening_bill_no,Broker_Code,
				id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code,Trans_No, prioritys,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,
				  Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) <= 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN isintradaycol = 0 AND  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365)     -- short term for openings
						THEN  ISNULL(sold_rate ,0)* ISNULL(sold_qty ,0)- ISNULL(opening_rate,0)*ISNULL(opening_qty ,0)
					 WHEN isintradaycol = 0 AND (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365)  -- short term for purchase
						THEN  ISNULL(sold_rate ,0)* ISNULL(sold_qty ,0)- ISNULL(purchase_rate,0)*ISNULL(purchase_qty ,0)
					 ELSE 0.0 END,

						
				CASE WHEN  isintradaycol = 0 and ((opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)     -- long term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365))						 -- long term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  isintradaycol = 1 AND (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,Trans_Type 
				FROM #mainouttable_1_Monthwise_BSEISINO 
				order by NameId
			END
		 
			UPDATE #mainoutputtable_1_Final_MonthWise SET prioritys=0
			DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final_MonthWise)
			UPDATE #mainoutputtable_1_Final_MonthWise
			SET prioritys  = @i , @i = @i + 1

		IF(@OUTPUT_Flag='Details')
			BEGIN
			IF(@Investmenttype != 2)
				BEGIN
					IF(@ConsultantCode !='')
						BEGIN
							SELECT id,prioritys,ScriptCode, Family_Name,Member_Name,script_name 'Script Name',Holding_Type,opening_bill_no,
							CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
							CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
							CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',
							ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',ISNULL(gain_loss,0) 'Gain/Loss',
							CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
							ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
							ISNULL(short_term,0) short_term,ISNULL(long_term,0) long_term,ISNULL(speculation,0) speculation,
							CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
							CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
							consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,ISNULL(isintradaycol,0),1 sort,[type] 
							FROM #mainoutputtable_1_Final_MonthWise
							WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)   
							ORDER By   consultant_name, script_name,Holding_Type
						END
					ELSE
						BEGIN
							SELECT id,prioritys,ScriptCode, Family_Name,Member_Name,script_name 'Script Name',Holding_Type,opening_bill_no,
							CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
							CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
							CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
							ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
							ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
							ISNULL(short_term,0) short_term,ISNULL(long_term,0) long_term,ISNULL(speculation,0) speculation,
							CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE 0 END gain_speculation,
							CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE 0 END loss_speculation,
							consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,isintradaycol,1 sort,[type] 
							FROM #mainoutputtable_1_Final_MonthWise
							WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
							ORDER By  Family_Name, Member_Name,Holding_Type, script_name, consultant_name--,CONVERT(date, purchase_date,103) 

				
						END
				END
			ELSE
				IF(@ConsultantCode!='')
					BEGIN
						SELECT id,prioritys,ScriptCode, Family_Name,Member_Name,script_name 'Script Name',Holding_Type,opening_bill_no,
						CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty ,0)'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
						ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,
						ISNULL(long_term,0)long_term,
						ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,isintradaycol,1 sort,[type] 
						FROM #mainoutputtable_1_Final_MonthWise
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0) 
						ORDER By  consultant_name,  sort,Family_Name,  Member_Name ,script_name
					END
				ELSE
					BEGIN
						select * from (
						SELECT id,prioritys,ScriptCode, Family_Name,Member_Name,script_name 'Script Name',Holding_Type,opening_bill_no,
						CONVERT(DATE, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(DATE, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(DATE, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',
						CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
						ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,isintradaycol,1 sort,[type] 
						FROM #mainoutputtable_1_Final_MonthWise
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
						 
						) T
						ORDER By   T.sort,T.Family_Name,  T.Member_Name ,T.consultant_name,T.[script name]
					 											
					END
			END

		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
			 --select * FROM #mainoutputtable_1_Final_MonthWise
				IF(@ConsultantCode !='')
					BEGIN
						
						SELECT  '' Opening_bill_no,0 id ,  0 prioritys, ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code, script_name 'Script Name',  Holding_Type,
						NULL 'Opening Date', 
						SUM(ISNULL(opening_qty,0)) 'Opening Qty',
						ISNULL((ISNULL(SUM(ISNULL(opening_amount,0)),0)  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate', 
					    SUM(ISNULL(opening_amount,0)) 'Opening Amount',
						NULL 'Purchase Date','' 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty',
					    ISNULL((ISNULL(SUM(purchase_amount),0)  / SUM(NULLIF(purchase_qty,0))),0)  'Purchase Rate',
						 SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
						NULL 'Sold Date', '' 'Sold BillNo', SUM(ISNULL(sold_qty,0)) 'Sold Qty',  
						CASE WHEN SUM(sold_qty) != 0
					    THEN SUM(sold_amount)/nullif(SUM(sold_qty),0)   
					    ELSE 0
				        END  'Sold Rate',
						SUM(ISNULL(sold_amount,0)) 'Sold Amount',
						SUM(ISNULL(gain_loss ,0)) 'Gain/Loss',
						 SUM(ISNULL(gain,0))  'Gain', 
						SUM(ISNULL(loss,0))  'Loss',
						
						SUM(ISNULL(closing_qty,0))  'Closing Qty',
						CASE WHEN SUM(closing_qty) != 0
					    THEN (SUM(closing_value) / SUM(NULLIF(closing_qty,0))) 
					    ELSE 0
				        END  'Closing Rate',
						
						SUM(ISNULL(closing_qty,0))  'Closing Qty',
						CASE WHEN SUM(closing_qty) != 0
							THEN SUM(ISNULL(closing_value,0))   
					    ELSE 0
				        END  'Closing Value', 
						SUM(ISNULL(short_term,0))  short_term,
						SUM(ISNULL(long_term,0))  long_term,
						SUM(ISNULL(speculation,0))speculation,
					    SUM(gain_speculation)gain_speculation,
						SUM(ISNULL(loss_speculation,0))loss_speculation,  consultant_name,0 nse_rate,0 bse_rate,1 sort --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
						FROM
							(
								SELECT '' Opening_bill_no,MAX(id+0)id ,MAX (prioritys+0) prioritys,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code, script_name  , Holding_Type,
								NULL 'Opening Date',
								SUM(isNull(opening_qty,0)) 'Opening_Qty',
								sum(isNull(opening_rate,0)) 'opening_rate' ,
								SUM(isNull(opening_amount,0)) 'Opening_Amount',
								NULL 'Purchase Date',purchase_bill_no,
								SUM(isNull(purchase_qty,0)) 'Purchase_Qty', 
								SUM(isnull(purchase_rate,0)) 'purchase_rate',
								SUM(isNull(purchase_amount,0)) 'Purchase_Amount',
								NULL 'Sold Date',sold_bill_no ,
								SUM(isNull(sold_qty,0)) 'Sold_Qty', 
								SUM(isNull(sold_rate,0))'sold_rate'  ,
								SUM(isNull(sold_amount,0)) 'Sold_Amount',
								SUM(isNull(gain_loss,0)) 'Gain_Loss',
								SUM(isNull(gain,0)) 'Gain',
								SUM(isNull(loss,0)) 'Loss',
								SUM(isNull(closing_qty,0)) 'Closing_Qty',

							--	SUM(isNULL(closing_rate,0)) 'Closing_Rate',
						    	(SUM(ISNULL(closing_value,0)) / SUM(NULLIF(closing_qty,0))) 'Closing_Rate',

								SUM(isNull(closing_value,0)) 'Closing_Value',
								SUM(isNull(short_term,0)) 'short_term',
								SUM(isNull(long_term,0)) 'long_term',
								SUM(isNull(speculation,0)) 'speculation',
								SUM(isNull(gain_speculation,0)) gain_speculation,
								SUM(isnull(loss_speculation,0)) loss_speculation,  consultant_name,0 nse_rate,0 bse_rate,1 sort,'' broker_code--,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
								FROM #mainoutputtable_1_Final_MonthWise 
								GROUP BY  Family_Name,Family_Code,Member_Name,Member_Code,consultant_name,ScriptCode,script_name,Holding_Type,purchase_bill_no,sold_bill_no 
							)a
						GROUP BY   Family_Name,Family_Code,Member_Name,Member_Code,consultant_name,Holding_Type,script_name  ,ScriptCode
						ORDER BY   consultant_name,Family_Name,Family_Code,Member_Name,Member_Code , 	 Holding_Type, script_name,ScriptCode -- else
					 END
				ELSE
					BEGIN
						SELECT  '' Opening_bill_no,0 id ,  0 prioritys, ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code, script_name 'Script Name',  Holding_Type,
						NULL 'Opening Date',
						SUM(ISNULL(opening_qty,0)) 'Opening Qty',   ISNULL((ISNULL(SUM(ISNULL(opening_amount,0)),0)  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate',
						SUM(ISNULL(opening_amount,0)) 'Opening Amount',
						NULL 'Purchase Date',MAX(purchase_bill_no) 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty', ISNULL((ISNULL(SUM(purchase_amount),0)  / 
						SUM(NULLIF(purchase_qty,0))),0)  'Purchase Rate',
						SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
						NULL 'Sold Date', MAX(sold_bill_no) 'Sold BillNo',
						SUM(ISNULL(sold_qty,0)) 'Sold Qty',   ISNULL((ISNULL(SUM(sold_amount),0) / NULLIF (SUM(ISNULL(sold_qty,0)),0)),0)'Sold Rate',
						SUM(ISNULL(sold_amount,0)) 'Sold Amount',
						SUM(ISNULL(gain_loss ,0)) 'Gain/Loss', 
						SUM(ISNULL(gain,0))  'Gain', 
						SUM(ISNULL(loss,0))  'Loss',
						SUM(ISNULL(closing_qty,0))  'Closing Qty',
						ISNULL((ISNULL(SUM(ISNULL(closing_value,0)),0) / NULLIF(SUM(ISNULL(closing_qty,0)),0)),0)   'Closing Rate', 
						CASE WHEN SUM(closing_qty) != 0
							THEN SUM(ISNULL(closing_value,0))   
					    ELSE 0
				        END  'Closing Value', 
						SUM(ISNULL(short_term,0))  short_term,
						SUM(ISNULL(long_term,0))  long_term,
						SUM(ISNULL(speculation,0))speculation, 
						SUM(ISNULL(gain_speculation,0))gain_speculation,
						SUM(ISNULL(loss_speculation,0))loss_speculation,  consultant_name,0 nse_rate,0 bse_rate,1 sort,''   broker_code  
						FROM
							(
								SELECT '' Opening_bill_no,MAX(id+0)id ,MAX (prioritys+0) prioritys,ScriptCode, Family_Name,Member_Name,Family_Code,Member_Code, script_name  , Holding_Type,
								NULL 'Opening Date',
								SUM(isNull(opening_qty,0)) 'Opening_Qty',
								sum(isNull(opening_rate,0)) opening_rate ,
								SUM(isNull(opening_amount,0)) 'Opening_Amount',
								NULL 'Purchase Date',purchase_bill_no,
								SUM(isNull(purchase_qty,0)) 'Purchase_Qty', 
								SUM(isNull(purchase_rate,0)) 'purchase_rate',
								SUM(isNull(purchase_amount,0)) 'Purchase_Amount',
								NULL 'Sold Date',sold_bill_no ,
								SUM(sold_qty) 'Sold_Qty',
								SUM(sold_rate)sold_rate  , 
							    SUM(sold_amount) 'Sold_Amount',
								SUM(gain_loss) 'Gain_Loss',
								SUM(gain) 'Gain',SUM(loss) 'Loss',
								SUM(closing_qty) 'Closing_Qty',

								--SUM(closing_rate) 'Closing_Rate',
								(SUM(ISNULL(closing_value,0)) / SUM(NULLIF(closing_qty,0))) 'Closing_Rate',

								SUM(closing_value) 'Closing_Value',SUM(short_term) short_term,SUM(long_term) long_term,
								SUM(speculation) speculation,SUM(gain_speculation) gain_speculation,SUM(loss_speculation) loss_speculation,  consultant_name,0 nse_rate,0 bse_rate,1 sort,''   broker_code  --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
								FROM #mainoutputtable_1_Final_MonthWise 
								GROUP BY  Family_Name,Family_Code,Member_Name,Member_Code,consultant_name,ScriptCode,script_name,Holding_Type,purchase_bill_no,sold_bill_no 
							)a
						GROUP BY   Family_Name,Family_Code,Member_Name,Member_Code,consultant_name,Holding_Type,script_name  ,ScriptCode
						ORDER BY  Family_Name,Family_Code,Member_Name,Member_Code , Holding_Type, script_name,ScriptCode, 	 consultant_name 
					END
			END

		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN
			
				SELECT  prioritys ,Trans_No,id ,ScriptCode, Family_Name,Member_Name, script_name ,Holding_Type, flag_script_name,flag_Holding_Type,
				CONVERT(DATE, opening_date,103),ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),
				CONVERT(DATE, purchase_date,103),purchase_bill_no,ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,
				CONVERT(DATE, sold_date,103) ,sold_bill_no ,ISNULL(sold_qty,0),ISNULL(sold_rate,0),ISNULL(sold_amount ,0),
				ISNULL(gain_loss ,0),ISNULL(gain,0) ,ISNULL(loss,0),ISNULL(closing_qty ,0),ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
				ISNULL(short_term,0),ISNULL(long_term,0),ISNULL(speculation,0),ISNULL(gain_speculation,0),ISNULL(loss_speculation,0),
				consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol
				FROM #mainoutputtable_1_Final_MonthWise
				ORDER BY  Family_Name,Member_Name,consultant_name, script_name  
			END

		ELSE IF (@OUTPUT_Flag = 'Summary')
			 BEGIN
					INSERT INTO  #mainoutputtable_1_Final_Summary
					SELECT  prioritys ,Trans_No,id ,ScriptCode, Family_Name,Member_Name, script_name ,Holding_Type, flag_script_name,flag_Holding_Type,
					CONVERT(DATE, opening_date,103),ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),
					CONVERT(DATE, purchase_date,103),purchase_bill_no,ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,
					CONVERT(DATE, sold_date,103) ,sold_bill_no ,ISNULL(sold_qty,0),ISNULL(sold_rate,0),ISNULL(sold_amount ,0),
					ISNULL(gain_loss ,0),ISNULL(gain,0) ,ISNULL(loss,0),ISNULL(closing_qty ,0),ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
					ISNULL(short_term,0),ISNULL(long_term,0),ISNULL(speculation,0),ISNULL(gain_speculation,0),ISNULL(loss_speculation,0),
					consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol
					FROM #mainoutputtable_1_Final_MonthWise
					ORDER BY  Family_Name,Member_Name,consultant_name, script_name  
	 
					SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
					T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
					T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
					T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
					T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
					T1.consultant_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,T1.Family_Name,T1.Member_Name,
	
					Case WHEN Dr.BSE_Rate is NOT NULL THEN  Dr.BSE_Rate END AS 'bse_rate', 
					Case WHEN Dr.NSE_Rate is NOT NULL THEN  Dr.NSE_Rate END AS 'nse_rate' 
						   
					INTO #alldata_Summary 
					FROM #mainoutputtable_1_Final_Summary  T1
					LEFT JOIN BrokerBill T2 ON T1.Trans_No=T2.Trans_no
					LEFT JOIN DailyRate DR ON DR.Script_Code = T1.ScriptCode  and Dr.Trans_Dt = @Todate /**/
		
					TRUNCATE TABLE #mainoutputtable_1_Final_Summary

					IF (@IsMmberSelected = 1)
						BEGIN 
							INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
							opening_date,opening_qty,opening_rate,opening_amount,
							purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
							sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
							closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
							consultant_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,T1.Family_Name,T1.Member_Name   ) 

							SELECT id,Trans_No,prioritys,script_name,UPPER(holding_type),flag_script_name,UPPER(flag_holding_type),
							opening_date,opening_qty,opening_rate,opening_amount,
							purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
							sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
							closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
							consultant_name,
							Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
							sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt,Family_Name,Member_Name    
							FROM #alldata_Summary  
							GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
							opening_date,opening_qty,opening_rate,opening_amount,
							purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
							sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
							closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
							consultant_name,sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt ,Family_Name,Member_Name 
						END
					ELSE 
						BEGIN
							INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
							opening_date,opening_qty,opening_rate,opening_amount,
							purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
							sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
							closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
							consultant_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,T1.Family_Name,T1.Member_Name   ) 

							SELECT id,Trans_No,prioritys,script_name,UPPER(holding_type),flag_script_name,UPPER(flag_holding_type),
							opening_date,opening_qty,opening_rate,opening_amount,
							purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
							sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
							closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
							consultant_name,
							Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
							sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt,Family_Name,''    
							FROM #alldata_Summary  
							GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
							opening_date,opening_qty,opening_rate,opening_amount,
							purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
							sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
							closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
							consultant_name,sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt ,Family_Name 
						END  

				--	select * from #mainoutputtable_1_Final_Summary

					IF(@RecordOnlyhavingClosingbalanceZero = 0)
						BEGIN
						
					IF((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1) OR (@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1))																																																																																																																																																																																																																																																								BEGIN
						IF(@ConsultantCode<>'')
							BEGIN												
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', Family_Name,Member_Name, ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss', 0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END 
								HAVING SUM(closing_qty) != 0
							END
				     	END
						ELSE IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0)
							BEGIN																 
							 IF(@ConsultantCode<>'')
																																																																																																															BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								''  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',

								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						    	ELSE
								 BEGIN	
																																																																																															SELECT holding_type,script_name AS 'Script Name', Family_Name,Member_Name, ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,''  consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate--,consultant_name
								HAVING SUM(closing_qty) != 0
								END
						 END

					ELSE IF(@WithActualAvgRate = 0)																																																																																																																																																																																																															BEGIN
						IF(@ConsultantCode<>'')											
							BEGIN																		 
								SELECT   max(id+1)id, holding_type,script_name 'Script Name', Family_Name,Member_Name, ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date','' 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',								
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
								ORDER BY Family_Name,Member_Name,consultant_name,holding_type
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name',Family_Name,Member_Name,  ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					END
						END
			    	ELSE IF(@RecordOnlyhavingClosingbalanceZero = 1)
																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																					BEGIN
				IF((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1) OR (@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1))
					BEGIN
					
						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT Family_Name,Member_Name, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss' ,
								0 Other_amt, '' consultant_name,'a' sort
								--SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate'
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
							END
					END
				ELSE IF((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0))
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT Family_Name,Member_Name, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss' ,
								0 Other_amt, '' consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate  
								HAVING SUM(closing_qty) = 0
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
							
								SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name

							END
						ELSE
							BEGIN
								SELECT Family_Name,Member_Name, holding_type,script_name 'Script Name',Family_Name,Member_Name, ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
									0 Other_amt,'' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) = 0
							END
					END
			END
						DROP TABLE #alldata_Summary
		END
			
		DROP TABLE #mainoutputtable_1_MonthWise 	
		DROP TABLE #mainouttable_1_Monthwise_BSEISINO	 
		DROP TABLE #alldata 		 
		DROP TABLE #Family
		DROP TABLE #Members

  END  






































GO
/****** Object:  StoredProcedure [dbo].[proc_Stockholdingposition_FamilyWise_Equity_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockholdingposition_FamilyWise_Equity_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Stockholdingposition_FamilyWise_Equity_Summary] AS' 
END
GO


--Execute  proc_Stockholdingposition_FamilyWise_Equity_Summary    0,0,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-03-31 03:50:37:50','A0218','','','', '0' ,'0',0,0,0,''

--Execute  proc_Stockholdingposition_Equity_Summary    0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0',1,1,1
ALTER PROCEDURE [dbo].[proc_Stockholdingposition_FamilyWise_Equity_Summary]  --''
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,
@RecordOnlyhavingClosingbalanceZero as bit,@WithActualAvgRate as bit, @DateWiseClosinStock as bit,@FamilyCode VARCHAR(MAX))
AS
	BEGIN

		CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
            prioritys INT,
			Trans_No VARCHAR(100),
			id INT,
			ScriptCode VARCHAR(20), 
			Family_Name VARCHAR(Max),
			Member_Name VARCHAR(Max),
			script_name  VARCHAR(Max),
			holding_type VARCHAR(200),
			flag_script_name  VARCHAR(Max),
			flag_holding_type VARCHAR(200),
           opening_date VARCHAR(50),
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date VARCHAR(50),
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date VARCHAR(50),
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain FLOAT DEFAULT 0,
		   loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(MAx), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   Other_amt FLOAT DEFAULT 0,
		   ServTax_Amt FLOAT DEFAULT 0,
		   Stt_amt FLOAT DEFAULT 0,
		   sort   VARCHAR(5),
		   isintradaycol  INT 
        ) 

		IF(@ConsultantCode = '0')	
			BEGIN
						
					SELECT DISTINCT p.member_code,p.year_code,
						STUFF((	SELECT distinct ',' + p1.Consultant_Code
								FROM Mst_Consultant p1
								--WHERE p.member_code = p1.member_code AND p.year_code = p1.year_code
								FOR XML PATH(''), TYPE
								).value('.', 'NVARCHAR(MAX)')
						,1,1,'') ConsultantCode
					into #temoConsultant
					FROM Mst_Consultant p

					SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant WHERE member_code = @memcode AND year_code = @yearcode)
					DROP table #temoConsultant
				--	Select @ConsultantCode
			END

		INSERT INTO  #mainoutputtable_1_Final_Summary
		EXEC proc_Stockholdingposition_FamilyWise_Equity   @status,@Investmenttype,@Ac_Type,@memcode,@yearcode,@Fromdate,@Todate,@ScriptCode,@ConsultantCode,@BSE_NSE_Code,@Is_BFCF,@IsIntraDay,@short_Long_Term,'ALLData',@FamilyCode
	 
		SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
		T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
		T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
		T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
		T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
		T1.consultant_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,T1.Family_Name,T1.Member_Name,
	
		Case WHEN Dr.BSE_Rate is NOT NULL THEN  Dr.BSE_Rate END AS 'bse_rate', /**/
		Case WHEN Dr.NSE_Rate is NOT NULL THEN  Dr.NSE_Rate END AS 'nse_rate' /**/
		
		
		   
		INTO #alldata_Summary 
		FROM #mainoutputtable_1_Final_Summary  T1
		LEFT JOIN BrokerBill T2 ON T1.Trans_No=T2.Trans_no
		LEFT JOIN DailyRate DR ON DR.Script_Code = T1.ScriptCode  and Dr.Trans_Dt = @Todate /**/
		
		TRUNCATE TABLE #mainoutputtable_1_Final_Summary

		INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,T1.Family_Name,T1.Member_Name   ) 

		SELECT id,Trans_No,prioritys,script_name,UPPER(holding_type),flag_script_name,UPPER(flag_holding_type),
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,
		Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt,Family_Name,Member_Name    FROM #alldata_Summary  

		GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt ,Family_Name,Member_Name 

		--select * from #mainoutputtable_1_Final_Summary

		IF(@RecordOnlyhavingClosingbalanceZero = 0)
			BEGIN
				IF((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1) OR (@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1))
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', Family_Name,Member_Name, ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss', 0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END 
								HAVING SUM(closing_qty) != 0
							END
					END

				ELSE IF(@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								''  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS( SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',

								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', Family_Name,Member_Name, ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,''  consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate--,consultant_name
								HAVING SUM(closing_qty) != 0
							END
					END

				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT   max(id+1)id, holding_type,script_name 'Script Name', Family_Name,Member_Name, ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date','' 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name ,Family_Name,Member_Name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name',Family_Name,Member_Name,  ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					END
			END
		ELSE IF(@RecordOnlyhavingClosingbalanceZero = 1)
			BEGIN
				IF((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1) OR (@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1))
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT Family_Name,Member_Name, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss' ,
								0 Other_amt, '' consultant_name,'a' sort
								--SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate'
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
							END
					END
				ELSE IF((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0))
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT Family_Name,Member_Name, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss' ,
								0 Other_amt, '' consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate  
								HAVING SUM(closing_qty) = 0
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								--SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) AS 'Value After Profit/Loss',
								--SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) / NULLIF(SUM(ISNULL(closing_qty,0)),0) AS 'Avg. Rate',
								SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name

							END
						ELSE
							BEGIN
								SELECT Family_Name,Member_Name, holding_type,script_name 'Script Name',Family_Name,Member_Name, ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								--SUM(closing_value)-SUM(gain_loss) / nullif(SUM(closing_qty),0) AS 'Avg. Rate',
								0 Other_amt,'' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) = 0
							END
					END
			END
			DROP TABLE #alldata_Summary
			--drop table #mainoutputtable_1_Final_Summary
	END



































GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency] AS' 
END
GO
--[dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency] 0,1,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','0', '0' ,'0','ClosingStocks',''
ALTER PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency] --0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','ScriptWiseTotal'
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(MAX),@ConsultantCode  VARCHAR(MAX),@BSE_NSE_Code VARCHAR(MAX),@Is_BFCF VARCHAR(MAX),@IsIntraDay VARCHAR(MAX),@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX),@FamilyCode VARCHAR(MAX),
@Script_Name varchar(max) = '')
AS 
  BEGIN 
  SET NOCOUNT ON;
		DECLARE @StartYearDate varchar(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101)
		CREATE TABLE #mainoutputtable_1
        (  
			pkid INT identity(1,1), 
			Dup_pkid int,
		 	Family_Name VARCHAR(500),
			Member_Name VARCHAR(500),
			Family_Code VARCHAR(500),
			Member_Code VARCHAR(500),
			Trans_No VARCHAR(20),
			id INT,
			prioritys INT,
			Trans_Type VARCHAR(50), 
			Split_Type VARCHAR(50), 
			Flag_Type VARCHAR(10),
			Flag_Type_Sold VARCHAR(10),
			flag_script_name VARCHAR(500),
			flag_holding_type VARCHAR(200), 
			script_name VARCHAR(500),
			holding_type VARCHAR(200), 
			opening_bill_no VARCHAR(10),		    
			opening_date DATETIME,
			opening_qty FLOAT DEFAULT 0,
			opening_rate FLOAT DEFAULT 0,
			opening_amount AS( [opening_qty] * [opening_rate] ), 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount AS( purchase_qty * purchase_rate ), 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount AS ( sold_qty * sold_rate ), 
			gain_loss float,
			closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 
			closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
			closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
			short_term FLOAT DEFAULT 0,
			long_term  FLOAT DEFAULT 0,
			speculation  FLOAT DEFAULT 0,
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			consultant_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			dayscount FLOAT DEFAULT 0,
			isintradaycol INT,
			[type] VARCHAR(20),
			ScriptCode  VARCHAR(50),
			Strike_Price float DEFAULT 0,
			OptionType VARCHAR(100),
			Last_Date VARCHAR(100),
		    Broker_Code  VARCHAR(MAX)
        )  

		CREATE TABLE #mainoutputtable_1_Final
        ( 
		   Dup_pkid int,
		   OrderBy varchar(100),
           Family_Name VARCHAR(500),
		   Member_Name VARCHAR(500),
		   Family_Code VARCHAR(500),
			Member_Code VARCHAR(500),
		   Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT,
		   Split_Type VARCHAR(50),
		   Flag_Type VARCHAR(10),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name  VARCHAR(500),
		   flag_holding_type VARCHAR(200), 
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(10),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
		   gain_loss FLOAT DEFAULT 0,
		   gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(20),
		   sort   VARCHAR(5),
		   ScriptCode  VARCHAR(50),
		   Strike_Price float DEFAULT 0,
		   OptionType VARCHAR(100),
		   Last_Date VARCHAR(100),
		   Broker_Code  VARCHAR(MAX)
        ) 
		 
		CREATE TABLE #Members
		(
			Member_Code varchar(MAX)
		)
			
		CREATE TABLE #Family
		(
			Family_Code varchar(MAX)
		)

		DECLARE @tmp VARCHAR(MAX)
				
		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty INT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT,@Dup_pkid int, @Pkid Varchar(50),@idcount int  ,@Family_Code VARCHAR(500),@Member_Code VARCHAR(500) 
		DECLARE @tablerowscount INT, @Broker_Code  VARCHAR(MAX)
      IF(@status = 0)
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
				@openingDate DATETIME,@openingRate FLOAT,@openingQty INT,@openingAmount FLOAT,
				@purchaseDate DATETIME,@PurchaseBillNo  VARCHAR(50),@purchaseRate FLOAT,@purchaseQty INT,@purchaseAmount FLOAT,
				@soldDate DATETIME,@soldBillNo  VARCHAR(50),@soldRate FLOAT,@soldQty INT,@soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50),@Consultant_Name  VARCHAR(100), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(10),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,@PurchaseIntraFlag VARCHAR(100),@SaleIntraFlag VARCHAR(10) 
				DECLARE @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@ScriptId VARCHAR(20),@Strike_Price FLOAT,@OptionType VARCHAR(50),@Last_Date VARCHAR(50)
				
				CREATE TABLE #SCriptName
				(
					ScriptName varchar(MAX)
				)

				IF(@Script_Name != '')
					INSERT INTO #SCriptName SELECT value FROM Fn_split(@Script_Name, ',') 
				ELSE 
					BEGIN
						INSERT INTO #SCriptName 
						Select distinct (Ms.script_name 
								+ '/' + CONVERT(VARCHAR(10),t.Last_Date,103) 
								+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
								+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' END) 
						from brokerbill_Trans t
						Left Join mst_Script ms on ms.script_Code = t.script_Code 
					END
				CREATE TABLE #ConsultantCodes
				(
					ConsultantCodes varchar(MAX)
				)			
				IF(@ConsultantCode = '0')	
					BEGIN
							SELECT DISTINCT p.member_code,p.year_code,
								STUFF((	SELECT distinct ',' + p1.Consultant_Code
										FROM Mst_Consultant p1
										FOR XML PATH(''), TYPE
									  ).value('.', 'NVARCHAR(MAX)')
								,1,1,'') ConsultantCode
							into #temoConsultant
							FROM Mst_Consultant p

							SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant )--WHERE member_code = @memcode AND year_code = @yearcode)
							DROP table #temoConsultant
					END
				 
				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes select Consultant_Code from Mst_Consultant

				
				IF(@memcode = '' AND @familycode != '')
					BEGIN
						INSERT INTO #Members
						SELECT Member_Code 
						FROM Mst_Member WHERE Family_Code IN (SELECT Value FROM membercodestable(@familycode,','))
						SET @tmp = ''
						SELECT @tmp = @tmp + Member_Code + ',' FROM #Members
						SET @memcode = 	IsNULL((select SUBSTRING(@tmp, 0, LEN(@tmp))),'')
					END
				
				IF(@memcode != '' AND @familycode = '')
					BEGIN
						INSERT INTO #Family
						SELECT Family_Code 
						FROM Mst_Member WHERE Member_Code IN (SELECT Value FROM membercodestable(@memcode,','))
						SET @tmp = ''
						SELECT @tmp = @tmp + Family_Code + ',' FROM #Family
						SET @familycode = 	IsNULL((SELECT SUBSTRING(@tmp, 0, LEN(@tmp))),'')
					END
				
				SELECT	 ROW_NUMBER ( ) OVER (ORDER BY MF.Family_Name,mm.Member_Name,t.script_code,t.Ac_Type,t.trans_dt ) AS NameId,t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,t.TransType,t.Ac_Type,t.Script_Code,t.Last_Date,t.Qty,t.Rate,
						t.Member_code,mm.Member_Name,MF.Family_Name,MF.Family_Code,cm.Consultant_Name,t.Consultant_code,
						t.YearCode,t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,t.Exp_Rate,t.FrmNm,t.ID,
						Ms.bse_code,Ms.nse_code,
						
						 Ms.script_name 
						 +	'/' +   CONVERT(VARCHAR(10),t.Last_Date,103) 
						 +	CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
						 +  CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' 
						END script_name,

						'' AS 'Holding Type',
						CASE WHEN (((t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101))AND t.TransType='Bought') THEN 'Opening'
							 WHEN t.TransType='Bought' AND  t.Bill_no != 'Opening'  THEN 'Bought' 
							 WHEN TransType='Sold' THEN 'Sold' 
						END AS 'Flag_Type',
						t.isstock,bb.Broker_Code 
						INTO #alldata 
				FROM brokerbill_trans t 
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN  Mst_Consultant cm ON t.Consultant_code = cm.Consultant_code  
				LEFT JOIN Mst_Member MM ON mm.Member_Code=t.Member_code
				LEFT JOIN Mst_Family MF ON MF.Family_Code =MM.Family_Code
				LEFT JOIN brokerbill bb on bb.trans_no = t.Trans_No 
				WHERE  ISNULL(t.isfnobill,0) = @Investmenttype 
				AND t.trans_dt <= @Todate 
				AND t.member_code IN (SELECT value FROM Fn_split(@memcode, ',') )
				AND t.yearcode = @yearcode  
				AND t.Ac_Type =(CASE WHEN  @Ac_Type='0' THEN t.Ac_Type  ELSE  @Ac_Type END)
				AND (Ms.script_name 
						 +	'/' +   CONVERT(VARCHAR(10),t.Last_Date,103) 
						 +	CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
						 +  CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' 
						END) IN (SELECT * FROM #SCriptName)
				AND	t.Consultant_code IN (SELECT * FROM #ConsultantCodes)
				AND	t.Member_Code IN (SELECT value FROM Fn_split(@memcode, ',') )
				AND	MF.Family_Code IN (SELECT value FROM Fn_split(@FamilyCode, ',') )
				AND ISNULL(t.isIntraDay,0) =(CASE WHEN @IsIntraDay=0 THEN  ISNULL(isIntraDay,0) ELSE @IsIntraDay END) 
				AND t.isstock=(select case when @Is_BFCF = 1 then  '' else  t.isstock end)
				GROUP BY MF.Family_Code,MF.Family_Name,t.Member_Code,MM.Member_Name,t.Consultant_code,cm.Consultant_Name,bb.Broker_Code ,t.Ac_Type,t.Script_Code,script_name,t.Trans_Dt,t.Trans_No,t.Sr_No,t.Bill_no,t.TransType,t.FrmNm,t.ID,
				t.MergedEntry,t.isFNOBill,t.Strike_Price,t.OptionType,t.Last_Date,t.isIntraDay,t.MonthYear,t.LotSize,t.Qty,t.LotQty,t.Disp_qty,
				t.Bal_qty,t.G_Rate,t.Brok_Amt,ServTax_Amount,Rate,t.Amount,Stt_Amount,t.YearCode,
				t.EntrySource,t.Ref_TransNo,t.Ref_SrNo,t.Brok_PerUnit,t.lockedbymerger,
				t.frac_Qty,t.Org_Trans_No,t.Org_SrNo,t.isDeleteMerger,t.isstock,t.ScripwiseExpense,t.isClient_code,t.isClient_Brokrage,t.c_Qty,t.C_Gross_Rate,
				t.C_Net_Rate,t.C_Amount,t.C_STT,t.C_STax,t.C_MisChg,t.TransactionChg,t.C_StampDuty,t.Exp_Rate,t.PerExp_Unit,bse_code,nse_code,t.isstock
		
				 
				DECLARE @isIntradayCol INT ,@COUNT INT ,@Family_Name VARCHAR(500),@Member_Name VARCHAR(500) 
				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT id,Broker_Code,Trans_No,script_name,Script_Code, Family_Name,Member_Name,Family_Code,Member_code, [holding type],bill_no,CONVERT(DATETIME,trans_dt,101),qty,rate,ISNULL(qty, 0) * ISNULL(rate, 0),ISNULL(isintraday, 0),consultant_name,
				Strike_Price,OptionType,Last_Date   
				FROM #alldata
				WHERE ((TransType != 'Sold' AND #alldata.bill_no IN('Opening')) OR  CONVERT(date,trans_dt,101)  < CONVERT(date ,@StartYearDate,101) AND #alldata.TransType='Bought')

				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID, @Broker_Code,@Trans_No, @scriptname, @ScriptId, @Family_Name, @Member_Name,@Family_Code,@Member_code,  @holding_type, @billno, @dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date
				WHILE(@@FETCH_STATUS = 0)
					BEGIN

							IF(@Investmenttype=2)
								SET @holding_type='Mutual Fund'
						-- Insert All Openings
							SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE script_name = @scriptname)-- AND ID = @ID)
							SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
							SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
							SET @Dup_pkid = ISNULL(@Dup_pkid,0)
							SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
							SET @Dup_pkid = @Dup_pkid + 1
							INSERT INTO #mainoutputtable_1   
							(
								 Broker_Code,Dup_pkid,id, ScriptCode,Family_Name,Member_Name, Family_Code,Member_code,   Trans_No,  Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,consultant_name,Strike_Price,OptionType,Last_Date
							) 
							SELECT @Broker_Code,@Dup_pkid,@ID, @ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,    @Trans_No, 'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date
			 				
							SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),0) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
							IF(@idcount>0)
							BEGIN
								UPDATE #MainOutputtable_1 
								SET Dup_pkid = Dup_pkid + 1 
								WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
							END

						FETCH NEXT FROM alldatacursor INTO @ID,@Broker_Code, @Trans_No, @scriptname, @ScriptId, @Family_Name, @Member_Name,@Family_Code,@Member_code,   @holding_type, @billno, @dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date
 					END 

				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 
				
				DECLARE @salecount INT=0,@Boughtcount INT=0,@Flag_Type VARCHAR(20)
				
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
				SELECT id,Broker_Code,Script_Code, Family_Name,Member_Name,Family_Code,Member_code,   Bill_no,Flag_Type,TransType,script_name,[holding type],Trans_No,CONVERT(DATETIME, trans_dt,101), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name
				,Strike_Price,OptionType,Last_Date
				FROM #alldata 
				WHERE   (TransType in('Bought','Sold')  OR CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening')
				
				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Broker_Code,@ScriptId, @Family_Name,@Member_Name,@Family_Code,@Member_code,  @billno,@Flag_Type , @TransType, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name ,@Strike_Price,@OptionType,@Last_Date
				
				WHILE (@@FETCH_STATUS = 0) 
						BEGIN
							
							SET @COUNT = 0
							DECLARE @IsOpening							INT				=	0
							DECLARE @prioritysId						INT				=	0
							DECLARE @str								VARCHAR(MAX)	=	''	
							DECLARE @purchase_Op_Qty					FLOAT			=	0
							DECLARE @purchase_Op_Bill					VARCHAR(20)		=	''
							DECLARE @purchase_Op_Date					VARCHAR(20)		=	''
							DECLARE @purchase_Op_Rate					FLOAT			=	0
							DECLARE	@PurQTY								FLOAT			=	0
							DECLARE	@BalPurQTY							FLOAT			=	0
							DECLARE @BalSoldQTY							FLOAT			=	0
							DECLARE @Balpurchase_Op_Qty					FLOAT			=	0
							DECLARE @BalOpeningQTY						FLOAT			=	0
							DECLARE	@Sold_Qty							FLOAT			=	0
							DECLARE @tempID								int				=	0
							
							IF(@isIntradayCol=0)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE   script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and Flag_Type ='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=0 AND consultant_name = (CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END) AND Family_Name = @Family_Name AND Member_Name=@Member_Name)
											IF (@COUNT > 0)
												BEGIN
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,
													* INTO #tempSoldValExists 
													FROM
													#MainOutputtable_1 
													WHERE script_name=@scriptname AND holding_type=@holding_type  AND isintradaycol=0 AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold IN('Sold')  and  Flag_Type ='Sold' AND isintradaycol=0
													ORDER BY NameId

													DECLARE @R_Sold_COUNT INT=(SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty INT 
													
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists ORDER BY Dup_pkid,NameId)
															SET @str = @TransType

															SELECT TOP 1	@Sold_Qty		= sold_qty,
																			@soldDate		= sold_date,
																			@soldRate		= sold_Rate,
																			@soldBillNo		= sold_bill_no,
																			@Pkid			= Pkid
																	
															FROM #tempSoldValExists
															WHERE id  = @tempSaleID 
															SET @purchase_Op_Qty = @qty
															 
														
															IF(@TransType='Opening')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	opening_date	=	@dates,
																		opening_rate	=	@rate,
																		opening_qty		=	CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	purchase_date	=	@dates,
																		purchase_rate	=	@rate,
																		purchase_bill_no=   @PurchaseBillNo, 
																		purchase_qty		=	CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(purchase_qty,0)=0 AND pkid = @pkid
																END
															

															IF(@Sold_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET sold_qty = @purchase_Op_Qty 
																	WHERE  id  = @tempSaleID AND Flag_Type_Sold='Sold' AND pkid = @pkid
																END

															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND Pkid=@Pkid
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempSoldValExists ) 
															DECLARE @Balancedval   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)

															IF(@Balancedval  < 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE script_name = @scriptname)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty=ABS(@Balancedval) 
																	SET @prioritysId  =(SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempSaleID )
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	INSERT INTO #MainOutputtable_1(Broker_Code,Dup_pkid,ID,ScriptCode, Family_Name,Member_Name,Family_Code,Member_code,   Trans_No, Flag_Type,Flag_Type_Sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name,Strike_Price,OptionType,Last_Date)
																	VALUES(@Broker_Code,@Dup_pkid,@tempSaleID , @ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date)
																	
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 

																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			where Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																		SET @Balancedval=0
																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE script_name = @scriptname)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  = (SELECT MAX(prioritys + 1) FROM #MainOutputtable_1)
																	
																	if(@TransType='Opening')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Broker_Code,Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No, Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date)
																			VALUES(@Broker_Code,@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date)
																			
																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	ELSE if(@TransType='Bought')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Broker_Code,Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date)
																			VALUES(@Broker_Code,@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date )

																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																ENd
																ELSE IF(@Balancedval=0)
																BEGIN
																	break;
																END
																SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
																SET @qty=@Balancedval
														END
												

													DROP TABLE #tempSoldValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
												 
													INSERT INTO #mainoutputtable_1 (Broker_Code,Dup_pkid,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date) 
													VALUES ( @Broker_Code,@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date) 
												END
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE  script_name = @scriptname AND Flag_Type IN('Bought','Opening') AND ISNULL(sold_qty,0)=0  AND isintradaycol=0  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END) AND Family_Name = @Family_Name AND Member_Name=@Member_Name)
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,
													* INTO #tempValExists 
													FROM
													#MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Opening') 
													AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END) AND ISNULL(sold_qty,0)=0  AND isintradaycol=0 
													order by NameId
													
													DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty int 
													
													
													WHILE(@RCOUNT > 0)
														BEGIN 
															SET @Sold_Qty = @qty
															SET @tempID = (Select top(1) id from #tempValExists  ORDER BY pkid)
															SET @str = (Select top(1) Flag_Type From #tempValExists Where id  = @tempID)
														
														
															IF(@str='Opening')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= opening_qty,
																					@openingDate	= opening_date,
																					@openingrate	= opening_rate,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID
																END
															ELSE IF(@str='Bought')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= purchase_qty,
																					@PurchaseDate	= purchase_date,
																					@Purchaserate	= purchase_rate,
																					@PurchaseBillNo = purchase_bill_no,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID
																END
															    
															    
															IF(@Sold_Qty > 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	UPDATE #MainOutputtable_1  
																		SET	
																			opening_qty = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							END,
																			purchase_qty  = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							END,
																			sold_date=@dates,
																			sold_bill_no=@billno,
																			sold_rate=@rate,
																			sold_qty= CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold='Sold',
																			prioritys       = @prioritysId
																	WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND pkid = @pkid
																	SET @Balanceval = ABS(@Sold_Qty) - ABS(@TempSoldQty)
																END
															
														DELETE FROM #tempValExists WHERE id = @tempID AND pkid = @pkid
														SET @tablerowscount=(SELECT COUNT(*) FROM  #tempValExists ) 
														SET @RCOUNT = @RCOUNT - 1
														--SET @Sold_Qty = @qty
														
														IF(@Balanceval  < 0)
															BEGIN
																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)
																IF(@str = 'Opening')
																	BEGIN
																		SET @openingQty=ABS(@Balanceval) 
																		SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																		SET @prioritysId = ISNULL(@prioritysId,0)+1

																		INSERT INTO #MainOutputtable_1(Broker_Code,Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date)
																		VALUES(@Broker_Code,@Dup_pkid,@tempID,@ScriptId ,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date)
																		UPDATE #MainOutputtable_1 SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempID

																		SET @prioritysId = ISNULL(@prioritysId,0)+1
																
																		UPDATE #MainOutputtable_1 
																		SET prioritys=@prioritysId+1  WHERE prioritys >=  @prioritysId 
																		AND ID <> @tempID
																	END
																ELSE 
																	BEGIN
																		SET @PurchaseQty = ABS(@Sold_Qty) 
																		SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																		SET @prioritysId = ISNULL(@prioritysId,0)+1

																		INSERT INTO #MainOutputtable_1(Broker_Code,Dup_pkid,ID,ScriptCode,Family_Name, Member_Name,Family_Code,Member_code,  Trans_No,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date)
																		VALUES(@Broker_Code,@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date)
																		UPDATE #MainOutputtable_1 SET prioritys=@prioritysId  WHERE prioritys = @prioritysId AND ID<>@tempID

																		SET @prioritysId = ISNULL(@prioritysId,0)+1
																			
																		UPDATE #MainOutputtable_1 
																		SET prioritys=@prioritysId    
																		WHERE prioritys >= @prioritysId AND ID <> @tempID

																	END
																SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),1) FROM #MainOutputtable_1)) END)  
																IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
																set @Balanceval=0;
																BREAK;
															END
														ELSE IF(@Balanceval  > 0 AND @tablerowscount = 0)
															BEGIN
																
																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1
																SET @prioritysId  = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1)

																
																INSERT INTO #MainOutputtable_1(Broker_Code,Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date)
																VALUES(@Broker_Code,@Dup_pkid,@ID, @ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date)
															
																UPDATE #MainOutputtable_1 
																SET prioritys=@prioritysId+1  
																WHERE prioritys > @prioritysId AND ID<>@tempSaleID 

																SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  

																IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1 
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																	FROM Fn_split(@Pkid, ',') ) 
																END
															ENd
															ELSE IF(ISNULL(@Balanceval,0) =0)
																BEGIN
																	SET @Balanceval=0
																	BREAK;
																END
														SET @qty = @Balanceval
													END

													DROP TABLE #tempValExists
												END
											
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1) 
												    SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
													INSERT INTO #MainOutputtable_1(Broker_Code,Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date)
													VALUES(@Broker_Code,@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No,  'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date)
													
												 
												END
											SET @purchase_Op_Date	=	''
											SET @purchase_Op_Rate	=	''
											SET @purchase_Op_Qty	=	''
											SET @purchase_Op_Bill	=	''
										END
								END
							 
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Broker_Code,@ScriptId, @Family_Name,@Member_Name,@Family_Code,@Member_code,  @billno,@Flag_Type , @TransType, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name ,@Strike_Price,@OptionType,@Last_Date
			END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 
		
		INSERT INTO #mainoutputtable_1_Final (OrderBy,Broker_Code, opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No, prioritys,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,Strike_Price,OptionType,Last_Date )
				SELECT ROW_NUMBER ( ) OVER (ORDER BY Member_Name,Script_Name,
				case   WHEN  Dup_pkid is Null Then Pkid
					   WHEN  Dup_pkid is NOt Null then Dup_pkid 
				       ELSE Dup_pkid end,
				prioritys,
				case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END desc)  
			    AS NameId,
				Broker_Code,opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No, prioritys,script_name ,'Empty', flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount , 

				 Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,

				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365) --short term for purchase
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
						
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365) --short term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) = 0) 
							AND (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol ,Strike_Price,OptionType,Last_Date
				FROM #mainoutputtable_1 
				order by NameId
		

			UPDATE #mainoutputtable_1_Final SET prioritys=0
			DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
			UPDATE #mainoutputtable_1_Final
			SET prioritys  = @i , @i = @i + 1
	  
		IF(@OUTPUT_Flag='Details')
			BEGIN
				IF(@ConsultantCode !='')
					BEGIN
						SELECT id,prioritys,ScriptCode,Family_Name,Member_Name,script_name 'Script Name',Holding_Type,opening_bill_no,
						CONVERT(DATE, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(DATE, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(DATE, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
						ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,
						ISNULL(long_term,0)long_term,
						ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,isintradaycol,1 sort 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
						ORDER BY  consultant_name,Holding_Type,script_name--,id
					END
				ELSE
					BEGIN
						SELECT id,prioritys,ScriptCode,Family_Name,Member_Name,script_name 'Script Name',Holding_Type,opening_bill_no,
						CONVERT(date, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(date, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(date, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',
						CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
						ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,
						ISNULL(long_term,0)long_term,
						ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,isintradaycol,1 sort 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  

						ORDER BY  script_name--,id
											
					END
			END

		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
				SELECT  '' opening_bill_no,0 id ,  0 prioritys, ScriptCode,Family_Name,Member_Name, Family_Code,Member_Code,script_name 'Script Name', '' Holding_Type,
				NULL 'Opening Date', SUM(ISNULL(opening_qty,0)) 'Opening Qty',  ISNULL((ISNULL(SUM(ISNULL(opening_amount,0)),0)  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate', SUM(ISNULL(opening_amount,0)) 'Opening Amount',
				NULL 'Purchase Date','' 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty',  ISNULL((ISNULL(SUM(ISNULL(purchase_amount,0)),0)  / SUM(NULLIF(purchase_qty,0))),0)  'Purchase Rate', SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
				NULL 'Sold Date', '' 'Sold BillNo', SUM(ISNULL(sold_qty,0)) 'Sold Qty',  ISNULL((ISNULL(SUM(ISNULL(sold_amount,0)),0) / NULLIF (SUM(ISNULL(sold_qty,0)),0)),0) 'Sold Rate', SUM(ISNULL(sold_amount,0)) 'Sold Amount', 
				SUM(ISNULL(gain_loss ,0)) 'Gain/Loss', SUM(ISNULL(gain,0))  'Gain', SUM(ISNULL(loss,0))  'Loss',
				SUM(ISNULL(closing_qty,0))  'Closing Qty',  ISNULL((ISNULL(SUM(ISNULL(closing_value,0)),0) / NULLIF(SUM(ISNULL(closing_qty,0)),0)),0)   'Closing Rate', SUM(ISNULL(closing_value,0))  'Closing Value', SUM(ISNULL(short_term,0))  short_term, SUM(ISNULL(long_term,0))  long_term,
				SUM(ISNULL(speculation,0))speculation, SUM(ISNULL(gain_speculation,0))gain_speculation, SUM(ISNULL(loss_speculation,0))loss_speculation,consultant_name,0 nse_rate,0 bse_rate,1 sort,'' Broker_Code --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
				FROM
					(
						SELECT '' opening_bill_no,MAX(id+0)id ,MAX (prioritys+0) prioritys, ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code, script_name  ,'' Holding_Type,
						NULL 'Opening Date',SUM(opening_qty) 'Opening_Qty',sum(opening_rate) opening_rate ,SUM(opening_amount) 'Opening_Amount',
						NULL 'Purchase Date',purchase_bill_no,SUM(purchase_qty) 'Purchase_Qty', SUM(purchase_rate) purchase_rate,SUM(purchase_amount) 'Purchase_Amount',
						NULL 'Sold Date',sold_bill_no ,SUM(sold_qty) 'Sold_Qty', SUM(sold_rate)sold_rate  , SUM(sold_amount) 'Sold_Amount',SUM(gain_loss) 'Gain_Loss',SUM(gain) 'Gain',SUM(loss) 'Loss',
						SUM(closing_qty) 'Closing_Qty',SUM(closing_rate) 'Closing_Rate',SUM(closing_value) 'Closing_Value',SUM(short_term) short_term,SUM(long_term) long_term,
						SUM(speculation) speculation,SUM(gain_speculation) gain_speculation,SUM(loss_speculation) loss_speculation,consultant_name,0 nse_rate,0 bse_rate,1 sort,'' Broker_Code --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
						FROM #mainoutputtable_1_Final 
						GROUP BY  Family_Name,Family_Code,Member_Name,Member_Code,script_name,ScriptCode,Holding_Type,purchase_bill_no,sold_bill_no ,consultant_name
					)a
				GROUP BY   Family_Name,Family_Code,Member_Name,Member_Code,script_name,ScriptCode,consultant_name  		
				ORDER BY  prioritys 
			END
		ELSE IF(@OUTPUT_Flag='BrokerWiseData')
			BEGIN
				SELECT  '' opening_bill_no,0 id ,  0 prioritys, ScriptCode,Family_Name,Member_Name, Family_Code,Member_Code,script_name 'Script Name', '' Holding_Type,
				NULL 'Opening Date', SUM(ISNULL(opening_qty,0)) 'Opening Qty',  ISNULL((ISNULL(SUM(ISNULL(opening_amount,0)),0)  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate', SUM(ISNULL(opening_amount,0)) 'Opening Amount',
				NULL 'Purchase Date','' 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty',  ISNULL((ISNULL(SUM(ISNULL(purchase_amount,0)),0)  / SUM(NULLIF(ISNULL(purchase_qty,0),0))),0)  'Purchase Rate', SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
				NULL 'Sold Date', '' 'Sold BillNo', SUM(ISNULL(sold_qty,0)) 'Sold Qty',  ISNULL((ISNULL(SUM(ISNULL(sold_amount,0)),0) / NULLIF (SUM(ISNULL(sold_qty,0)),0)),0) 'Sold Rate', SUM(ISNULL(sold_amount,0)) 'Sold Amount', 
				SUM(ISNULL(gain_loss ,0)) 'Gain/Loss', SUM(ISNULL(gain,0))  'Gain', SUM(ISNULL(loss,0))  'Loss',
				SUM(ISNULL(closing_qty,0))  'Closing Qty',  ISNULL((ISNULL(SUM(closing_value),0) / NULLIF(SUM(closing_qty),0)),0)   'Closing Rate', SUM(closing_value)  'Closing Value', SUM(short_term)  short_term, SUM(long_term)  long_term,
				SUM(ISNULL(speculation,0)) speculation, SUM(ISNULL(gain_speculation,0))gain_speculation, SUM(ISNULL(loss_speculation,0))loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort,Broker_Code --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
				FROM
					(
						SELECT '' opening_bill_no,MAX(id+0)id ,MAX (prioritys+0) prioritys, ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code, script_name  ,'' Holding_Type,
						NULL 'Opening Date',SUM(opening_qty) 'Opening_Qty',sum(opening_rate) opening_rate ,SUM(opening_amount) 'Opening_Amount',
						NULL 'Purchase Date',purchase_bill_no,SUM(purchase_qty) 'Purchase_Qty', SUM(purchase_rate) purchase_rate,SUM(purchase_amount) 'Purchase_Amount',
						NULL 'Sold Date',sold_bill_no ,SUM(sold_qty) 'Sold_Qty', SUM(sold_rate)sold_rate  , SUM(sold_amount) 'Sold_Amount',SUM(gain_loss) 'Gain_Loss',SUM(gain) 'Gain',SUM(loss) 'Loss',
						SUM(closing_qty) 'Closing_Qty',SUM(closing_rate) 'Closing_Rate',SUM(closing_value) 'Closing_Value',SUM(short_term) short_term,SUM(long_term) long_term,
						SUM(speculation) speculation,SUM(gain_speculation) gain_speculation,SUM(loss_speculation) loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort ,Broker_Code --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
						FROM #mainoutputtable_1_Final 
						GROUP BY  Family_Name,Family_Code,Member_Name,Member_Code,Broker_Code ,script_name,ScriptCode,Holding_Type,purchase_bill_no,sold_bill_no 
					)a
				GROUP BY   Family_Name,Family_Code,Member_Name,Member_Code,Broker_Code ,script_name,ScriptCode  		
				ORDER BY  prioritys 
			END
		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN
			
				SELECT  prioritys ,Trans_No,id ,  ScriptCode,Family_Name,Member_Name, script_name ,Holding_Type, flag_script_name,flag_Holding_Type,
				CONVERT(DATE, opening_date,101),ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),
				CONVERT(DATE, purchase_date,101),purchase_bill_no,ISNULL(purchase_qty ,0),ISNULL(purchase_rate ,0),ISNULL(purchase_amount ,0),
				CONVERT(DATE, sold_date,101),sold_bill_no ,ISNULL(sold_qty,0) ,
				ISNULL(sold_rate,0),ISNULL(sold_amount,0) ,ISNULL(gain_loss ,0),ISNULL(gain ,0),ISNULL(loss,0),ISNULL(closing_qty ,0),ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
				ISNULL(short_term,0),ISNULL(long_term,0),ISNULL(speculation,0),ISNULL(gain_speculation,0),ISNULL(loss_speculation,0),consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol,Strike_Price,OptionType,Last_Date
				FROM #mainoutputtable_1_Final
				ORDER BY  Family_Name,Member_Name,script_name ,CONVERT(date, purchase_date,101) 
			END
		ELSE IF(@output_Flag='ClosingStocks')
			BEGIN

				 SELECT id,
						Broker_Code,
						Trans_No ,
						script_name,
						ScriptCode,
						Family_Name,
						Member_Name,
						Family_Code,
						Member_Code,
						holding_type,
						CASE
							WHEN ISNULL(closing_qty,0) < 0		THEN sold_bill_no
							WHEN ISNULL(opening_date,'') != ''   OR  ISNULL(purchase_date,'') != '' THEN  purchase_bill_no
							ELSE ''
						END  AS  'bill_no',
						CASE
							WHEN ISNULL(closing_qty,0) < 0		THEN CONVERT(DATE,sold_date,101)
							WHEN ISNULL(opening_date,'') != ''	THEN  CONVERT(DATE,opening_date,101)
							WHEN ISNULL(purchase_date,'') != '' THEN CONVERT(DATE,purchase_date,101)
						END  AS  'trans_dt',
						ABS(ISNULL(closing_qty,0)) 'Qty',
						ISNULL(closing_rate,0) 'rate',
						ISNULL(closing_value,0) 'amount',
						isintradaycol,
						consultant_name,
						Strike_Price,
						OptionType,
						Last_Date,
						CASE
							WHEN ISNULL(closing_qty,0)    < 0		THEN 'Sold'
							WHEN ISNULL(opening_date,'')  != ''		THEN 'Opening'
							WHEN ISNULL(purchase_date,'') != ''		THEN 'Bought'
							ELSE ''
						END  AS  'Type'
				from #mainoutputtable_1_Final 
				WHERE ISNULL(closing_qty,0) <> 0
				ORDER BY  trans_dt,Trans_No			
			END
		DROP TABLE #mainoutputtable_1 	 
		DROP TABLE #alldata  
		DROP TABLE #Family
		DROP TABLE #Members

  END  


















GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Monthwise]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Monthwise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Monthwise] AS' 
END
GO


 --Execute proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Monthwise 0,0,'0','Y0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','Summary',''
ALTER PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Monthwise] --0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','ScriptWiseTotal'
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(MAX),@ConsultantCode  VARCHAR(MAX),@BSE_NSE_Code VARCHAR(MAX),@Is_BFCF VARCHAR(MAX),@IsIntraDay VARCHAR(MAX),@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX),@FamilyCode VARCHAR(MAX),
@RecordOnlyhavingClosingbalanceZero as bit = 0,@WithActualAvgRate as bit =0 , @DateWiseClosinStock as bit = 0,
@Script_Name varchar(max) = '')

AS 
  BEGIN 
  SET NOCOUNT ON;
		DECLARE @StartYearDate varchar(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101)
		CREATE TABLE #mainoutputtable_1_MonthWise
        (  
			pkid INT identity(1,1), 
			Dup_pkid int,
		 	Family_Name VARCHAR(500),
			Member_Name VARCHAR(500),
			Family_Code VARCHAR(500),
			Member_Code VARCHAR(500),
			Trans_No VARCHAR(20),
			id INT,
			prioritys INT,
			Trans_Type VARCHAR(50), 
			Split_Type VARCHAR(50), 
			Flag_Type VARCHAR(10),
			Flag_Type_Sold VARCHAR(10),
			flag_script_name VARCHAR(500),
			flag_holding_type VARCHAR(200), 
			script_name VARCHAR(500),
			holding_type VARCHAR(200), 
			opening_bill_no VARCHAR(10),		    
			opening_date DATETIME,
			opening_qty FLOAT DEFAULT 0,
			opening_rate FLOAT DEFAULT 0,
			opening_amount AS( [opening_qty] * [opening_rate] ), 
			purchase_date DATETIME,
			purchase_bill_no VARCHAR(100),
			purchase_qty FLOAT DEFAULT 0,
			purchase_rate FLOAT DEFAULT 0,
			purchase_amount AS( purchase_qty * purchase_rate ), 
			sold_date DATETIME,
			sold_bill_no VARCHAR(100),
			sold_qty FLOAT DEFAULT 0,
			sold_rate FLOAT DEFAULT 0,
			sold_amount AS ( sold_qty * sold_rate ), 
			gain_loss float,
			closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 
			closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
			closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
			short_term FLOAT DEFAULT 0,
			long_term  FLOAT DEFAULT 0,
			speculation  FLOAT DEFAULT 0,
			gain_speculation FLOAT DEFAULT 0,
			loss_speculation FLOAT DEFAULT 0,
			consultant_name VARCHAR(500), 
			nse_rate FLOAT DEFAULT 0,
			bse_rate FLOAT DEFAULT 0,
			dayscount FLOAT DEFAULT 0,
			isintradaycol INT,
			[type] VARCHAR(20),
			ScriptCode  VARCHAR(50),
			Strike_Price float DEFAULT 0,
			OptionType VARCHAR(100),
			Last_Date VARCHAR(100),
		    Broker_Code  VARCHAR(MAX)
        )  

		CREATE TABLE #mainoutputtable_1_Final_MonthWise
        ( 
		   Dup_pkid int,
		   OrderBy varchar(100),
           Family_Name VARCHAR(500),
		   Member_Name VARCHAR(500),
		   Family_Code VARCHAR(500),
			Member_Code VARCHAR(500),
		   Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT,
		   Split_Type VARCHAR(50),
		   Flag_Type VARCHAR(10),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name  VARCHAR(500),
		   flag_holding_type VARCHAR(200), 
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(10),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
		   gain_loss FLOAT DEFAULT 0,
		   gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(20),
		   sort   VARCHAR(5),
		   ScriptCode  VARCHAR(50),
		   Strike_Price float DEFAULT 0,
		   OptionType VARCHAR(100),
		   Last_Date VARCHAR(100),
		   Broker_Code  VARCHAR(MAX)
        ) 

		CREATE TABLE #Openings
        (
		   id								INT, 
		   Broker_Code						VARCHAR(20),
		   Trans_No							VARCHAR(20),
		   script_name						VARCHAR(500),
		   Script_Code						VARCHAR(50),
		   Family_Name						VARCHAR(500),
		   Member_Name						VARCHAR(500),
		   Family_Code						VARCHAR(50),
		   Member_Code						VARCHAR(50),
		   holding_type						VARCHAR(200),
		   bill_no							VARCHAR(100),		     
           trans_dt							Datetime,
		   qty								FLOAT DEFAULT 0,
		   rate								FLOAT DEFAULT 0,
		   amount							FLOAT DEFAULT 0, 
           isintraday						bit DEFAULT 0, 
		   consultant_name					VARCHAR(500),
		   StrikePrice						float,
		   OptionType						VARCHAR(100),
		   Last_dt							Datetime,
		   BillType							varchar(20),
	   ) 

	   	CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
            prioritys INT,Trans_No VARCHAR(50),id INT, ScriptCode VARCHAR(20),Family_Name VARCHAR(20),Member_Name VARCHAR(20),script_name  VARCHAR(500),holding_type VARCHAR(200),flag_script_name  VARCHAR(500),flag_holding_type VARCHAR(200),
           opening_date VARCHAR(50),opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
           purchase_date VARCHAR(50),purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
           sold_date VARCHAR(50),sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   Other_amt FLOAT DEFAULT 0,
		   ServTax_Amt FLOAT DEFAULT 0,
		   Stt_amt FLOAT DEFAULT 0,
		   sort   VARCHAR(5),
		   isintradaycol  INT,
		   Strike_Price float,
		   OptionType varchar(max),
		   Last_Date dateTime
        ) 

		 
		CREATE TABLE #Members
		(
			Member_Code varchar(MAX)
		)
			
		CREATE TABLE #Family
		(
			Family_Code varchar(MAX)
		)

		DECLARE @tmp VARCHAR(MAX)
				
		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty INT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT,@Dup_pkid int, @Pkid Varchar(50),@idcount int  ,@Family_Code VARCHAR(500),@Member_Code VARCHAR(500) 
		DECLARE @tablerowscount INT, @Broker_Code  VARCHAR(MAX)
      IF(@status = 0)
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
				@openingDate DATETIME,@openingRate FLOAT,@openingQty INT,@openingAmount FLOAT,@BillType varchar(20),
				@purchaseDate DATETIME,@PurchaseBillNo  VARCHAR(50),@purchaseRate FLOAT,@purchaseQty INT,@purchaseAmount FLOAT,
				@soldDate DATETIME,@soldBillNo  VARCHAR(50),@soldRate FLOAT,@soldQty INT,@soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50),@Consultant_Name  VARCHAR(100), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(10),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,@PurchaseIntraFlag VARCHAR(100),@SaleIntraFlag VARCHAR(10) 
				DECLARE @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@ScriptId VARCHAR(20),@Strike_Price FLOAT,@OptionType VARCHAR(50),@Last_Date VARCHAR(50)
				
				CREATE TABLE #SCriptName
				(
					ScriptName varchar(MAX)
				)

				IF(@Script_Name != '')
					INSERT INTO #SCriptName SELECT value FROM Fn_split(@Script_Name, ',') 
				ELSE 
					BEGIN
						INSERT INTO #SCriptName 
						Select distinct (Ms.script_name 
								+ '/' + CONVERT(VARCHAR(10),t.Last_Date,103) 
								+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
								+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' END) 
						from brokerbill_Trans t
						Left Join mst_Script ms on ms.script_Code = t.script_Code 
					END

				CREATE TABLE #ConsultantCodes
				(
					ConsultantCodes varchar(MAX)
				)
				
				IF(@ConsultantCode = '0')	
					BEGIN
							SELECT DISTINCT p.member_code,p.year_code,
								STUFF((	SELECT distinct ',' + p1.Consultant_Code
										FROM Mst_Consultant p1
										FOR XML PATH(''), TYPE
									  ).value('.', 'NVARCHAR(MAX)')
								,1,1,'') ConsultantCode
							into #temoConsultant
							FROM Mst_Consultant p

							SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant )--WHERE member_code = @memcode AND year_code = @yearcode)
							DROP table #temoConsultant
					END
				 
				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes select Consultant_Code from Mst_Consultant				
				IF(@memcode = '' AND @familycode != '')
					BEGIN
						INSERT INTO #Members
						SELECT Member_Code 
						FROM Mst_Member WHERE Family_Code IN (SELECT Value FROM membercodestable(@familycode,','))
						SET @tmp = ''
						SELECT @tmp = @tmp + Member_Code + ',' FROM #Members
						SET @memcode = 	IsNULL((select SUBSTRING(@tmp, 0, LEN(@tmp))),'')
					END
				
				IF(@memcode != '' AND @familycode = '')
					BEGIN
						INSERT INTO #Family
						SELECT Family_Code 
						FROM Mst_Member WHERE Member_Code IN (SELECT Value FROM membercodestable(@memcode,','))
						SET @tmp = ''
						SELECT @tmp = @tmp + Family_Code + ',' FROM #Family
						SET @familycode = 	IsNULL((SELECT SUBSTRING(@tmp, 0, LEN(@tmp))),'')
					END
				
				SELECT	 ROW_NUMBER ( ) OVER (ORDER BY MF.Family_Name,mm.Member_Name,t.script_code,t.Ac_Type,t.trans_dt ) AS NameId,t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,t.TransType,t.Ac_Type,t.Script_Code,t.Last_Date,t.Qty,t.Rate,
						t.Member_code,mm.Member_Name,MF.Family_Name,MF.Family_Code,cm.Consultant_Name,t.Consultant_code,
						t.YearCode,t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,t.Exp_Rate,t.FrmNm,t.ID,
						Ms.bse_code,Ms.nse_code,						
						 Ms.script_name 
						 +	'/' +   CONVERT(VARCHAR(10),t.Last_Date,103) 
						 +	CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
						 +  CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' 
							END script_name,
						'' AS 'Holding Type',
						CASE WHEN (((t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101))AND t.TransType='Bought') THEN 'Opening'
							 WHEN t.TransType='Bought' AND  t.Bill_no != 'Opening'  THEN 'Bought' 
							 WHEN TransType='Sold' THEN 'Sold' 
						END AS 'Flag_Type',
						t.isstock,bb.Broker_Code 
						INTO #alldata 
				FROM brokerbill_trans t 
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN  Mst_Consultant cm ON t.Consultant_code = cm.Consultant_code  
				LEFT JOIN Mst_Member MM ON mm.Member_Code=t.Member_code
				LEFT JOIN Mst_Family MF ON MF.Family_Code =MM.Family_Code
				LEFT JOIN brokerbill bb on bb.trans_no = t.Trans_No 
				WHERE  ISNULL(t.isfnobill,0) = @Investmenttype 
				AND t.trans_dt >=  @Fromdate AND t.trans_dt <= @Todate
				AND t.member_code IN (SELECT value FROM Fn_split(@memcode, ',') )
				AND t.yearcode = @yearcode  
				AND t.Ac_Type =(CASE WHEN  @Ac_Type='0' THEN t.Ac_Type  ELSE  @Ac_Type END)
				AND (Ms.script_name 
						 +	'/' +   CONVERT(VARCHAR(10),t.Last_Date,103) 
						 +	CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
						 +  CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' 
							END) IN (SELECT * FROM #SCriptName)
				AND	t.Consultant_code IN (SELECT * FROM #ConsultantCodes)
				AND	t.Member_Code IN (SELECT value FROM Fn_split(@memcode, ',') )
				AND	MF.Family_Code IN (SELECT value FROM Fn_split(@FamilyCode, ',') )
				AND ISNULL(t.isIntraDay,0) = (CASE WHEN @IsIntraDay=0 THEN  ISNULL(isIntraDay,0) ELSE @IsIntraDay END) 
				AND t.isstock = (select case when @Is_BFCF = 1 then  '' else  t.isstock end)
				GROUP BY MF.Family_Code,MF.Family_Name,t.Member_Code,MM.Member_Name,t.Consultant_code,cm.Consultant_Name,bb.Broker_Code ,t.Ac_Type,t.Script_Code,script_name,t.Trans_Dt,t.Trans_No,t.Sr_No,t.Bill_no,t.TransType,t.FrmNm,t.ID,
				t.MergedEntry,t.isFNOBill,t.Strike_Price,t.OptionType,t.Last_Date,t.isIntraDay,t.MonthYear,t.LotSize,t.Qty,t.LotQty,t.Disp_qty,
				t.Bal_qty,t.G_Rate,t.Brok_Amt,ServTax_Amount,Rate,t.Amount,Stt_Amount,t.YearCode,
				t.EntrySource,t.Ref_TransNo,t.Ref_SrNo,t.Brok_PerUnit,t.lockedbymerger,
				t.frac_Qty,t.Org_Trans_No,t.Org_SrNo,t.isDeleteMerger,t.isstock,t.ScripwiseExpense,t.isClient_code,t.isClient_Brokrage,t.c_Qty,t.C_Gross_Rate,
				t.C_Net_Rate,t.C_Amount,t.C_STT,t.C_STax,t.C_MisChg,t.TransactionChg,t.C_StampDuty,t.Exp_Rate,t.PerExp_Unit,bse_code,nse_code,t.isstock
		

	        -- 	Select * from #alldata

				DECLARE @ToDATEfORcLOSIng VARCHAR(15) =  CONVERT(Varchar,CONVERT(DATETime,@fROMdATE,101) - 1,101)
				INSERT INTO #Openings
				EXECUTE proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency 0,@Investmenttype,@Ac_Type,@memcode,@Yearcode,@FromDate,@ToDATEfORcLOSIng,@ScriptCode,@ConsultantCode,@BSE_NSE_Code,@Is_BFCF,'0', @short_Long_Term ,'ClosingStocks',@FamilyCode,@Script_Name	

			--	Select * from  #Openings

				DECLARE @isIntradayCol INT ,@COUNT INT ,@Family_Name VARCHAR(500),@Member_Name VARCHAR(500) 
				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT *
				FROM #Openings 
				WHERE BillType = 'Opening'
				UNION ALL
				SELECT id,Broker_Code,Trans_No,script_name,Script_Code, Family_Name,Member_Name,Family_Code,Member_code, [holding type],bill_no,CONVERT(DATETIME,trans_dt,101),qty,rate,ISNULL(qty, 0) * ISNULL(rate, 0),ISNULL(isintraday, 0),consultant_name,
				Strike_Price,OptionType,Last_Date,'Opening'   
				FROM #alldata
				WHERE (TransType != 'Sold' AND #alldata.bill_no IN('Opening')) OR  CONVERT(date,trans_dt,101)  < CONVERT(date ,@StartYearDate,101)
				
				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID, @Broker_Code,@Trans_No, @scriptname, @ScriptId, @Family_Name, @Member_Name,@Family_Code,@Member_code,  @holding_type, @billno, @dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date,@BillType
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
							IF(@Investmenttype=2)
								SET @holding_type='Mutual Fund'
						-- Insert All Openings
							SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE script_name = @scriptname)-- AND ID = @ID)
							SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
							SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
							SET @Dup_pkid = ISNULL(@Dup_pkid,0)
							SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
							SET @Dup_pkid = @Dup_pkid + 1
							
							INSERT INTO #mainoutputtable_1_MonthWise   
							(
								 Broker_Code,Dup_pkid,id, ScriptCode,Family_Name,Member_Name, Family_Code,Member_code,   Trans_No,  Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,consultant_name,Strike_Price,OptionType,Last_Date
							) 
							SELECT @Broker_Code,@Dup_pkid,@ID, @ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,    @Trans_No, 'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date
			 				
							SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),0) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
							IF(@idcount>0)
							BEGIN
								UPDATE #mainoutputtable_1_MonthWise 
								SET Dup_pkid = Dup_pkid + 1 
								WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
							END

						FETCH NEXT FROM alldatacursor INTO @ID,@Broker_Code, @Trans_No, @scriptname, @ScriptId, @Family_Name, @Member_Name,@Family_Code,@Member_code,   @holding_type, @billno, @dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date,@BillType
 					END 

				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 	
					
			

				DECLARE @salecount INT=0,@Boughtcount INT=0,@Flag_Type VARCHAR(20)				
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
	            
				SELECT id,Broker_Code,Script_Code, Family_Name,Member_Name,Family_Code,Member_code,Bill_no,BillType,BillType,script_name,holding_type,Trans_No,CONVERT(DATETIME, trans_dt,101), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name
				,StrikePrice,OptionType,Last_dt	
				FROM #Openings 
				WHERE BillType != 'Opening'		
				UNION ALL 
				SELECT id,Broker_Code,Script_Code, Family_Name,Member_Name,Family_Code,Member_code,Bill_no,Flag_Type,TransType,script_name,[holding type],Trans_No,CONVERT(DATETIME, trans_dt,101), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name
				,Strike_Price,OptionType,Last_Date
				FROM #alldata 
				WHERE (TransType in('Bought','Sold')  AND CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening')				
				
				
				OPEN purchaseANDSaledatacursor 			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Broker_Code,@ScriptId, @Family_Name,@Member_Name,@Family_Code,@Member_code,  @billno,@Flag_Type , @TransType, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name ,@Strike_Price,@OptionType,@Last_Date
				
				WHILE (@@FETCH_STATUS = 0) 
						BEGIN
							
							SET @COUNT = 0
							DECLARE @IsOpening							INT				=	0
							DECLARE @prioritysId						INT				=	0
							DECLARE @str								VARCHAR(MAX)	=	''	
							DECLARE @purchase_Op_Qty					FLOAT			=	0
							DECLARE @purchase_Op_Bill					VARCHAR(20)		=	''
							DECLARE @purchase_Op_Date					VARCHAR(20)		=	''
							DECLARE @purchase_Op_Rate					FLOAT			=	0
							DECLARE	@PurQTY								FLOAT			=	0
							DECLARE	@BalPurQTY							FLOAT			=	0
							DECLARE @BalSoldQTY							FLOAT			=	0
							DECLARE @Balpurchase_Op_Qty					FLOAT			=	0
							DECLARE @BalOpeningQTY						FLOAT			=	0
							DECLARE	@Sold_Qty							FLOAT			=	0
							DECLARE @tempID								int				=	0
							
							IF(@isIntradayCol=0)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
										
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #mainoutputtable_1_MonthWise WHERE   script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and Flag_Type ='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=0 AND consultant_name = (CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END) AND Family_Name = @Family_Name AND Member_Name=@Member_Name)
											IF (@COUNT > 0)
												BEGIN
												
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,
													* INTO #tempSoldValExists 
													FROM
													#mainoutputtable_1_MonthWise 
												    WHERE   script_name=@scriptname
													AND Flag_Type_Sold IN('Sold')  and Flag_Type ='Sold'
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) 
													AND isintradaycol=0 
													AND consultant_name = (CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END) 
													AND Family_Name = @Family_Name 
													AND Member_Name=@Member_Name
													ORDER BY NameId
													
													DECLARE @R_Sold_COUNT INT=(SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty INT 
													
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists ORDER BY Dup_pkid,NameId)
															SET @str = @TransType

															SELECT TOP 1	@Sold_Qty		= sold_qty,
																			@soldDate		= sold_date,
																			@soldRate		= sold_Rate,
																			@soldBillNo		= sold_bill_no,
																			@Pkid			= Pkid
																	
															FROM #tempSoldValExists
															WHERE id  = @tempSaleID 
															SET @purchase_Op_Qty = @qty
															 
														
															IF(@TransType='Opening')
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise  
																	SET	opening_date	=	@dates,
																		opening_rate	=	@rate,
																		opening_qty		=	CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise  
																	SET	purchase_date	=	@dates,
																		purchase_rate	=	@rate,
																		purchase_bill_no=   @PurchaseBillNo, 
																		purchase_qty		=	CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(purchase_qty,0)=0 AND pkid = @pkid
																END
															

															IF(@Sold_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise  
																	SET sold_qty = @purchase_Op_Qty 
																	WHERE  id  = @tempSaleID AND Flag_Type_Sold='Sold' AND pkid = @pkid
																END

															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND Pkid=@Pkid
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempSoldValExists ) 
															DECLARE @Balancedval   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)

															IF(@Balancedval  < 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE script_name = @scriptname)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty=ABS(@Balancedval) 
																	SET @prioritysId  =(SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise)-- WHERE id=@tempSaleID )
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
																	INSERT INTO #mainoutputtable_1_MonthWise(Broker_Code,Dup_pkid,ID,ScriptCode, Family_Name,Member_Name,Family_Code,Member_code,   Trans_No, Flag_Type,Flag_Type_Sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name,Strike_Price,OptionType,Last_Date)
																	VALUES(@Broker_Code,@Dup_pkid,@tempSaleID , @ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date)
																	
																	UPDATE #mainoutputtable_1_MonthWise 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 

																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
																	
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #mainoutputtable_1_MonthWise 
																			SET Dup_pkid = Dup_pkid + 1 
																			where Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																		SET @Balancedval=0
																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #mainoutputtable_1_MonthWise WHERE script_name = @scriptname)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  = (SELECT MAX(prioritys + 1) FROM #mainoutputtable_1_MonthWise)
																	
																	if(@TransType='Opening')
																		BEGIN
																			INSERT INTO #mainoutputtable_1_MonthWise(Broker_Code,Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No, Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date)
																			VALUES(@Broker_Code,@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date)
																			
																			UPDATE #mainoutputtable_1_MonthWise 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	ELSE if(@TransType='Bought')
																		BEGIN
																			INSERT INTO #mainoutputtable_1_MonthWise(Broker_Code,Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date)
																			VALUES(@Broker_Code,@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date )

																			UPDATE #mainoutputtable_1_MonthWise 
																			SET prioritys=@prioritysId+1  
																			WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																		END
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #mainoutputtable_1_MonthWise 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																ENd
																ELSE IF(@Balancedval=0)
																BEGIN
																	break;
																END
																SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
																SET @qty=@Balancedval
														END
												

													DROP TABLE #tempSoldValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1_MonthWise)
												 
													INSERT INTO #mainoutputtable_1_MonthWise (Broker_Code,Dup_pkid,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date) 
													VALUES ( @Broker_Code,@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date) 
												END
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
										
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #mainoutputtable_1_MonthWise 
											WHERE  script_name = @scriptname AND Flag_Type IN('Bought','Opening') AND ISNULL(sold_qty,0)=0  AND isintradaycol=0  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END) AND Family_Name = @Family_Name AND Member_Name=@Member_Name)
										 
											IF (@COUNT > 0)
									 			BEGIN

													DECLARE @Balanceval FLOAT
													
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,
													* INTO #tempValExists 
													FROM #mainoutputtable_1_MonthWise 
													WHERE  script_name = @scriptname AND Flag_Type IN('Bought','Opening') AND ISNULL(sold_qty,0)=0  AND isintradaycol=0  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END) AND Family_Name = @Family_Name AND Member_Name=@Member_Name
													order by NameId
												
													DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty int 
													
												
													WHILE(@RCOUNT > 0)
														BEGIN 
															SET @Sold_Qty = @qty
															SET @tempID = (Select top(1) id from #tempValExists  ORDER BY pkid)
															SET @str = (Select top(1) Flag_Type From #tempValExists Where id  = @tempID)
														
														
															IF(@str='Opening')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= opening_qty,
																					@openingDate	= opening_date,
																					@openingrate	= opening_rate,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID
																END
															ELSE IF(@str='Bought')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= purchase_qty,
																					@PurchaseDate	= purchase_date,
																					@Purchaserate	= purchase_rate,
																					@PurchaseBillNo = purchase_bill_no,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID
																END
															    
															    
															IF(@Sold_Qty > 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	UPDATE #mainoutputtable_1_MonthWise  
																		SET	
																			opening_qty = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							END,
																			purchase_qty  = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							END,
																			sold_date=@dates,
																			sold_bill_no=@billno,
																			sold_rate=@rate,
																			sold_qty= CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold='Sold',
																			prioritys       = @prioritysId
																	WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND pkid = @pkid
																	SET @Balanceval = ABS(@Sold_Qty) - ABS(@TempSoldQty)
																END
															
														DELETE FROM #tempValExists WHERE id = @tempID AND pkid = @pkid
														SET @tablerowscount=(SELECT COUNT(*) FROM  #tempValExists ) 
														SET @RCOUNT = @RCOUNT - 1
														--SET @Sold_Qty = @qty
														
														IF(@Balanceval  < 0)
															BEGIN
																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE script_name = @scriptname)
																SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise)
																IF(@str = 'Opening')
																	BEGIN
																		SET @openingQty=ABS(@Balanceval) 
																		SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise)-- WHERE id=@tempID)
																		SET @prioritysId = ISNULL(@prioritysId,0)+1

																		INSERT INTO #mainoutputtable_1_MonthWise(Broker_Code,Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date)
																		VALUES(@Broker_Code,@Dup_pkid,@tempID,@ScriptId ,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date)
																		UPDATE #mainoutputtable_1_MonthWise SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempID

																		SET @prioritysId = ISNULL(@prioritysId,0)+1
																
																		UPDATE #mainoutputtable_1_MonthWise 
																		SET prioritys=@prioritysId+1  WHERE prioritys >=  @prioritysId 
																		AND ID <> @tempID
																	END
																ELSE 
																	BEGIN
																		SET @PurchaseQty = ABS(@Sold_Qty) 
																		SET @prioritysId  = (SELECT MAX(prioritys) FROM #mainoutputtable_1_MonthWise)-- WHERE id=@tempID)
																		SET @prioritysId = ISNULL(@prioritysId,0)+1

																		INSERT INTO #mainoutputtable_1_MonthWise(Broker_Code,Dup_pkid,ID,ScriptCode,Family_Name, Member_Name,Family_Code,Member_code,  Trans_No,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date)
																		VALUES(@Broker_Code,@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date)
																		UPDATE #mainoutputtable_1_MonthWise SET prioritys=@prioritysId  WHERE prioritys = @prioritysId AND ID<>@tempID

																		SET @prioritysId = ISNULL(@prioritysId,0)+1
																			
																		UPDATE #mainoutputtable_1_MonthWise 
																		SET prioritys=@prioritysId    
																		WHERE prioritys >= @prioritysId AND ID <> @tempID

																	END
																SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),1) FROM #mainoutputtable_1_MonthWise)) END)  
																IF(@idcount>0)
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
																set @Balanceval=0;
																BREAK;
															END
														ELSE IF(@Balanceval  > 0 AND @tablerowscount = 0)
															BEGIN
																
																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #mainoutputtable_1_MonthWise WHERE Pkid = @Pkid)
																SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #mainoutputtable_1_MonthWise) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #mainoutputtable_1_MonthWise WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1
																SET @prioritysId  = (SELECT MAX(prioritys+1) FROM #mainoutputtable_1_MonthWise)

																
																INSERT INTO #mainoutputtable_1_MonthWise(Broker_Code,Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date)
																VALUES(@Broker_Code,@Dup_pkid,@ID, @ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date)
															
																UPDATE #mainoutputtable_1_MonthWise 
																SET prioritys=@prioritysId+1  
																WHERE prioritys > @prioritysId AND ID<>@tempSaleID 

																SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #mainoutputtable_1_MonthWise)) END)  

																IF(@idcount>0)
																BEGIN
																	UPDATE #mainoutputtable_1_MonthWise 
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																	FROM Fn_split(@Pkid, ',') ) 
																END
															ENd
															ELSE IF(ISNULL(@Balanceval,0) =0)
																BEGIN
																	SET @Balanceval=0
																	BREAK;
																END
														SET @qty = @Balanceval
													END

													DROP TABLE #tempValExists
												END
											
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
												  
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1_MonthWise) 
												    SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1_MonthWise)
													INSERT INTO #mainoutputtable_1_MonthWise(Broker_Code,Dup_pkid,ID,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date)
													VALUES(@Broker_Code,@Dup_pkid,@ID,@ScriptId,@Family_Name,@Member_Name,@Family_Code,@Member_code,  @Trans_No,  'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date)
													
												 
												END
											SET @purchase_Op_Date	=	''
											SET @purchase_Op_Rate	=	''
											SET @purchase_Op_Qty	=	''
											SET @purchase_Op_Bill	=	''
										END
								END
							 
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@Broker_Code,@ScriptId, @Family_Name,@Member_Name,@Family_Code,@Member_code,  @billno,@Flag_Type , @TransType, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name ,@Strike_Price,@OptionType,@Last_Date
			END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 
		
		INSERT INTO #mainoutputtable_1_Final_MonthWise (OrderBy,Broker_Code, opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No, prioritys,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,Strike_Price,OptionType,Last_Date )
				SELECT ROW_NUMBER ( ) OVER (ORDER BY Member_Name,Script_Name,
				case   WHEN  Dup_pkid is Null Then Pkid
					   WHEN  Dup_pkid is NOt Null then Dup_pkid 
				       ELSE Dup_pkid end,
				prioritys,
				case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END desc)  
			    AS NameId,
				Broker_Code,opening_bill_no,id,ScriptCode,Family_Name,Member_Name,Family_Code,Member_code,  Trans_No, prioritys,script_name ,'Empty', flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount , 

				 Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,

				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365) --short term for purchase
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
						
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365) --short term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) = 0) 
							AND (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol ,Strike_Price,OptionType,Last_Date
				FROM #mainoutputtable_1_MonthWise 
				order by NameId
		

			UPDATE #mainoutputtable_1_Final_MonthWise SET prioritys=0
			DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final_MonthWise)
			UPDATE #mainoutputtable_1_Final_MonthWise
			SET prioritys  = @i , @i = @i + 1
	  
		IF(@OUTPUT_Flag='Details')
			BEGIN
				IF(@ConsultantCode !='')
					BEGIN
						SELECT id,prioritys,ScriptCode,Family_Name,Member_Name,script_name 'Script Name',Holding_Type,opening_bill_no,
						CONVERT(DATE, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(DATE, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(DATE, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
						ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,
						ISNULL(long_term,0)long_term,
						ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,isintradaycol,1 sort 
						FROM #mainoutputtable_1_Final_MonthWise
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
						ORDER BY  consultant_name,Holding_Type,script_name--,id
					END
				ELSE
					BEGIN
						SELECT id,prioritys,ScriptCode,Family_Name,Member_Name,script_name 'Script Name',Holding_Type,opening_bill_no,
						CONVERT(date, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(date, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(date, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',
						CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
						ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,
						ISNULL(long_term,0)long_term,
						ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,isintradaycol,1 sort 
						FROM #mainoutputtable_1_Final_MonthWise
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  

						ORDER BY  script_name--,id
											
					END
			END

		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
				SELECT  '' opening_bill_no,0 id ,  0 prioritys, ScriptCode,Family_Name,Member_Name, Family_Code,Member_Code,script_name 'Script Name', '' Holding_Type,
				NULL 'Opening Date', SUM(ISNULL(opening_qty,0)) 'Opening Qty',  ISNULL((ISNULL(SUM(ISNULL(opening_amount,0)),0)  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate', SUM(ISNULL(opening_amount,0)) 'Opening Amount',
				NULL 'Purchase Date','' 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty',  ISNULL((ISNULL(SUM(ISNULL(purchase_amount,0)),0)  / SUM(NULLIF(purchase_qty,0))),0)  'Purchase Rate', SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
				NULL 'Sold Date', '' 'Sold BillNo', SUM(ISNULL(sold_qty,0)) 'Sold Qty',  ISNULL((ISNULL(SUM(ISNULL(sold_amount,0)),0) / NULLIF (SUM(ISNULL(sold_qty,0)),0)),0) 'Sold Rate', SUM(ISNULL(sold_amount,0)) 'Sold Amount', 
				SUM(ISNULL(gain_loss ,0)) 'Gain/Loss', SUM(ISNULL(gain,0))  'Gain', SUM(ISNULL(loss,0))  'Loss',
				SUM(ISNULL(closing_qty,0))  'Closing Qty',  ISNULL((ISNULL(SUM(ISNULL(closing_value,0)),0) / NULLIF(SUM(ISNULL(closing_qty,0)),0)),0)   'Closing Rate', SUM(ISNULL(closing_value,0))  'Closing Value', SUM(ISNULL(short_term,0))  short_term, SUM(ISNULL(long_term,0))  long_term,
				SUM(ISNULL(speculation,0))speculation, SUM(ISNULL(gain_speculation,0))gain_speculation, SUM(ISNULL(loss_speculation,0))loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort,'' Broker_Code --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
				FROM
					(
						SELECT '' opening_bill_no,MAX(id+0)id ,MAX (prioritys+0) prioritys, ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code, script_name  ,'' Holding_Type,
						NULL 'Opening Date',SUM(opening_qty) 'Opening_Qty',sum(opening_rate) opening_rate ,SUM(opening_amount) 'Opening_Amount',
						NULL 'Purchase Date',purchase_bill_no,SUM(purchase_qty) 'Purchase_Qty', SUM(purchase_rate) purchase_rate,SUM(purchase_amount) 'Purchase_Amount',
						NULL 'Sold Date',sold_bill_no ,SUM(sold_qty) 'Sold_Qty', SUM(sold_rate)sold_rate  , SUM(sold_amount) 'Sold_Amount',SUM(gain_loss) 'Gain_Loss',SUM(gain) 'Gain',SUM(loss) 'Loss',
						SUM(closing_qty) 'Closing_Qty',SUM(closing_rate) 'Closing_Rate',SUM(closing_value) 'Closing_Value',SUM(short_term) short_term,SUM(long_term) long_term,
						SUM(speculation) speculation,SUM(gain_speculation) gain_speculation,SUM(loss_speculation) loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort,'' Broker_Code --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
						FROM #mainoutputtable_1_Final_MonthWise 
						GROUP BY  Family_Name,Family_Code,Member_Name,Member_Code,script_name,ScriptCode,Holding_Type,purchase_bill_no,sold_bill_no 
					)a
				GROUP BY   Family_Name,Family_Code,Member_Name,Member_Code,script_name,ScriptCode  		
				ORDER BY  prioritys 
			END
		ELSE IF(@OUTPUT_Flag='BrokerWiseData')
			BEGIN
				SELECT  '' opening_bill_no,0 id ,  0 prioritys, ScriptCode,Family_Name,Member_Name, Family_Code,Member_Code,script_name 'Script Name', '' Holding_Type,
				NULL 'Opening Date', SUM(ISNULL(opening_qty,0)) 'Opening Qty',  ISNULL((ISNULL(SUM(ISNULL(opening_amount,0)),0)  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate', SUM(ISNULL(opening_amount,0)) 'Opening Amount',
				NULL 'Purchase Date','' 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty',  ISNULL((ISNULL(SUM(ISNULL(purchase_amount,0)),0)  / SUM(NULLIF(ISNULL(purchase_qty,0),0))),0)  'Purchase Rate', SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
				NULL 'Sold Date', '' 'Sold BillNo', SUM(ISNULL(sold_qty,0)) 'Sold Qty',  ISNULL((ISNULL(SUM(ISNULL(sold_amount,0)),0) / NULLIF (SUM(ISNULL(sold_qty,0)),0)),0) 'Sold Rate', SUM(ISNULL(sold_amount,0)) 'Sold Amount', 
				SUM(ISNULL(gain_loss ,0)) 'Gain/Loss', SUM(ISNULL(gain,0))  'Gain', SUM(ISNULL(loss,0))  'Loss',
				SUM(ISNULL(closing_qty,0))  'Closing Qty',  ISNULL((ISNULL(SUM(closing_value),0) / NULLIF(SUM(closing_qty),0)),0)   'Closing Rate', SUM(closing_value)  'Closing Value', SUM(short_term)  short_term, SUM(long_term)  long_term,
				SUM(ISNULL(speculation,0)) speculation, SUM(ISNULL(gain_speculation,0))gain_speculation, SUM(ISNULL(loss_speculation,0))loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort,Broker_Code --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
				FROM
					(
						SELECT '' opening_bill_no,MAX(id+0)id ,MAX (prioritys+0) prioritys, ScriptCode,Family_Name,Member_Name,Family_Code,Member_Code, script_name  ,'' Holding_Type,
						NULL 'Opening Date',SUM(opening_qty) 'Opening_Qty',sum(opening_rate) opening_rate ,SUM(opening_amount) 'Opening_Amount',
						NULL 'Purchase Date',purchase_bill_no,SUM(purchase_qty) 'Purchase_Qty', SUM(purchase_rate) purchase_rate,SUM(purchase_amount) 'Purchase_Amount',
						NULL 'Sold Date',sold_bill_no ,SUM(sold_qty) 'Sold_Qty', SUM(sold_rate)sold_rate  , SUM(sold_amount) 'Sold_Amount',SUM(gain_loss) 'Gain_Loss',SUM(gain) 'Gain',SUM(loss) 'Loss',
						SUM(closing_qty) 'Closing_Qty',SUM(closing_rate) 'Closing_Rate',SUM(closing_value) 'Closing_Value',SUM(short_term) short_term,SUM(long_term) long_term,
						SUM(speculation) speculation,SUM(gain_speculation) gain_speculation,SUM(loss_speculation) loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort ,Broker_Code --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
						FROM #mainoutputtable_1_Final_MonthWise 
						GROUP BY  Family_Name,Family_Code,Member_Name,Member_Code,Broker_Code ,script_name,ScriptCode,Holding_Type,purchase_bill_no,sold_bill_no 
					)a
				GROUP BY   Family_Name,Family_Code,Member_Name,Member_Code,Broker_Code ,script_name,ScriptCode  		
				ORDER BY  prioritys 
			END
		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN
			
				SELECT  prioritys ,Trans_No,id ,  ScriptCode,Family_Name,Member_Name, script_name ,Holding_Type, flag_script_name,flag_Holding_Type,
				CONVERT(DATE, opening_date,101),ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),
				CONVERT(DATE, purchase_date,101),purchase_bill_no,ISNULL(purchase_qty ,0),ISNULL(purchase_rate ,0),ISNULL(purchase_amount ,0),
				CONVERT(DATE, sold_date,101),sold_bill_no ,ISNULL(sold_qty,0) ,
				ISNULL(sold_rate,0),ISNULL(sold_amount,0) ,ISNULL(gain_loss ,0),ISNULL(gain ,0),ISNULL(loss,0),ISNULL(closing_qty ,0),ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
				ISNULL(short_term,0),ISNULL(long_term,0),ISNULL(speculation,0),ISNULL(gain_speculation,0),ISNULL(loss_speculation,0),consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol,Strike_Price,OptionType,Last_Date
				FROM #mainoutputtable_1_Final_MonthWise
				ORDER BY  Family_Name,Member_Name,script_name ,CONVERT(date, purchase_date,101) 
			END
		ELSE IF(@OUTPUT_Flag='Summary')
			BEGIN
			
				INSERT INTO  #mainoutputtable_1_Final_Summary
				SELECT  prioritys ,Trans_No,id ,  ScriptCode,Family_Name,Member_Name, script_name ,Holding_Type, flag_script_name,flag_Holding_Type,
				CONVERT(DATE, opening_date,101),ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),
				CONVERT(DATE, purchase_date,101),purchase_bill_no,ISNULL(purchase_qty ,0),ISNULL(purchase_rate ,0),ISNULL(purchase_amount ,0),
				CONVERT(DATE, sold_date,101),sold_bill_no ,ISNULL(sold_qty,0) ,
				ISNULL(sold_rate,0),ISNULL(sold_amount,0) ,ISNULL(gain_loss ,0),ISNULL(gain ,0),ISNULL(loss,0),ISNULL(closing_qty ,0),ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
				ISNULL(short_term,0),ISNULL(long_term,0),ISNULL(speculation,0),ISNULL(gain_speculation,0),ISNULL(loss_speculation,0),consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol,Strike_Price,OptionType,Last_Date
				FROM #mainoutputtable_1_Final_MonthWise
				ORDER BY  Family_Name,Member_Name,script_name ,CONVERT(date, purchase_date,101) 
		
		
		
		SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
		T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
		T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
		T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
		T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
		T1.consultant_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,T1.Family_Name,T1.Member_Name,  
		Isnull(Dr.Bse_FO_Rate,0) AS 'bse_rate', /**/
		Isnull(Dr.Nse_FO_Rate,0) AS 'nse_rate' /**/
		 
		INTO #alldata_Summary 
		FROM #mainoutputtable_1_Final_Summary  T1
		LEFT JOIN BrokerBill T2 ON T1.Trans_No=T2.Trans_no
		LEFT JOIN DailyRate  DR  
		ON 
			DR.InvestmentType != 0 and Dr.InvestmentType != 2 AND
			DR.Script_Code = T1.ScriptCode and dr.Trans_Dt =  Convert(Datetime,@Todate,101) AND 
			Convert(varchar,DR.Expir_Date ,101) =  Convert(varchar,T1.Last_Date,101) AND
			ISNULL(Substring(RTRIM(LTRIM(T1.OptionType)),0,3),'') = ISNULL( DR.OptionType,'') AND
			ISNULL(DR.Strike_Price,0) = ISNULL(T1.Strike_Price,'')
	
		
		TRUNCATE TABLE #mainoutputtable_1_Final_Summary

		INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,T1.Family_Name,T1.Member_Name   ) 

		SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,
		Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt,Family_Name,Member_Name    FROM #alldata_Summary  

		GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt ,Family_Name,Member_Name 

		IF(@RecordOnlyhavingClosingbalanceZero = 0)
			BEGIN
				IF((@WithActualAvgRate = 1 and @DateWiseClosinStock = 1) OR (@WithActualAvgRate = 0 and @DateWiseClosinStock = 1))
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name 
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', Family_Name,Member_Name, ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								0 Other_amt,''  consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END 
								HAVING SUM(closing_qty) != 0
							END
					END
				ELSE IF(@WithActualAvgRate = 1 and @DateWiseClosinStock = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,consultant_name 
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', Family_Name,Member_Name, ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								0 Other_amt,''  consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END 
								HAVING SUM(closing_qty) != 0
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT   max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date','' 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
 
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name',Family_Name,Member_Name,  ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)   END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					END
			END
		ELSE IF(@RecordOnlyhavingClosingbalanceZero = 1)
			BEGIN
				IF ((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)OR (@WithActualAvgRate = 0 and @DateWiseClosinStock = 1))
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0 
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT Family_Name,Member_Name, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',0 Other_amt,''  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
							END
					END
				ELSE IF ((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0))
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT Family_Name,Member_Name, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								0 Other_amt, '' consultant_name,'a' sort 
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate  
								HAVING SUM(closing_qty) = 0
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) AS 'Value After Profit/Loss',
								SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) / NULLIF(SUM(ISNULL(closing_qty,0)),0) AS 'Avg. Rate',
								SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name

							END
						ELSE
							BEGIN
								SELECT Family_Name,Member_Name, holding_type,script_name 'Script Name',Family_Name,Member_Name, ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / nullif(SUM(closing_qty),0) AS 'Avg. Rate',
								0 Other_amt,'' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) = 0
							END
					END
			END
			DROP TABLE #alldata_Summary
			END

		DROP TABLE #mainoutputtable_1_MonthWise 
		 
		DROP TABLE #alldata 
	 
		DROP TABLE #Family
		DROP TABLE #Members

  END  



















GO
/****** Object:  StoredProcedure [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Summary] AS' 
END
GO
--Execute  proc_Stockholdingposition_FamilyWise_Equity_Summary    0,0,'0','A0001,M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0',0,0,0,''

--Execute  proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Summary    0,1,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-02-01 03:50:37:50','','','0','', '0' ,'0',0,0,0,''
ALTER PROCEDURE [dbo].[proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency_Summary]  --''
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate DateTime,@Todate DateTime, 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,
@RecordOnlyhavingClosingbalanceZero as bit,@WithActualAvgRate as bit, @DateWiseClosinStock as bit,@FamilyCode VARCHAR(MAX),
@Script_Name varchar(max) = '')
AS
	BEGIN
	SET NOCOUNT ON;
		CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
            prioritys INT,Trans_No VARCHAR(50),id INT, ScriptCode VARCHAR(20),Family_Name VARCHAR(20),Member_Name VARCHAR(20),script_name  VARCHAR(500),holding_type VARCHAR(200),flag_script_name  VARCHAR(500),flag_holding_type VARCHAR(200),
           opening_date VARCHAR(50),opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
           purchase_date VARCHAR(50),purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
           sold_date VARCHAR(50),sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   Other_amt FLOAT DEFAULT 0,
		   ServTax_Amt FLOAT DEFAULT 0,
		   Stt_amt FLOAT DEFAULT 0,
		   sort   VARCHAR(5),
		   isintradaycol  INT,
		   Strike_Price float,
		   OptionType varchar(max),
		   Last_Date dateTime
        ) 

		
		IF(@ConsultantCode = '0')	
			BEGIN
						
					SELECT DISTINCT p.member_code,p.year_code,
						STUFF((	SELECT distinct ',' + p1.Consultant_Code
								FROM Mst_Consultant p1
								FOR XML PATH(''), TYPE
								).value('.', 'NVARCHAR(MAX)')
						,1,1,'') ConsultantCode
					into #temoConsultant
					FROM Mst_Consultant p

					SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant WHERE member_code = @memcode AND year_code = @yearcode)
					DROP table #temoConsultant
			END

		INSERT INTO  #mainoutputtable_1_Final_Summary
		EXEC proc_StockholdingPosition_FamilyWise_F_And_O_AND_MCX_And_Currency   @status,@Investmenttype,@Ac_Type,@memcode,@yearcode,@Fromdate,@Todate,@ScriptCode,@ConsultantCode,@BSE_NSE_Code,@Is_BFCF,@IsIntraDay,@short_Long_Term,'ALLData',@FamilyCode,@Script_Name
		
		
		SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
		T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
		T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
		T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
		T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
		T1.consultant_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,T1.Family_Name,T1.Member_Name,  
		Isnull(Dr.Bse_FO_Rate,0) AS 'bse_rate', /**/
		Isnull(Dr.Nse_FO_Rate,0) AS 'nse_rate' /**/
		 
		INTO #alldata_Summary 
		FROM #mainoutputtable_1_Final_Summary  T1
		LEFT JOIN BrokerBill T2 ON T1.Trans_No=T2.Trans_no
		LEFT JOIN DailyRate  DR  
		ON 
			DR.InvestmentType != 0 and Dr.InvestmentType != 2 AND
			DR.Script_Code = T1.ScriptCode and  Convert(varchar,dr.Trans_Dt,101) =  Convert(varchar,@Todate,101) AND 
			Convert(varchar,DR.Expir_Date ,101) =  Convert(varchar,T1.Last_Date,101) AND
			ISNULL(Substring(RTRIM(LTRIM(T1.OptionType)),0,3),'') = ISNULL( DR.OptionType,'') AND
			ISNULL(DR.Strike_Price,0) = ISNULL(T1.Strike_Price,'')
	
		
		TRUNCATE TABLE #mainoutputtable_1_Final_Summary

		INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,T1.Family_Name,T1.Member_Name   ) 

		SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,
		Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt,Family_Name,Member_Name    FROM #alldata_Summary  

		GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt ,Family_Name,Member_Name 

		IF(@RecordOnlyhavingClosingbalanceZero = 0)
			BEGIN
				IF((@WithActualAvgRate = 1 and @DateWiseClosinStock = 1) OR (@WithActualAvgRate = 0 and @DateWiseClosinStock = 1))
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name 
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', Family_Name,Member_Name, ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								0 Other_amt,''  consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END 
								HAVING SUM(closing_qty) != 0
							END
					END
				ELSE IF(@WithActualAvgRate = 1 and @DateWiseClosinStock = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,consultant_name 
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', Family_Name,Member_Name, ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								0 Other_amt,''  consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END 
								HAVING SUM(closing_qty) != 0
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT   max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date','' 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
 
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name',Family_Name,Member_Name,  ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)   END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					END
			END
		ELSE IF(@RecordOnlyhavingClosingbalanceZero = 1)
			BEGIN
				IF ((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1)OR (@WithActualAvgRate = 0 and @DateWiseClosinStock = 1))
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0 
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT Family_Name,Member_Name, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',0 Other_amt,''  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
							END
					END
				ELSE IF ((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0))
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT Family_Name,Member_Name, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
								END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
								END AS 'Value After Profit/Loss',
								0 Other_amt, '' consultant_name,'a' sort 
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate  
								HAVING SUM(closing_qty) = 0
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) AS 'Value After Profit/Loss',
								SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) / NULLIF(SUM(ISNULL(closing_qty,0)),0) AS 'Avg. Rate',
								SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name

							END
						ELSE
							BEGIN
								SELECT Family_Name,Member_Name, holding_type,script_name 'Script Name',Family_Name,Member_Name, ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / nullif(SUM(closing_qty),0) AS 'Avg. Rate',
								0 Other_amt,'' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY Family_Name,Member_Name, holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) = 0
							END
					END
			END
			DROP TABLE #alldata_Summary
	END

































GO
/****** Object:  StoredProcedure [dbo].[proc_Stockposition_Equity_ROI]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockposition_Equity_ROI]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Stockposition_Equity_ROI] AS' 
END
GO


 -- execute [dbo].[proc_Stockposition_Equity_ROI]  0,0,'0','30001','1120182019','2018-04-01 12:00:00:00','2019-03-31 03:50:37:50','C0147','','','', '0' ,'0','Details'
ALTER  PROCEDURE [dbo].[proc_Stockposition_Equity_ROI] 
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,
@OUTPUT_Flag VARCHAR(MAX),@IsWithTax bit = 0,@IsBSEISIN bit=0,@isDIVIDEND bit=0)
AS 
  BEGIN 
  SET NOCOUNT ON;
		DECLARE @StartYearDate varchar(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101)
		 
		CREATE TABLE #mainoutputtable_1
        ( 
		   pkid INT identity(1,1), 
		   Dup_pkid int, 
           Trans_No VARCHAR(20),
		   Ac_type VARCHAR(20),
		   id INT,
		    sr_no int,
		   prioritys INT,
		   Trans_Type  VARCHAR(50), 
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(50),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name VARCHAR(Max),
		   flag_holding_type VARCHAR(Max), 
		   script_name VARCHAR(Max),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(100),	
           opening_date DATETIME,
		   opening_qty FLOAT DEFAULT 0,
		   opening_rate FLOAT DEFAULT 0,
		   opening_amount AS( [opening_qty] * [opening_rate] ), 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount AS( purchase_qty * purchase_rate ), 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount AS ( sold_qty * sold_rate ), 
		   gain_loss float,
		   closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 
           closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
		   closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
		   short_term FLOAT DEFAULT 0,
		   long_term  FLOAT DEFAULT 0,
           speculation  FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   NoOfDays FLOAT DEFAULT 0,
		   ROI FLOAT DEFAULT 0,
		   [Actual ROI] FLOAT DEFAULT 0,
		   [Monthly ROI] FLOAT DEFAULT 0,
		   [Anually ROI] FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(50) ,
		   ScriptCode Varchar(50),
		   Broker_Code VARCHAR(100),
		   Dp_code  VARCHAR(100),
		   Consultant_code VARCHAR(20)
        )  

		CREATE TABLE #mainoutputtable_1_BSEISINNO
		(
		   pkid INT,
		   Dup_pkid int,
		   Trans_No VARCHAR(20),
		   Ac_type VARCHAR(20),
		   id INT,
		   sr_no int,
		   prioritys INT,
		   Trans_Type  VARCHAR(50), 
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(50),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name VARCHAR(Max),
		   flag_holding_type VARCHAR(Max), 
		   script_name VARCHAR(Max),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(100),	
           opening_date DATETIME,
		   opening_qty FLOAT DEFAULT 0,
		   opening_rate FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0,
		   purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0,
		   sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0,
		   gain_loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0,
		   closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term  FLOAT DEFAULT 0,
           speculation  FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   NoOfDays FLOAT DEFAULT 0,
		   ROI FLOAT DEFAULT 0,
		   [Actual ROI] FLOAT DEFAULT 0,
		   [Monthly ROI] FLOAT DEFAULT 0,
		   [Anually ROI] FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(50) ,
		   ScriptCode Varchar(50),
		   Broker_Code VARCHAR(100),
		   Dp_code  VARCHAR(100),
		   Consultant_code VARCHAR(20)
		)

		CREATE TABLE #mainoutputtable_1_Final
        ( 
		   Dup_pkid int, 
		   OrderBy varchar(100),
           Trans_No VARCHAR(20),
		   Ac_type VARCHAR(20),
		   id INT,prioritys INT   ,
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(50),
		   Flag_Type_Sold VARCHAR(50),
		   flag_script_name  VARCHAR(Max),
		   flag_holding_type VARCHAR(Max), 
		   script_name  VARCHAR(Max),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(100),		     
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(50),
		   sort   VARCHAR(5),
		   NoOfDays  AS
		   (
		   CASE WHEN ISNULL(opening_date,'')  !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR , CONVERT(DATETIME , opening_date , 101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101)))  ELSE 
		   CASE WHEN ISNULL(purchase_date,'') !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME , purchase_date , 101)) , CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) ELSE 0 END END
		   ) ,
		   ROI AS 
		   (
				CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (Gain_Loss / NULLIF(Opening_Amount,0)) * 100 WHEN ISNULL(Purchase_Amount,0) != 0 
				THEN  (Gain_Loss/Purchase_Amount)*100	END
		   ) ,
		   [Actual ROI]  AS
		   (
			   CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ((Gain_Loss / NULLIF(Opening_Amount,0)) * 100) /  
			   NULLIF(CASE WHEN ISNULL(opening_date,'')  !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR , CONVERT(DATETIME , opening_date , 101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101)))  ELSE 
			   CASE WHEN ISNULL(purchase_date,'') !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME , purchase_date , 101)) , CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) ELSE 0 END END,0) 
			ELSE
			   CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN ((Gain_Loss / Purchase_Amount) * 100) / 
			   NULLIF(CASE WHEN ISNULL(opening_date,'')  !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR , CONVERT(DATETIME , opening_date , 101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101)))  ELSE 
			   CASE WHEN ISNULL(purchase_date,'') !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME , purchase_date , 101)) , CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) ELSE 0 END END,0) 
			   END END
		   )
		   ,
		   [Monthly ROI] AS
		   (
				CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((Gain_Loss / NULLIF(Opening_Amount,0)) * 100) /  
				NULLIF(CASE WHEN ISNULL(opening_date,'')  !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR , CONVERT(DATETIME , opening_date , 101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101)))  ELSE 
				CASE WHEN ISNULL(purchase_date,'') !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME , purchase_date , 101)) , CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) ELSE 0 END END,0))  * 30  
			ELSE
				CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN  (((Gain_Loss / NULLIF(Purchase_Amount,0)) * 100) / 
				NULLIF(CASE WHEN ISNULL(opening_date,'')  !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR , CONVERT(DATETIME , opening_date , 101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101)))  ELSE 
				CASE WHEN ISNULL(purchase_date,'') !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME , purchase_date , 101)) , CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) ELSE 0 END END,0)) * 30 
				END END 
		   )
		   ,
		   [Anually ROI]  AS
		   (
				CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((Gain_Loss / NULLIF(Opening_Amount,0)) * 100) / 
				NULLIF(CASE WHEN ISNULL(opening_date,'')  !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR , CONVERT(DATETIME , opening_date , 101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101)))  ELSE 
				CASE WHEN ISNULL(purchase_date,'') !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME , purchase_date , 101)) , CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) ELSE 0 END END,0)) * 365 
		   ELSE
				CASE WHEN ISNULL(Purchase_Amount,0)!=0 THEN  (((Gain_Loss / NULLIF(Purchase_Amount,0))*100) / 
				NULLIF(CASE WHEN ISNULL(opening_date,'')  !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR , CONVERT(DATETIME , opening_date , 101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101)))  ELSE 
				CASE WHEN ISNULL(purchase_date,'') !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME , purchase_date , 101)) , CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) ELSE 0 END END,0))*365 
				END END 
		   ),ScriptCode Varchar(50)
					
         ) 

	    CREATE TABLE #Dividend 
        ( 
           membercode VARCHAR(100), 
           amount     FLOAT,
		   DivideScriptCode VARCHAR(Max) 
        ) 

	    INSERT INTO #Dividend 
	    SELECT   EQ.member_code, 
               Sum(EQ.amount) AS 'Amount',
			   EQ.Script_Code  
        FROM     EQDividend_Trans EQ          
        WHERE    EQ.member_code= @memcode
               AND EQ.Year_Code = @yearcode 
			   Group by EQ.member_code, EQ.Script_Code  
  
		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty FLOAT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT  
		DECLARE @tablerowscount INT
		DECLARE @Ac_Types VARCHAR(50) 
		IF(@status = 0) 
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
						@openingDate DATETIME,@openingRate FLOAT,@openingQty FLOAT,@openingAmount FLOAT,
						@purchaseDate DATETIME,@PurchaseBillNo  VARCHAR(50),@purchaseRate FLOAT,@purchaseQty FLOAT,@purchaseAmount FLOAT,
						@soldDate DATETIME,@soldBillNo  VARCHAR(50),@soldRate FLOAT,@soldQty FLOAT,@soldAmount FLOAT,
						@purchaseScriptId VARCHAR(50),@Consultant_Name  VARCHAR(100), 
						@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(10),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,@PurchaseIntraFlag VARCHAR(100),@SaleIntraFlag VARCHAR(10) 
				DECLARE @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@Bse_Rate float,@Nse_Rate float ,@ScriptId VARCHAR(10),@Dup_pkid int, @Pkid varchar(20),@idcount int,@Sr_No INT,@Dp_code VARCHAR(100),@Broker_code VARCHAR(100),@Consultant_code VARCHAR(20)

				CREATE TABLE #SCriptCodes
				(
					ScriptCode varchar(MAX)
				)

				IF(@ScriptCode != '')
					INSERT INTO #SCriptCodes SELECT value FROM Fn_split(@ScriptCode, ',') 
				ELSE 
					INSERT INTO #SCriptCodes select Script_Code from mst_script 

				CREATE TABLE #ConsultantCodes
				(
					ConsultantCodes varchar(MAX)
				)
				
				IF(@ConsultantCode = '0')	
					BEGIN
						SELECT DISTINCT p.member_code,p.year_code,
							STUFF((	SELECT DISTINCT ',' + p1.Consultant_Code
									FROM Mst_Consultant p1
									--WHERE p.member_code = p1.member_code AND p.year_code = p1.year_code
									FOR XML PATH(''), TYPE
									).value('.', 'NVARCHAR(MAX)')
							,1,1,'') ConsultantCode
						INTO #temoConsultant
						FROM Mst_Consultant p
						SET @ConsultantCode = (SELECT TOP(1) ConsultantCode FROM  #temoConsultant WHERE member_code = @memcode AND year_code = @yearcode)
						DROP TABLE #temoConsultant
					END
				 
				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes select Consultant_Code from Mst_Consultant

				SELECT	ROW_NUMBER ( ) OVER (ORDER BY t.script_code,t.Ac_Type,t.trans_dt ) AS NameId,
						t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,t.TransType,
						t.Ac_Type,t.Script_Code,t.Last_Date,t.Qty,
						Case When @IsWithTax = 0 Then t.Rate Else t.Exp_Rate END As 'Rate',--t.Rate,`
						max(isnull(dr.BSE_Rate,0))BSE_Rate,MAX(isnull(dr.NSE_Rate,0))NSE_Rate,
						t.Member_code,t.YearCode,t.Consultant_code,t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,t.Exp_Rate,t.FrmNm,t.ID,
						Ms.bse_code,Ms.nse_code,Ms.script_name,ma.ac_name AS 'Holding Type',
						CASE WHEN TransType		=	'Sold'								 THEN 'Sold'
						     WHEN (((t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101))AND t.TransType='Bought') THEN 'Opening'
							 WHEN TransType		=	'Bought' AND t.Bill_no =  'Bonus'	 THEN 'Bonus' 
							 WHEN TransType		=	'Bought' AND t.Bill_no =  'Rights'	 THEN 'Rights' 
							 WHEN TransType		=	'Bought' AND t.Bill_no =  'Split'	 THEN 'Split' 
							 WHEN TransType		=	'Bought' AND t.Bill_no =  'Transfer' THEN 'Transfer' 
							 WHEN TransType     =   'Bought' AND Frmnm =      'IPO'      THEN 'IPO'   
							 WHEN TransType     =   'Bought' AND Frmnm=       'MFDRI'    THEN 'Devidend Re-Investment'
							 WHEN t.TransType	=	'Bought' AND t.Bill_no <> 'Opening'  THEN 'Bought' 
							 
						END AS 'Flag_Type',
						cm.Consultant_Name--,t.isstock
				INTO #alldata 
				FROM brokerbill_trans t 
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN mst_account ma ON t.ac_type = ma.ac_code AND ma.member_code = @memcode
				LEFT JOIN Mst_Consultant    cm ON t.Consultant_code = cm.Consultant_code  
				LEFT JOIN DailyRate DR ON DR.Script_Code = Ms.script_code and dr.Trans_Dt=t.Trans_Dt

				WHERE  isfnobill = @Investmenttype 
				AND t.trans_dt <= @Todate
				AND t.member_code = @memcode AND yearcode = @yearcode  AND 
				Ac_Type =(CASE WHEN  @Ac_Type='0' THEN Ac_Type  ELSE  @Ac_Type END)
				AND  t.script_code IN (SELECT * FROM #SCriptCodes)
				AND	 t.Consultant_code IN (SELECT * FROM #ConsultantCodes)
				AND  ISNULL(t.isIntraDay,0) =(CASE WHEN ISNULL(@IsIntraDay,0)=0 THEN   ISNULL(isIntraDay,0) ELSE  ISNULL(@IsIntraDay,0) END) 
				AND t.MergedEntry = 0  AND ISNULL( t.Ref_SrNo,0) != 1
				AND (IsSLBS=0 OR IsSLBS IS NUll) 
				GROUP BY t.Trans_Dt,Trans_No,Sr_No,Bill_no,TransType,Ac_Type,t.Script_Code,MonthYear,Last_Date,LotSize,Qty,LotQty,Disp_qty,
				Bal_qty,G_Rate,Brok_Amt,ServTax_Amount,Rate,Amount,Stt_Amount,t.Member_Code,YearCode,t.Consultant_code,
				EntrySource,Ref_TransNo,Ref_SrNo,MergedEntry,isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,Brok_PerUnit,lockedbymerger,
				frac_Qty,Org_Trans_No,Org_SrNo,isDeleteMerger,isstock,ScripwiseExpense,isClient_code,isClient_Brokrage,c_Qty,C_Gross_Rate,
				C_Net_Rate,C_Amount,C_STT,C_STax,C_MisChg,TransactionChg,C_StampDuty,Exp_Rate,PerExp_Unit,FrmNm,ID,bse_code,nse_code,script_name,ma.AC_Name,cm.Consultant_Name
				 Order by NameId
						
				DECLARE @isIntradayCol INT 
				DECLARE  @COUNT INT=0
				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT id,Trans_No,script_name,Script_Code , [holding type],Ac_type,bill_no,CONVERT(DATETIME,trans_dt,101),qty,rate,ISNULL(qty, 0) * ISNULL(rate, 0),ISNULL(isintraday, 0),consultant_name,BSE_Rate,NSE_Rate   
				FROM #alldata
				WHERE ((TransType != 'Sold' AND #alldata.bill_no IN('Opening')) OR  CONVERT(date,trans_dt,101)  < CONVERT(date ,@StartYearDate,101)AND #alldata.TransType='Bought')
				 

				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type,@Ac_types, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@Bse_rate,@Nse_rate
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
						-- Insert All Openings

						IF(@Investmenttype=2)
							SET @holding_type='Mutual Fund'

						SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
						SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
						SET @Dup_pkid = ISNULL((Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end),0)
						SET @Dup_pkid = ISNULL(@Dup_pkid,0)
						SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
						SET @Dup_pkid = @Dup_pkid + 1
					
						
								INSERT INTO #mainoutputtable_1   (opening_bill_no ,id,Dup_pkid,ScriptCode,Trans_No,  Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,
								isintradaycol,consultant_name,bse_rate,nse_rate) 
								SELECT @billno,@ID, @Dup_pkid,@ScriptId ,@Trans_No, 'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Consultant_Name,@Bse_Rate,@Nse_Rate
							--END	
							   SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),0) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  

						IF(@idcount>0)
							BEGIN
								UPDATE #MainOutputtable_1 
								SET Dup_pkid = Dup_pkid + 1 
								WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
							END
			 			FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type,@Ac_types, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@Bse_rate,@Nse_rate
					END 
			
				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 
				DECLARE @salecount INT=0,@Boughtcount INT=0,@Flag_Type VARCHAR(50)
				
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
				
				SELECT id,Bill_no,Flag_Type,TransType,Script_Code,script_name,[holding type],Ac_type,Trans_No,CONVERT(DATETIME, trans_dt,101), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name,BSE_Rate,NSE_Rate
				FROM #alldata 
				WHERE   
				(TransType in('Bought','Sold')  OR CONVERT(DATE,trans_dt,101)  >= CONVERT(DATE ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
								
				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Ac_types, @Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name ,@BSE_Rate,@NSE_Rate
				
			WHILE (@@FETCH_STATUS = 0)
				BEGIN
					SET @COUNT = 0
					DECLARE @IsOpening	INT				=	0, 
					@prioritysId		INT				=	0,
					@str				VARCHAR(MAX)	=	''	, 
					@purchase_Op_Qty	FLOAT			=	0,
					@purchase_Op_Bill	VARCHAR(20)		=	'',
					@purchase_Op_Date	VARCHAR(20)		=	'',
					@purchase_Op_Rate	FLOAT			=	0,
					@PurQTY				FLOAT			=	0,
					@BalPurQTY			FLOAT			=	0,
					@BalSoldQTY			FLOAT			=	0,
					@Balpurchase_Op_Qty FLOAT			=	0,
					@BalOpeningQTY		FLOAT			=	0, 
					@Sold_Qty			FLOAT			=	0,
					@tempID				INT				=	0
							
					IF(@isIntradayCol=0)
						BEGIN
							IF(@Investmenttype=2)
									SET @holding_type='Mutual Fund'

							IF(@TransType LIKE '%Bought%')
								BEGIN

									-- Select * from #MainOutputtable_1
									/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */																
									SET @COUNT = (	SELECT COUNT(*) 
													FROM #MainOutputtable_1 
													WHERE holding_type = @holding_type 
													AND script_name = @scriptname 
													AND Flag_Type_Sold = 'Sold'  
													AND  Flag_Type = 'Sold' 
													AND ISNULL(sold_qty,0) !=0 
													AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) 
													AND isintradaycol = 0  
													AND consultant_name = (CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
								
									IF (@COUNT > 0)
										BEGIN
											SELECT  ROW_NUMBER ( ) OVER (ORDER BY  Ac_Type,scriptcode, CASE WHEN opening_date <> NULL THEN opening_date ELSE purchase_date END  ) AS NameId,* 
											INTO #tempSoldValExists 
											FROM #MainOutputtable_1 
											WHERE holding_type = @holding_type 
													AND script_name = @scriptname 
													AND Flag_Type_Sold = 'Sold'  
													AND  Flag_Type = 'Sold' 
													AND ISNULL(sold_qty,0) !=0 
													AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) 
													AND isintradaycol = 0  
													AND consultant_name = (CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
											ORDER BY NameId								
									
											DECLARE @R_Sold_COUNT FLOAT = ( SELECT COUNT(*) FROM #tempSoldValExists )
											DECLARE @Temppurchase_Op_Qty FLOAT 
											WHILE(@R_Sold_COUNT  > 0 )
												BEGIN
													DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists ORDER BY Dup_pkid,NameId)
													SET @str = @TransType

													SELECT TOP 1	@Sold_Qty		= sold_qty,
																	@soldDate		= sold_date,
																	@soldRate		= sold_Rate,
																	@soldBillNo		= sold_bill_no,
																	@Pkid			= Pkid
																	
													FROM #tempSoldValExists
													WHERE id  = @tempSaleID 
													SET @purchase_Op_Qty = @qty
														 
													IF(@TransType='Opening')
														BEGIN
															UPDATE #MainOutputtable_1  
															SET	opening_date=@dates,
																opening_rate=@rate,
																opening_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
														    	Flag_Type = 'Bought'
														    	WHERE  id = @tempSaleID  AND ISNULL(opening_qty,0)=0 AND pkid = @pkid
														END
													ELSE IF(@TransType = 'Bought')
														BEGIN
															UPDATE #MainOutputtable_1  
															SET	purchase_date=@dates,
																purchase_bill_no=@billno,
																purchase_rate=@rate,
																purchase_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																Flag_Type = 'Bought'
															WHERE  id = @tempSaleID  AND ISNULL(purchase_qty,0)=0 AND pkid = @pkid
														END
													if(@Sold_Qty > @purchase_Op_Qty )
														BEGIN
															UPDATE #MainOutputtable_1  
															SET	sold_qty = @purchase_Op_Qty 
															WHERE  id  = @tempSaleID AND Flag_Type_Sold='Sold' AND pkid = @pkid
														END
															
													DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND pkid = @pkid
													DECLARE @Balancedval   FLOAT = Round((ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)),6) /* This is related to pending sold qty from table. If it is Negative then 
														it will save into sale data else it is positive means Bought is greater So it will be inserted into Purchase Entry */
															
													SET @tablerowscount = (SELECT COUNT(*) FROM  #tempSoldValExists)
													IF(@Balancedval  < 0)
														BEGIN
														--	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															SET @soldQty = ABS(@Balancedval) 
															SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1) 
															SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
															INSERT INTO #MainOutputtable_1
																		(ID,Sr_No, Dup_pkid, DP_Code,ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Trans_No, Flag_Type,Flag_Type_Sold,  prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name, Trans_Type)
															VALUES		(@tempSaleID , @Sr_No, @Dup_pkid ,@DP_Code,@ScriptId,@Ac_Types ,@Broker_Code, @Consultant_code  ,@Trans_No,'Sold','Sold', @prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name,'Sold')
																	
															UPDATE #MainOutputtable_1 
															SET prioritys=@prioritysId+1  
															WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
															IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1 
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																	FROM Fn_split(@Pkid, ',') ) 
																END
																SET @Balancedval = 0

															BREAK;
														END
													ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
														BEGIN
															SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1
															SET @prioritysId = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1)

															IF(@TransType='Opening')
																BEGIN
																	INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name, Trans_Type)
																	VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId,@Ac_Types ,@Broker_Code,  @Consultant_code  ,'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name,@flag_Type)
																			
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No, ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name, Trans_Type)
																	VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId,@Ac_Types ,@Broker_Code, @Consultant_code  , 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name,@flag_Type)
																			
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																END
																SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
															IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1 
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																	FROM Fn_split(@Pkid, ',') ) 
																END
															ENd
													ELSE IF(@Balancedval=0)
														BEGIN
															break;
														END
													SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
													SET @qty = @Balancedval
															 
												END
											DROP TABLE #tempSoldValExists
										END
									/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
									ELSE
										BEGIN
											--SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
											--SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
											  SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
											  SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0)+1 from #mainoutputtable_1)

											INSERT INTO #mainoutputtable_1 (id,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type,Broker_Code, Consultant_code  , prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name, Trans_Type)
											VALUES ( @ID,@Sr_No, ISNULL(@Dup_pkid,0),@DP_Code,@Trans_No,@ScriptId,@Ac_Types,@Broker_Code, @Consultant_code  , @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name,@flag_Type) 
										END

								END	
							ELSE IF(@TransType LIKE '%Sold%')
								BEGIN
									/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
									--SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') AND ISNULL(sold_qty,0)=0  AND isnull(isintradaycol,0)=0 AND consultant_name= @Consultant_Name  )
									SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') AND ISNULL(sold_qty,0)=0  AND isnull(isintradaycol,0)=0 AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
									IF (@COUNT > 0)
									 	BEGIN
											DECLARE @Balanceval FLOAT
											SELECT ROW_NUMBER ( ) OVER (ORDER BY  Ac_type,ScriptCode,case when opening_date <> NULL then opening_date else purchase_date end) AS NameId,* 
											INTO #tempValExists 
											FROM
											#MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') 
											AND (consultant_name = CASE WHEN  @ConsultantCode <> '' THEN  @Consultant_Name ELSE consultant_name END) 
											AND ISNULL(sold_qty,0) = 0  AND isintradaycol = 0 
											ORDER BY NameId
													
											DECLARE @RCOUNT INT = (SELECT COUNT(*) FROM #tempValExists)
											DECLARE @TempSoldQty FLOAT 
													 
											WHILE(@RCOUNT > 0 )
												BEGIN 
													SET @Sold_Qty = @qty
														 
													SET @tempID = (SELECT TOP(1) id FROM #tempValExists ORDER BY dup_pkid)
													SET @str = (SELECT TOP(1) Flag_Type FROM #tempValExists WHERE id = @tempID  )
															
													IF(@str='Opening')
														BEGIN
															SELECT	TOP(1)	@TempSoldQty	= opening_qty,
																			@openingDate	= opening_date,
																			@openingrate	= opening_rate,
																			@Pkid			= Pkid
															FROM #tempValExists 
															WHERE id  = @tempID
														END
													ELSE IF(@str='Bought')
														BEGIN
															SELECT	TOP(1)	@TempSoldQty	= purchase_qty,
																			@PurchaseDate	= purchase_date,
																			@Purchaserate	= purchase_rate,
																			@PurchaseBillNo = purchase_bill_no,
																			@Pkid			= Pkid
															FROM #tempValExists 
															WHERE id  = @tempID
														END

													IF(@Sold_Qty > 0)
														BEGIN
															SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
															SET @prioritysId = ISNULL(@prioritysId,0)+1
															UPDATE #MainOutputtable_1  
																SET	
																	opening_qty     = CASE WHEN @str ='Opening'
																						THEN 
																							CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																						ELSE 0
																						END,
																	purchase_qty    = CASE WHEN @str ='Bought'
																						THEN 
																							CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																						END,
																	sold_date       = @dates,
																	sold_bill_no    = @billno,
																	sold_rate       = @rate,
																	sold_qty        = CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																	Flag_Type_Sold  = 'Sold',
																	prioritys       = @prioritysId
															WHERE  id = @tempID AND ISNULL(sold_qty,0)=0 AND pkid = @Pkid
															SET @Balanceval = Round((ABS(@Sold_Qty) - ABS(@TempSoldQty)),6)
														END
															
													DELETE FROM #tempValExists WHERE id = @tempID AND pkid = @pkid
													SET @tablerowscount = (SELECT COUNT(*) FROM  #tempValExists)
													SET @RCOUNT = @RCOUNT - 1
														
													IF(@Balanceval < 0)
														BEGIN
														--	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															--SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															--SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															--SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															--SET @Dup_pkid = @Dup_pkid + 1

															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1
																	 
															IF(@str='Opening')
																BEGIN
																	SET @openingQty = ABS(@Balanceval) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	INSERT INTO #MainOutputtable_1(ID,opening_bill_no, Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code,  Consultant_code  ,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@tempID,'Opening',@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																			
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
															
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId   
																	WHERE prioritys >= @prioritysId AND ID <> @tempID
																END
															ELSE 
																BEGIN
																	SET @PurchaseQty = ABS(@Sold_Qty) 
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																			
																	INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code, Consultant_code  , ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name, Trans_Type)
																	VALUES(@tempID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																			
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																			
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId    
																	WHERE prioritys >= @prioritysId AND ID <> @tempID
																END
																	 
																	
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT ISNULL(MAX(pkid),1) FROM #MainOutputtable_1)) END)  
															IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
																SET @Balanceval = 0
															BREAK;
														END
														
													ELSE IF(ISNULL(@Balanceval,0) > 0 and @tablerowscount=0)
														BEGIN
															--SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															--SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															--SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															--SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															--SET @Dup_pkid = @Dup_pkid + 1
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1


															SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
															INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code, Consultant_code  , ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
															VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	
															UPDATE #MainOutputtable_1 
															SET prioritys=@prioritysId+1  
															WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	
															IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1 
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																	FROM Fn_split(@Pkid, ',') ) 
																END
														END
													ELSE IF(ISNULL(@Balanceval,0) =0)
														BEGIN
															SET @Balanceval=0
															BREAK;
														END
																 
													SET @qty = @Balanceval
												END

										DROP TABLE #tempValExists
									END
									/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
									ELSE
										BEGIN
											--SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
											--SET @prioritysId = ISNULL(@prioritysId,0)+1
											SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #MainOutputtable_1)
											SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0)+1 from #MainOutputtable_1)

											INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type,Broker_Code, Consultant_code  ,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
											VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId, @Ac_Types,@Broker_Code, @Consultant_code  , 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
										END
											
									SET @purchase_Op_Date	=	''
									SET @purchase_Op_Rate	=	''
									SET @purchase_Op_Qty	=	''
									SET @purchase_Op_Bill	=	''
								END
						END
					ELSE IF(@isIntradayCol=1)
						BEGIN
							IF(@TransType LIKE '%Bought%')
								BEGIN
									/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
									--SELECT * FROM #MainOutputtable_1 --WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and ISNULL(Flag_Type,'')='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=1  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
									SET @COUNT = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold ='Sold' and  Flag_Type  = 'Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=1  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
									IF (@COUNT > 0)
										BEGIN
											SELECT  ROW_NUMBER ( ) OVER (ORDER BY   Ac_Type,scriptcode,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
											* INTO #tempBought	
											FROM	#MainOutputtable_1 
											WHERE script_name=@scriptname AND holding_type=@holding_type  
											AND isintradaycol=1 
											AND (consultant_name = CASE WHEN  @Consultant_Name <> '' THEN @Consultant_Name ELSE consultant_name END)
											AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
											AND Flag_Type_Sold =  'Sold'   AND  Flag_Type = 'Sold' AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
											ORDER BY NameId
													 
											DECLARE @Bought_COUNT INT = ( SELECT COUNT(*) FROM #tempBought )
											DECLARE @Temppurchase_Qty FLOAT 
											SET @purchase_Op_Qty = @qty
											DECLARE @Balance_val FLOAT
											WHILE(@Bought_COUNT  > 0)
												BEGIN 
													DECLARE @tempSale_ID INT = (SELECT TOP(1) id FROM #tempBought ORDER BY Dup_pkid)
													SET @str=@TransType

													SELECT	@Temppurchase_Qty		= sold_qty,
															@soldDate				= sold_date,
															@soldRate				= sold_rate,
															@soldBillNo				= sold_bill_no,
															@pkid					= pkid
													FROM #tempBought 
													WHERE id  = @tempSale_ID 

													SET @Sold_Qty= ABS(@Temppurchase_Qty)
															 
													IF(@TransType='Bought')
														BEGIN
															UPDATE #MainOutputtable_1  
															SET	purchase_date=@dates,
																purchase_bill_no=@billno,
																purchase_rate=@rate,
																purchase_qty= CASE	WHEN @Temppurchase_Qty > @purchase_Op_Qty 
																					THEN ABS(@purchase_Op_Qty) 
																					ELSE ABS(@Temppurchase_Qty) 
																				END,
																Flag_Type='Bought'
															WHERE  id = @tempSale_ID  and pkid=@pkid
														END
													IF(@Temppurchase_Qty > @purchase_Op_Qty )
														BEGIN
															UPDATE #MainOutputtable_1  
															SET sold_qty = ABS(@purchase_Op_Qty) 
															WHERE Flag_Type_Sold = 'Sold' 
															AND   id = @tempSale_ID   and pkid=@pkid
														END
															
													DELETE FROM #tempBought  WHERE id = @tempSale_ID 
													SET @Balance_val =  Round((isnull(@purchase_Op_Qty,0) - (@Sold_Qty)),6)
													SET @tablerowscount = (SELECT COUNT(*) FROM  #tempBought)
															
													SET @Bought_COUNT  = @Bought_COUNT  - 1
													SET @qty = @Balance_val

													IF(@Balance_val  < 0)
														BEGIN
															--SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															SET @soldQty = ABS(@Balance_val) 
															SET @prioritysId  =(SELECT MAX(prioritys) FROM #MainOutputtable_1 )--WHERE id=@tempSale_ID )
															SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
															INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Trans_No, Flag_Type,Flag_Type_sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name,Trans_Type)
															VALUES(@tempSale_ID ,@Sr_No, @Dup_pkid,@DP_Code,@ScriptId,@Ac_Types ,@Broker_Code, @Consultant_code  ,@Trans_No,'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balance_val),@soldRate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	
															UPDATE #MainOutputtable_1 
															SET prioritys=@prioritysId+1  
															WHERE prioritys >= @prioritysId AND ID<>@tempSale_ID 
																
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	
															IF(@idcount>0)
																BEGIN
 																	UPDATE #MainOutputtable_1
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																	FROM Fn_split(@Pkid, ',') ) 
																END

															BREAK;
														END
													ELSE IF(@Balance_val  > 0 and @tablerowscount = 0)
														BEGIN
															IF(@TransType='Bought')
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																			
																	INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No, ScriptCode,Ac_type ,Broker_Code, Consultant_code  , Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name,Trans_Type)
																	VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId,@Ac_Types ,@Broker_Code, @Consultant_code  , 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balance_val)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																			
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																			
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   
																			CONVERT(VARCHAR(200),pkid) NOT IN ( SELECT value FROM Fn_split(@Pkid, ',') ) 
																		END
																END
														ENd
													SET @purchase_Op_Qty= (@Balance_val)
												END

													
											DROP TABLE #tempBought
										END
									/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
									ELSE
										BEGIN
											--SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
											--SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
											SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
											SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0) + 1 from #mainoutputtable_1)

											INSERT INTO #mainoutputtable_1 (id,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type,Broker_Code, Consultant_code  , prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name,Trans_Type) 
											VALUES ( @ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId,@Ac_Types,@Broker_Code, @Consultant_code  , @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name,@Flag_Type) 
										END
								END	
							ELSE IF(@TransType LIKE '%Sold%')
								BEGIN
									/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
									SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer','Other') AND ISNULL(sold_qty,0)=0  AND isnull(isintradaycol,0)=1 AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
									IF (@COUNT > 0)
									 	BEGIN
											DECLARE @Balanceval_sold FLOAT
											SELECT ROW_NUMBER ( ) OVER (ORDER BY  Ac_type,ScriptCode,case when opening_date <> NULL then opening_date else purchase_date end ) AS NameId,* 
											INTO #tempSold 
											FROM #MainOutputtable_1
											WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer','Other') 
											AND (consultant_name = CASE WHEN  @ConsultantCode <> '' THEN  @Consultant_Name ELSE consultant_name END) 
											AND ISNULL(sold_qty,0) = 0  AND isintradaycol = 1 
											ORDER BY NameId
													
											DECLARE @RSoldCOUNT INT = (SELECT COUNT(*) FROM #tempSold)
											DECLARE @TempQty_Sold FLOAT 
												    
											WHILE(@RSoldCOUNT > 0 )
												BEGIN 
													SET @Sold_Qty = @qty
													SET @tempID  =   (SELECT TOP(1) id FROM #tempSold)
													SET @str     =   (SELECT TOP(1) Flag_Type FROM #tempSold WHERE id = @tempID  ORDER BY Dup_pkid,NameId)
													SET @pkid    =   (SELECT TOP(1) pkid  FROM #tempSold WHERE id  = @tempID )
															
													IF(@str='Bought')
														BEGIN
															SELECT	@TempQty_Sold	=	purchase_qty,
																	@PurchaseDate	=	purchase_date,
																	@Purchaserate	=	purchase_rate,
																	@PurchaseBillNo	=	purchase_bill_no
															FROM #tempSold 
															WHERE id  = @tempID 
														END
													IF(@Sold_Qty > 0)
														BEGIN
															SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
															SET @prioritysId = ISNULL(@prioritysId,0)+1
															UPDATE #MainOutputtable_1  
																SET	
																	purchase_qty  = CASE WHEN @str ='Bought'
																							THEN CASE	WHEN  @TempQty_Sold >= @Sold_Qty 
																									THEN @Sold_Qty 
																									ELSE @TempQty_Sold 
																								END
																						END,
																	sold_date      = @dates,
																	sold_bill_no   = @billno,
																	sold_rate      = @rate,
																	sold_qty       = CASE WHEN @TempQty_Sold > @Sold_Qty THEN @Sold_Qty ELSE @TempQty_Sold END,
																	Flag_Type_Sold = 'Sold',
																	prioritys      = @prioritysId
															WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND pkid = @pkid
															SET @Balanceval_sold = Round((ABS(@Sold_Qty) - ABS(@TempQty_Sold)),6)
														END
															
													DELETE FROM #tempSold WHERE id = @tempID
													SET @RSoldCOUNT = @RSoldCOUNT - 1
													SET @tablerowscount = (SELECT COUNT(*) FROM  #tempSold)
														
													IF(@Balanceval_sold < 0)
														BEGIN
															--SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															SET @PurchaseQty=ABS(@Sold_Qty) 
															SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
															SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
															INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code, Consultant_code  , ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name,Trans_Type)
															VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval_sold)  ,@Purchaserate,@isIntradayCol,@Consultant_Name,@Flag_Type)
																	
															SET @prioritysId = ISNULL(@prioritysId,0)+1
																	
															UPDATE #MainOutputtable_1 
															SET prioritys=@prioritysId    
															WHERE prioritys >= @prioritysId AND ID <> @tempID
																	
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
															IF(@idcount>0)
																BEGIN
																		UPDATE #MainOutputtable_1 
																		SET Dup_pkid = Dup_pkid + 1 
																		WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
															BREAK;
														END
													ELSE IF(ISNULL(@Balanceval_sold,0) > 0 AND @tablerowscount=0)
														BEGIN
															SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
															SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
															SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
															SET @Dup_pkid = ISNULL(@Dup_pkid,0)
															SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
															SET @Dup_pkid = @Dup_pkid + 1

															SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)

															INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,Ac_type,Broker_Code, Consultant_code  , ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
															VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@Ac_Types,@Broker_Code, @Consultant_code  ,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval_sold)  ,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)

															UPDATE #MainOutputtable_1 
															SET prioritys=@prioritysId+1  
															WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
															SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
															IF(@idcount>0)
																BEGIN
																	UPDATE #MainOutputtable_1 
																	SET Dup_pkid = Dup_pkid + 1 
																	WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value FROM Fn_split(@Pkid, ',') ) 
																END
														END
													SET @qty = @Balanceval_sold
												END	
											DROP TABLE #tempSold
										END
											
									/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
									ELSE
										BEGIN											
											SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
											SET @Dup_pkid =(select ISNULL(max(Dup_pkid),0) +1 from #mainoutputtable_1)

											INSERT INTO #MainOutputtable_1(ID,Sr_No, Dup_pkid,DP_Code,Trans_No,ScriptCode,Ac_type,Broker_Code, Consultant_code  ,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Trans_Type)
											VALUES(@ID,@Sr_No, @Dup_pkid,@DP_Code,@Trans_No,@ScriptId, @Ac_Types,@Broker_Code, @Consultant_code  , 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name,@Flag_Type)
										END
											
									SET @purchase_Op_Date	=	''
									SET @purchase_Op_Rate	=	''
									SET @purchase_Op_Qty	=	''
									SET @purchase_Op_Bill	=	''
								END

						END
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Ac_types, @Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name ,@BSE_Rate,@NSE_Rate
						END 			
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 

		if(@IsBSEISIN=1)
		BEGIN
				INSERT INTO #mainoutputtable_1_BSEISINNO 				
				SELECT ma.pkid,ma.Dup_pkid,ma.Trans_No,ma.Ac_type,ma.id,ma.sr_no, ma.prioritys,ma.Trans_Type, ma.Split_Type, ma.Flag_Type, ma.Flag_Type_Sold,ma.flag_script_name,
				ma.flag_holding_type,  
				ma.script_name + '[' +ms.BSE_Code + ']' + '[' +ms.ISIN_No+ ']',ma.holding_type,ma.opening_bill_no ,ma.opening_date ,ma.opening_qty,ma.opening_rate ,ma.opening_amount ,ma.purchase_date ,ma.purchase_bill_no ,
				ma.purchase_qty,ma.purchase_rate,ma.purchase_amount ,ma.sold_date ,ma.sold_bill_no ,ma.sold_qty,ma.sold_rate,ma.sold_amount ,ma.gain_loss ,ma.closing_qty,
				ma.closing_rate,ma.closing_value,ma.short_term,ma.long_term,ma.speculation ,ma.gain_speculation ,ma.loss_speculation ,ma.consultant_name ,ma.nse_rate ,ma.bse_rate, 
				ma.NoOfDays,ma.ROI,ma.[Actual ROI],ma.[Monthly ROI],ma.[Anually ROI],ma.isintradaycol,ma.[type],ma.ScriptCode ,ma.Broker_Code,ma.Dp_code ,ma.Consultant_code 
				from #mainoutputtable_1 ma 
				INNER JOIN Mst_Script Ms On  ma.ScriptCode=Ms.Script_Code
		END
		ELSE if(@IsBSEISIN=0)
			BEGIN
			   
				INSERT INTO #mainoutputtable_1_BSEISINNO 				
				SELECT ma.pkid,ma.Dup_pkid,ma.Trans_No,ma.Ac_type,ma.id,ma.sr_no, ma.prioritys,ma.Trans_Type, ma.Split_Type, ma.Flag_Type, ma.Flag_Type_Sold,ma.flag_script_name,
				ma.flag_holding_type,ma.script_name,ma.holding_type,ma.opening_bill_no ,ma.opening_date ,ma.opening_qty,ma.opening_rate ,ma.opening_amount ,ma.purchase_date ,ma.purchase_bill_no ,
				ma.purchase_qty,ma.purchase_rate,ma.purchase_amount ,ma.sold_date ,ma.sold_bill_no ,ma.sold_qty,ma.sold_rate,ma.sold_amount ,ma.gain_loss ,ma.closing_qty,
				ma.closing_rate,ma.closing_value,ma.short_term,ma.long_term,ma.speculation ,ma.gain_speculation ,ma.loss_speculation ,ma.consultant_name ,ma.nse_rate ,ma.bse_rate, 
				ma.NoOfDays,ma.ROI,ma.[Actual ROI],ma.[Monthly ROI],ma.[Anually ROI],ma.isintradaycol,ma.[type],ma.ScriptCode ,ma.Broker_Code,ma.Dp_code ,ma.Consultant_code 
				from #mainoutputtable_1 ma 
				
		END
		IF(@Investmenttype=2)
			BEGIN
				INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no ,id,Trans_No, prioritys,ScriptCode,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss , closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type])

				SELECT 
				ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,Pkid,case when CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) else CONVERT(DATE,purchase_date,103) END,prioritys DESC, sold_date DESC ) AS NameId,
				opening_bill_no ,id,Trans_No, prioritys,ScriptCode,script_name,'Empty', flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount , 
				   Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				closing_qty,closing_rate ,Round(closing_value,4) ,
				CASE WHEN isintradaycol = 0 AND ( (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365)) --short term for purchase
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
						
				CASE WHEN  isintradaycol = 0 AND ((opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365)) --short term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  isintradaycol = 1 AND  (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol,Trans_Type 
				FROM #mainoutputtable_1_BSEISINNO 
				ORDER BY NameId
			END
		ELSE
			BEGIN
				INSERT INTO #mainoutputtable_1_Final (OrderBy,id,Trans_No, prioritys,ScriptCode,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss , closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol,[type])

				SELECT 
				ROW_NUMBER ( ) OVER (ORDER BY   holding_type,ScriptCode,-- Pkid,
			   case  WHEN  Dup_pkid is Null Then Pkid
				    WHEN  Dup_pkid is NOt Null then Dup_pkid 
				    else Dup_pkid end,prioritys,
			    Case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
					 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
					 ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,

				id,Trans_No, prioritys,ScriptCode,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,
				   Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN isintradaycol = 0 AND  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) <= 365)     -- short term for openings
						THEN  ISNULL(sold_rate ,0)* ISNULL(sold_qty ,0)- ISNULL(opening_rate,0)*ISNULL(opening_qty ,0)
					 WHEN isintradaycol = 0 AND (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) <= 365)  -- short term for purchase
						THEN  ISNULL(sold_rate ,0)* ISNULL(sold_qty ,0)- ISNULL(purchase_rate,0)*ISNULL(purchase_qty ,0)
					 ELSE 0.0 END,
				CASE WHEN isintradaycol = 0 AND ((opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365)) --short term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  isintradaycol = 1 AND (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate * purchase_qty ELSE 0.0 END,
				0, 0, consultant_name , nse_rate , bse_rate , 1 sort, isintradaycol,Trans_Type 
				FROM #mainoutputtable_1_BSEISINNO 
			END
		IF(@OUTPUT_Flag='Details')
			BEGIN		
				IF(@Investmenttype!=2)
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN 
							   UPDATE #mainoutputtable_1_Final SET prioritys=0
				               DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
				               UPDATE #mainoutputtable_1_Final
				               SET prioritys  = @i , @i = @i + 1

								SELECT id,prioritys,  ScriptCode,script_name 'Script Name',Holding_Type,opening_bill_no,
								CONVERT(datetime, opening_date,101) 'Opening Date',opening_qty 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
								CONVERT(datetime, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',isnull(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
								CONVERT(datetime, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',isnull(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',isnull(sold_amount,0) 'Sold Amount',
								ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
								ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
								ISNULL(short_term,0) short_term,ISNULL(long_term,0) long_term,ISNULL(speculation,0) speculation,
								CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
								CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
								 consultant_name,nse_rate,bse_rate,isintradaycol,
								NoOfDays,

								CASE 
									WHEN ISNULL(Opening_Amount,0) != 0  THEN  (ISNULL(Gain_Loss ,0)/ NULLIF(Opening_Amount,0)) * 100 
									WHEN ISNULL(Purchase_Amount,0) != 0 THEN  (ISNULL(Gain_Loss,0)/ NULLIF(Purchase_Amount,0)) * 100	END AS 	'ROI',

								CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0) ELSE
								CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN ((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0) END END AS 'Actual ROI',

								CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0))  * 30  ELSE
								CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN (((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 30 END END AS 'Monthly ROI',
								
								(CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN (((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 365 ELSE
								 CASE WHEN ISNULL(Purchase_Amount,0)!=0 THEN  (((ISNULL(Gain_Loss ,0)/ NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0))*365 END END ) AS 'Anually ROI',
								 ISNULL(bse_rate,0)bse_rate,ISNULL(nse_rate,0)nse_rate,1 sort,[type] 
								FROM #mainoutputtable_1_Final
								WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
								ORDER By consultant_name,Holding_Type,script_name
							END
						ELSE
							BEGIN
							   UPDATE #mainoutputtable_1_Final SET prioritys=0
			                   DECLARE @iv INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
				               UPDATE #mainoutputtable_1_Final
				               SET prioritys  = @iv , @iv = @iv + 1

								SELECT id,prioritys,  ScriptCode,script_name 'Script Name',Holding_Type,opening_bill_no,
								CONVERT(datetime, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
								CONVERT(datetime, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',isnull(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
								CONVERT(datetime, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
								ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
								ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
								ISNULL(short_term,0) short_term, ISNULL(long_term,0) long_term,ISNULL(speculation,0) speculation,
								CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
								CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
								'' consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,isintradaycol,
								ISNULL(NoOfDays,0)NoOfDays,
								CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100 
									 WHEN ISNULL(Purchase_Amount,0) != 0 THEN  (ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0)) * 100	
									 END AS 	'ROI',

								CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0) ELSE
								CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN ((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0) 
									END END AS 'Actual ROI',

								CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0))  * 30  ELSE
								CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 30 
									END END AS 'Monthly ROI',

								(CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 365 ELSE
								CASE WHEN ISNULL(Purchase_Amount,0)!=0 THEN  (((ISNULL(Gain_Loss ,0) / NULLIF(Purchase_Amount,0))*100) / NULLIF(NoOfDays,0))*365 
									END END ) AS 'Anually ROI',
								ISNULL(bse_rate,0)bse_rate,ISNULL(nse_rate,0)nse_rate,
								1 sort,[type] 
								FROM #mainoutputtable_1_Final
								WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
								ORDER BY  script_name,Holding_Type--,id
								 
							END
					END
				ELSE
					IF(@ConsultantCode <> '')
						BEGIN

						   UPDATE #mainoutputtable_1_Final SET prioritys=0
						   DECLARE @ii INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
						   UPDATE #mainoutputtable_1_Final
						   SET prioritys  = @ii , @ii = @ii + 1


							SELECT id,prioritys,ScriptCode,script_name 'Script Name',Holding_Type,opening_bill_no,
							CONVERT(DATETIME, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
							CONVERT(DATETIME, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
							CONVERT(DATETIME, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
							ISNULL(gain_loss,0) 'Gain/Loss',ISNULL(gain,0) 'Gain',ISNULL(loss,0) 'Loss',ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
							ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
							CASE WHEN isintradaycol=1 and ISNULL(gain,0)!=0 THEN gain  ELSE '' END gain_speculation,
							CASE WHEN isintradaycol=1 and ISNULL(loss,0)!=0  THEN loss  ELSE '' END loss_speculation,
							consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,ISNULL(isintradaycol,0)isintradaycol,
							ISNULL(NoOfDays,0)NoOfDays,

							CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100 
								 WHEN ISNULL(Purchase_Amount,0) != 0 THEN  (ISNULL(Gain_Loss,0)/NULLIF(Purchase_Amount,0)) * 100	END AS 	'ROI',

							CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0) ELSE
							CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN ((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0) END END AS 'Actual ROI',

							CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0))  * 30  ELSE
							CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 30 
							END END AS 'Monthly ROI',

							(CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 365 ELSE
							CASE WHEN ISNULL(Purchase_Amount,0)!=0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0))*100) / NULLIF(NoOfDays,0))*365 
							END END ) AS 'Anually ROI', 
							1 sort,[type] 
							FROM #mainoutputtable_1_Final
							WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
					 
							--ORDER By consultant_name,script_name
							Order By prioritys,consultant_name, Holding_Type,script_name,id
					END
					ELSE
						BEGIN
						    
						   UPDATE #mainoutputtable_1_Final SET prioritys=0
						   DECLARE @iii INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
						   UPDATE #mainoutputtable_1_Final
						   SET prioritys  = @iii , @iii = @iii + 1

						--   Select * from #mainoutputtable_1_Final

							SELECT id,prioritys,  ScriptCode,script_name 'Script Name',Holding_Type,opening_bill_no,
							CONVERT(DATETIME, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
							CONVERT(DATETIME, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
							CONVERT(DATETIME, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
							ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
							ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
							ISNULL(short_term,0) short_term,ISNULL(long_term,0) long_term,ISNULL(speculation,0) speculation,
							CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
							CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
							'' consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,ISNULL(isintradaycol,0)isintradaycol,
							ISNULL(NoOfDays,0)NoOfDays,

							CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100 
							WHEN ISNULL(Purchase_Amount,0) != 0 THEN  (ISNULL(Gain_Loss,0)/ NULLIF(Purchase_Amount,0)) * 100	END AS 	'ROI',

							CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0) ELSE
							CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN ((ISNULL(Gain_Loss ,0)/ NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0) END END AS 'Actual ROI',

							CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0))  * 30  ELSE
							CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 30 
							END END AS 'Monthly ROI',

							(CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 365 ELSE
							CASE WHEN ISNULL(Purchase_Amount,0)!=0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0))*100) / NULLIF(NoOfDays,0))*365 
							END END ) AS 'Anually ROI',
							ISNULL(bse_rate,0) bse_rate ,ISNULL(nse_rate,0) nse_rate,1 sort,[type] 
							FROM #mainoutputtable_1_Final
							WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  						
							--ORDER BY prioritys, Holding_Type,script_name,id
							ORDER BY prioritys,id,script_name
						END
			END		
		ELSE IF(@OUTPUT_Flag='AllData')
		
			BEGIN
			  -- Select * from #mainoutputtable_1_Final
				SELECT  prioritys ,Trans_No,id ,  ScriptCode,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,
				CONVERT(DATETIME, opening_date,101),ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),
				CONVERT(DATETIME, purchase_date,101),purchase_bill_no,ISNULL(purchase_qty ,0),ISNULL(purchase_rate ,0),ISNULL(purchase_amount ,0),
				CONVERT(DATETIME, sold_date,101) ,sold_bill_no ,ISNULL(sold_qty ,0),ISNULL(sold_rate,0),ISNULL(sold_amount ,0),
				ISNULL(gain_loss ,0)gain_loss,ISNULL(gain ,0)gain ,ISNULL(loss,0)loss,ISNULL(closing_qty ,0)closing_qty ,ISNULL(closing_rate ,0)closing_rate ,ISNULL(closing_value ,0)closing_value ,
				ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,ISNULL(gain_speculation,0)gain_speculation,ISNULL(loss_speculation,0)loss_speculation,consultant_name,
				ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol,
				ISNULL(NoOfDays,0) NoOfDays,0 	'ROI',0 'Actual ROI',0 'Monthly ROI',0 'Anually ROI'
				FROM #mainoutputtable_1_Final
				ORDER BY Holding_Type,script_name
			END
		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal' AND @isDIVIDEND=0)
			 BEGIN
				SELECT 0 id,0 prioritys,  ScriptCode,script_name 'Script Name',Holding_Type,
				'' opening_bill_no,NULL 'Opening Date',SUM(ISNULL(opening_qty,0)) 'Opening Qty',  ISNULL((SUM(ISNULL(opening_amount,0))  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate',SUM(ISNULL(opening_amount,0)) 'Opening Amount',
				NULL 'Purchase Date','' 'Purchase BillNo',SUM(ISNULL(purchase_qty,0)) 'Purchase Qty', ISNULL((SUM(ISNULL(Purchase_amount,0))  / NULLIF(SUM(Purchase_qty),0)),0)  'Purchase Rate',SUM(ISNULL(purchase_amount,0)) 'Purchase Amount',
				NULL 'Sold Date','' 'Sold BillNo',SUM(ISNULL(sold_qty,0)) 'Sold Qty',ISNULL((SUM(ISNULL(Sold_amount,0))  / NULLIF(SUM(ISNULL(Sold_qty,0)),0)),0) 'Sold Rate',SUM(ISNULL(ISNULL(sold_amount,0),0)) 'Sold Amount',
				SUM(ISNULL(gain_loss,0)) 'Gain/Loss',CASE WHEN SUM((ISNULL(gain_loss,0))) > 0 THEN SUM(ISNULL(gain_loss,0)) ELSE 0 END  AS 'Gain',
				CASE WHEN SUM((ISNULL(gain_loss,0))) < 0 THEN SUM(ISNULL(gain_loss,0)) ELSE 0 END  AS  'Loss',ISNULL(SUM(closing_qty),0) 'Closing Qty',
				SUM(ISNULL(closing_rate,0)) 'Closing Rate',SUM(ISNULL(closing_value,0)) 'Closing Value',
				SUM(ISNULL(short_term,0)) short_term,
				SUM(ISNULL(long_term,0)) long_term,
				SUM(ISNULL(speculation,0)) speculation,
				SUM( gain_speculation)gain_speculation,
				SUM( loss_speculation)loss_speculation,
				'' consultant_name,SUM(ISNULL(nse_rate,0)),SUM(ISNULL(bse_rate,0)),0  isintradaycol ,
				SUM(ISNULL(NoOfDays,0)) NoOfDays ,
				CASE 
				WHEN  SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100 WHEN SUM(ISNULL(Purchase_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / SUM(ISNULL(Purchase_Amount,0))) * 100	END AS 	'ROI',

				CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100 /  NULLIF(SUM(ISNULL(NoOfDays,0)),0) ELSE
				CASE WHEN SUM(ISNULL(Purchase_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Purchase_Amount,0)),0)) * 100  / NULLIF(SUM(ISNULL(NoOfDays,0)),0) END END AS 'Actual ROI',

				CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(Opening_Amount),0)) * 100 /  NULLIF(SUM(ISNULL(NoOfDays,0)),0)   * 30  ELSE
				CASE WHEN SUM(ISNULL(Purchase_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(Purchase_Amount),0)) * 100 / NULLIF(SUM(ISNULL(NoOfDays,0)),0) * 30 
				END END AS 'Monthly ROI',

				CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN   ((SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100  / NULLIF(SUM(ISNULL(NoOfDays,0)),0))  * 365 ELSE
				CASE WHEN SUM(ISNULL(Purchase_Amount,0)) !=0 
				THEN   (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Purchase_Amount,0)),0)) * 100  / NULLIF(SUM(ISNULL(NoOfDays,0)),0) * 365 
				END END   AS 'Anually ROI',1 sort 
				FROM  
				(
				SELECT 0 id,0 prioritys,  ScriptCode,script_name 'script_name', Holding_Type,
				'' opening_bill_no,NULL 'Opening Date',SUM(ISNULL(opening_qty,0)) 'opening_qty',  ISNULL((SUM(ISNULL(opening_amount,0))  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening_Rate',
				SUM(ISNULL(opening_amount,0)) 'opening_amount',
				NULL 'Purchase Date','' 'Purchase BillNo',SUM(ISNULL(purchase_qty,0)) 'purchase_qty', ISNULL((SUM(ISNULL(Purchase_amount,0))  / NULLIF(SUM(Purchase_qty),0)),0)  'Purchase_Rate',
				SUM(ISNULL(purchase_amount,0)) 'purchase_amount',
				NULL 'Sold Date','' 'Sold BillNo',SUM(ISNULL(sold_qty,0)) 'sold_qty',ISNULL((SUM(ISNULL(Sold_amount,0))  / NULLIF(SUM(ISNULL(Sold_qty,0)),0)),0) 'Sold_Rate',
				SUM(ISNULL(ISNULL(sold_amount,0),0)) 'sold_amount',
				SUM(ISNULL(gain_loss,0)) 'gain_loss',CASE WHEN SUM((ISNULL(gain_loss,0))) > 0 THEN SUM(ISNULL(gain_loss,0)) ELSE 0 END  AS 'Gain',
				CASE WHEN SUM((ISNULL(gain_loss,0))) < 0 THEN SUM(ISNULL(gain_loss,0)) ELSE 0 END  AS  'Loss',ISNULL(SUM(closing_qty),0) 'closing_qty',
				SUM(ISNULL(closing_rate,0)) 'closing_rate',SUM(ISNULL(closing_value,0)) 'closing_value',
				SUM(ISNULL(short_term,0)) short_term,
				SUM(ISNULL(long_term,0)) long_term,
				SUM(ISNULL(speculation,0)) speculation,
				CASE WHEN ISNULL(isintradaycol,0)=1 AND SUM(ISNULL(gain,0)) != 0 THEN SUM(ISNULL(gain,0))  ELSE '' END gain_speculation,
				CASE WHEN ISNULL(isintradaycol,0)=1 AND SUM(ISNULL(loss,0)) != 0  THEN SUM(ISNULL(loss,0))  ELSE '' END loss_speculation,
				'' consultant_name,SUM(ISNULL(nse_rate,0))nse_rate,SUM(ISNULL(bse_rate,0))bse_rate,ISNULL(isintradaycol,0)isintradaycol,
				SUM(ISNULL(NoOfDays,0)) NoOfDays,
				CASE  WHEN  SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100 WHEN SUM(ISNULL(Purchase_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / SUM(ISNULL(Purchase_Amount,0))) * 100	END AS 	'ROI',

				CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100 /  NULLIF(SUM(ISNULL(NoOfDays,0)),0) ELSE
				CASE WHEN SUM(ISNULL(Purchase_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Purchase_Amount,0)),0)) * 100  / NULLIF(SUM(ISNULL(NoOfDays,0)),0) END END AS 'Actual ROI',

				CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(Opening_Amount),0)) * 100 /  NULLIF(SUM(ISNULL(NoOfDays,0)),0)   * 30  ELSE
				CASE WHEN SUM(ISNULL(Purchase_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(Purchase_Amount),0)) * 100 / NULLIF(SUM(ISNULL(NoOfDays,0)),0) * 30 
				END END AS 'Monthly ROI',

				CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN   ((SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100  / NULLIF(SUM(ISNULL(NoOfDays,0)),0))  * 365 ELSE
				CASE WHEN SUM(ISNULL(Purchase_Amount,0)) !=0 
				THEN   (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Purchase_Amount,0)),0)) * 100  / NULLIF(SUM(ISNULL(NoOfDays,0)),0) * 365 
				END END   AS 'Anually ROI',1 sort 
				FROM #mainoutputtable_1_Final
				WHERE ( (opening_qty) != 0  or  (purchase_qty) != 0  or  (sold_qty) != 0)  
				GROUP BY ScriptCode,script_name  ,Holding_Type,isintradaycol
				)a
				GROUP BY ScriptCode,script_name  ,Holding_Type--,isintradaycol
				ORDER BY  script_name,Holding_Type 
			END		
			ELSE IF(@OUTPUT_Flag='ScriptWiseTotal' AND @isDIVIDEND=1)
			 BEGIN
			-- Select * from #Dividend
				SELECT 0 id,0 prioritys,  ScriptCode,script_name 'Script Name',Holding_Type,
				'' opening_bill_no,NULL 'Opening Date',SUM(ISNULL(opening_qty,0)) 'Opening Qty',  ISNULL((SUM(ISNULL(opening_amount,0))  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate',SUM(ISNULL(opening_amount,0)) 'Opening Amount',
				NULL 'Purchase Date','' 'Purchase BillNo',SUM(ISNULL(purchase_qty,0)) 'Purchase Qty', ISNULL((SUM(ISNULL(Purchase_amount,0))  / NULLIF(SUM(Purchase_qty),0)),0)  'Purchase Rate',SUM(ISNULL(purchase_amount,0)) 'Purchase Amount',
				NULL 'Sold Date','' 'Sold BillNo',SUM(ISNULL(sold_qty,0)) 'Sold Qty',ISNULL((SUM(ISNULL(Sold_amount,0))  / NULLIF(SUM(ISNULL(Sold_qty,0)),0)),0) 'Sold Rate',SUM(ISNULL(ISNULL(sold_amount,0),0)) 'Sold Amount',
				SUM(ISNULL(gain_loss,0)) 'Gain/Loss',CASE WHEN SUM((ISNULL(gain_loss,0))) > 0 THEN SUM(ISNULL(gain_loss,0)) ELSE 0 END  AS 'Gain',
				CASE WHEN SUM((ISNULL(gain_loss,0))) < 0 THEN SUM(ISNULL(gain_loss,0)) ELSE 0 END  AS  'Loss',ISNULL(SUM(closing_qty),0) 'Closing Qty',
				SUM(ISNULL(closing_rate,0)) 'Closing Rate',SUM(ISNULL(closing_value,0)) 'Closing Value',
				SUM(ISNULL(short_term,0)) short_term,
				SUM(ISNULL(long_term,0)) long_term,
				SUM(ISNULL(speculation,0)) speculation,
				SUM( gain_speculation)gain_speculation,
				SUM( loss_speculation)loss_speculation,
				'' consultant_name,SUM(ISNULL(nse_rate,0)),SUM(ISNULL(bse_rate,0)),0  isintradaycol ,
				SUM(ISNULL(NoOfDays,0)) NoOfDays ,
				CASE 
				WHEN  SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100 WHEN SUM(ISNULL(Purchase_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / SUM(ISNULL(Purchase_Amount,0))) * 100	END AS 	'ROI',

				CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100 /  NULLIF(SUM(ISNULL(NoOfDays,0)),0) ELSE
				CASE WHEN SUM(ISNULL(Purchase_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Purchase_Amount,0)),0)) * 100  / NULLIF(SUM(ISNULL(NoOfDays,0)),0) END END AS 'Actual ROI',

				CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(Opening_Amount),0)) * 100 /  NULLIF(SUM(ISNULL(NoOfDays,0)),0)   * 30  ELSE
				CASE WHEN SUM(ISNULL(Purchase_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(Purchase_Amount),0)) * 100 / NULLIF(SUM(ISNULL(NoOfDays,0)),0) * 30 
				END END AS 'Monthly ROI',

				CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN   ((SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100  / NULLIF(SUM(ISNULL(NoOfDays,0)),0))  * 365 ELSE
				CASE WHEN SUM(ISNULL(Purchase_Amount,0)) !=0 
				THEN   (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Purchase_Amount,0)),0)) * 100  / NULLIF(SUM(ISNULL(NoOfDays,0)),0) * 365 
				END END   AS 'Anually ROI',1 sort ,ISNULL(a.Amount,0) As'DividendAmount'
				FROM  
				(
				SELECT 0 id,0 prioritys, ScriptCode,script_name 'script_name', Holding_Type,
				'' opening_bill_no,NULL 'Opening Date',SUM(ISNULL(opening_qty,0)) 'opening_qty',  ISNULL((SUM(ISNULL(opening_amount,0))  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening_Rate',
				SUM(ISNULL(opening_amount,0)) 'opening_amount',
				NULL 'Purchase Date','' 'Purchase BillNo',SUM(ISNULL(purchase_qty,0)) 'purchase_qty', ISNULL((SUM(ISNULL(Purchase_amount,0))  / NULLIF(SUM(Purchase_qty),0)),0)  'Purchase_Rate',
				SUM(ISNULL(purchase_amount,0)) 'purchase_amount',
				NULL 'Sold Date','' 'Sold BillNo',SUM(ISNULL(sold_qty,0)) 'sold_qty',ISNULL((SUM(ISNULL(Sold_amount,0))  / NULLIF(SUM(ISNULL(Sold_qty,0)),0)),0) 'Sold_Rate',
				SUM(ISNULL(ISNULL(sold_amount,0),0)) 'sold_amount',
				SUM(ISNULL(gain_loss,0)) 'gain_loss',CASE WHEN SUM((ISNULL(gain_loss,0))) > 0 THEN SUM(ISNULL(gain_loss,0)) ELSE 0 END  AS 'Gain',
				CASE WHEN SUM((ISNULL(gain_loss,0))) < 0 THEN SUM(ISNULL(gain_loss,0)) ELSE 0 END  AS  'Loss',ISNULL(SUM(closing_qty),0) 'closing_qty',
				SUM(ISNULL(closing_rate,0)) 'closing_rate',SUM(ISNULL(closing_value,0)) 'closing_value',
				SUM(ISNULL(short_term,0)) short_term,
				SUM(ISNULL(long_term,0)) long_term,
				SUM(ISNULL(speculation,0)) speculation,
				CASE WHEN ISNULL(isintradaycol,0)=1 AND SUM(ISNULL(gain,0)) != 0 THEN SUM(ISNULL(gain,0))  ELSE '' END gain_speculation,
				CASE WHEN ISNULL(isintradaycol,0)=1 AND SUM(ISNULL(loss,0)) != 0  THEN SUM(ISNULL(loss,0))  ELSE '' END loss_speculation,
				'' consultant_name,SUM(ISNULL(nse_rate,0))nse_rate,SUM(ISNULL(bse_rate,0))bse_rate,ISNULL(isintradaycol,0)isintradaycol,
				SUM(ISNULL(NoOfDays,0)) NoOfDays,
				CASE  WHEN  SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100 WHEN SUM(ISNULL(Purchase_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / SUM(ISNULL(Purchase_Amount,0))) * 100	END AS 	'ROI',

				CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100 /  NULLIF(SUM(ISNULL(NoOfDays,0)),0) ELSE
				CASE WHEN SUM(ISNULL(Purchase_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Purchase_Amount,0)),0)) * 100  / NULLIF(SUM(ISNULL(NoOfDays,0)),0) END END AS 'Actual ROI',

				CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(Opening_Amount),0)) * 100 /  NULLIF(SUM(ISNULL(NoOfDays,0)),0)   * 30  ELSE
				CASE WHEN SUM(ISNULL(Purchase_Amount,0)) != 0 
				THEN  (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(Purchase_Amount),0)) * 100 / NULLIF(SUM(ISNULL(NoOfDays,0)),0) * 30 
				END END AS 'Monthly ROI',

				CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0 
				THEN   ((SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100  / NULLIF(SUM(ISNULL(NoOfDays,0)),0))  * 365 ELSE
				CASE WHEN SUM(ISNULL(Purchase_Amount,0)) !=0 
				THEN   (SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Purchase_Amount,0)),0)) * 100  / NULLIF(SUM(ISNULL(NoOfDays,0)),0) * 365 
				END END   AS 'Anually ROI',1 sort ,EQ.Amount
				FROM #mainoutputtable_1_Final
				Left Join #Dividend  EQ On EQ.DivideScriptCode=#mainoutputtable_1_Final.ScriptCode
				WHERE ( (opening_qty) != 0  or  (purchase_qty) != 0  or  (sold_qty) != 0)  
				GROUP BY #mainoutputtable_1_Final.ScriptCode,script_name  ,Holding_Type,isintradaycol,EQ.amount,EQ.DivideScriptCode
				)a
				GROUP BY ScriptCode,script_name  ,Holding_Type,a.Amount--,isintradaycol
				ORDER BY  script_name,Holding_Type 
			END

		DROP TABLE #mainoutputtable_1 
		DROP TABLE #mainoutputtable_1_BSEISINNO
		DROP TABLE #alldata 
  END  




















































GO
/****** Object:  StoredProcedure [dbo].[proc_Stockposition_Equity_ROI_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockposition_Equity_ROI_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Stockposition_Equity_ROI_Summary] AS' 
END
GO




--Execute  proc_Stockposition_Equity_ROI_Summary    0,0,'0','Y0001','1120172018','2015-02-01 12:00:00:00','2018-03-28 03:50:37:50','','','','', '0' ,'0',0
--Execute  proc_Stockholdingposition_Equity_Summary    0,0,'0','M0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0',1,1,1
ALTER PROCEDURE [dbo].[proc_Stockposition_Equity_ROI_Summary]  --''
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,
@DateWiseClosinStock as bit, @IsWithTax bit = 0,@IsBSEISIN bit=0,@isDIVIDEND bit=0)
AS
BEGIN
SET NOCOUNT ON;
		CREATE TABLE #mainoutputtable_1_Final_Summary  
        ( 
           prioritys INT,Trans_No VARCHAR(50), id INT,script_Code  VARCHAR(50),script_name  VARCHAR(500),holding_type VARCHAR(200),flag_script_name VARCHAR(500),
		   flag_holding_type VARCHAR(200),opening_date datetime,opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
           purchase_date datetime,purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
           sold_date datetime,sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0,
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   closing_Date  AS 
			   CASE WHEN closing_qty < 0 THEN sold_date ELSE
			   CASE WHEN ISNULL(opening_date,'') != '' THEN opening_date ELSE
			   CASE WHEN ISNULL(purchase_date,'') != '' THEN purchase_date ELSE '' 
								END END END,

		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   Other_amt FLOAT DEFAULT 0,
		   ServTax_Amt FLOAT DEFAULT 0,
		   Stt_amt FLOAT DEFAULT 0,
		   sort   VARCHAR(5),
		   isintradaycol  INT ,
		   NoOfDays INT ,
		   ROI FLOAT DEFAULT 0,
		   [Actual ROI] FLOAT DEFAULT 0,
		   [Monthly ROI] FLOAT DEFAULT 0,
		   [Anually ROI] FLOAT DEFAULT 0
        ) 	
		IF(@ConsultantCode = '0' OR @ConsultantCode = '1' )	
			BEGIN
					SELECT DISTINCT p.member_code,p.year_code,
						STUFF((	SELECT distinct ',' + p1.Consultant_Code
								FROM Mst_Consultant p1
								--WHERE p.member_code = p1.member_code AND p.year_code = p1.year_code
								FOR XML PATH(''), TYPE
								).value('.', 'NVARCHAR(MAX)')
						,1,1,'') ConsultantCode
					into #temoConsultant
					FROM Mst_Consultant p
				 
					SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant)-- WHERE member_code = @memcode AND year_code = @yearcode)
					DROP table #temoConsultant		 	 
			END

        CREATE TABLE #Dividend 
        ( 
           membercode VARCHAR(100), 
           amount     FLOAT,
		   DivideScriptCode VARCHAR(Max) 
        ) 

	    INSERT INTO #Dividend 
	    SELECT   EQ.member_code, 
               Sum(EQ.amount) AS 'Amount',
			   EQ.Script_Code  
        FROM     EQDividend_Trans EQ          
        WHERE    EQ.member_code= @memcode
               AND EQ.Year_Code = @yearcode 
			   Group by EQ.member_code, EQ.Script_Code  

		INSERT INTO #mainoutputtable_1_Final_Summary
		EXEC [proc_Stockposition_Equity_ROI]  @status,@Investmenttype,@Ac_Type,@memcode,@yearcode,@Fromdate,@Todate,@ScriptCode,@ConsultantCode,@BSE_NSE_Code,@Is_BFCF,@IsIntraDay,@short_Long_Term,'ALLData',@IsWithTax,@IsBSEISIN
	   
		SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
		T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
		T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
		T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
		T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
		T1.consultant_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,
		T1.NoOfDays,T1.ROI,T1.[Actual ROI],  T1.[Monthly ROI],T1.[Anually ROI],T1.script_Code,
		ISNULL(Dr.BSE_Rate,0)  AS 'bse_rate', /**/
		ISNULL(Dr.NSE_Rate,0)  AS 'nse_rate' /**/
		INTO #alldata 
		FROM #mainoutputtable_1_Final_Summary  T1
		LEFT JOIN BrokerBill T2 ON T1.Trans_No=T2.Trans_no
		LEFT JOIN DailyRate DR ON DR.Script_Code = T1.script_Code  and Dr.Trans_Dt = @Todate /**/
						
		TRUNCATE TABLE #mainoutputtable_1_Final_Summary	

		INSERT INTO #mainoutputtable_1_Final_Summary 
		(
			id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
			opening_date,opening_qty,opening_rate,opening_amount,
			purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
			sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
			closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
			consultant_name,
			nse_rate,
			bse_rate,
			sort,isintradaycol,
			T2.Other_amt,
			T2.ServTax_Amt,
			T2.Stt_amt,
			T1.NoOfDays,
			T1.ROI,
			T1.[Actual ROI],  
			T1.[Monthly ROI],
			T1.[Anually ROI],
			script_Code
				
		) 
		SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,
		max(isnull(nse_rate,0)),
		max(isnull(bse_rate,0)),
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt ,
		 NoOfDays,  ROI, [Actual ROI],  [Monthly ROI], [Anually ROI],script_Code 
		FROM #alldata  		
		GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt ,
		NoOfDays, ROI, [Actual ROI],  [Monthly ROI], [Anually ROI] ,script_Code
	
	  --  Select * from #alldata

		IF(@DateWiseClosinStock = 1)
			BEGIN
				IF(@ConsultantCode<>'')		
					BEGIN	
						SELECT  MAX(id+0)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',
						isnull (SUM(closing_qty),0) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
						Closing_date 'Closing Date',
						MAX(bse_rate)  AS  'BSERATE',
						MAX(bse_rate) * SUM(closing_qty)  AS  'BSE_Valuation',
						CASE WHEN MAX(bse_rate) = 0 THEn 0 ELSE max(bse_rate) * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
						MAX(nse_rate) AS  'NSERATE',
						MAX(nse_rate) * SUM(closing_qty) AS  'NSE_Valuation',
						CASE WHEN MAX(nse_rate)=0 THEN 0 ELSE  MAX(nse_rate) * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
						SUM(gain_loss) AS 'Profit/Loss',
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
							ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
							0 END 
							END AS 'Avg. Rate',

						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
							ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
							0 END 
							END AS 'Value After Profit/Loss',
						SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,
						
						ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,@Todate,101)), CONVERT(DATETIME,closing_Date,103)),0)) NoOfDays,
								
						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0  AND MAX(ISNULL(bse_rate,0)) <> 0 THEN ((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100 --FOR BSE
							ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0  THEN ((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100     --FOR NSE
							ELSE 
						0 END END,2) AS 'ROI',

						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0   AND MAX(ISNULL(bse_rate,0)) <> 0  THEN (((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / 
						NULLIF(
							
								ABS(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,@Todate,101)), CONVERT(DATETIME,closing_Date,103)))
							,0)
						ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN (((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0))))    --FOR NSE
							ELSE 
						0 END END,2) AS 'Actual ROI',

						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0   AND MAX(ISNULL(bse_rate,0)) <> 0 THEN (((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0)))) * 30 --FOR BSE
							ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN (((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0)))) * 30    --FOR NSE
							ELSE 
						0 END END,2) AS  'Monthly ROI',

						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0  AND MAX(ISNULL(bse_rate,0)) <> 0  THEN ((((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0)))) * 30) * 12  --FOR BSE
							ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN ((((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0)))) * 30) * 12    --FOR NSE
							ELSE 
						0 END END,2) AS  'Anually ROI',
						'a' sort,
						0 As'DividendAmount' 
						FROM #mainoutputtable_1_Final_Summary
						GROUP BY holding_type,script_name,closing_Date,consultant_name
						HAVING SUM(closing_qty) != 0
						ORDER BY  	consultant_name,script_name,Holding_Type
					END
				ELSE			
					BEGIN
						SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',
						isnull (SUM(closing_qty),0) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
						closing_Date  'Closing Date',
						MAX(ISNULL(bse_rate,0))  AS  'BSERATE',
						MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,''))  AS  'BSE_Valuation',
						CASE WHEN MAX(ISNULL(bse_rate,0)) = 0 THEn 0 ELSE MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0)) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
						MAX(ISNULL(nse_rate,0)) AS  'NSERATE',
						MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0)) AS  'NSE_Valuation',
						CASE WHEN MAX(ISNULL(nse_rate,0))=0 THEN 0 ELSE  MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0)) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
						SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(ISNULL(closing_qty,0)),0)) 
								ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(ISNULL(closing_qty,0)),0)) ELSE
								0 END 
								END AS 'Avg. Rate',

						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(ISNULL(closing_qty,0)),0)) * (SUM(ISNULL(closing_qty,0))) 
								ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(ISNULL(closing_qty,0)),0)) * (SUM(ISNULL(closing_qty,0))) ELSE
								0 END 
								END AS 'Value After Profit/Loss',

						SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,
						
						ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,@Todate,101)), CONVERT(DATETIME,closing_Date,103)),0)) NoOfDays,
								
						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0  AND MAX(ISNULL(bse_rate,0)) <> 0 THEN ((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100 --FOR BSE
							ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0  THEN ((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100     --FOR NSE
							ELSE 
						0 END END,2) AS 'ROI',

						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0   AND MAX(ISNULL(bse_rate,0)) <> 0  THEN (((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / 
						NULLIF(
							
								ABS(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,@Todate,101)), CONVERT(DATETIME,closing_Date,103)))
							,0)
						ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN (((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0))))    --FOR NSE
							ELSE 
						0 END END,2) AS 'Actual ROI',

						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0   AND MAX(ISNULL(bse_rate,0)) <> 0 THEN (((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0)))) * 30 --FOR BSE
							ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN (((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0)))) * 30    --FOR NSE
							ELSE 
						0 END END,2) AS  'Monthly ROI',

						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0  AND MAX(ISNULL(bse_rate,0)) <> 0  THEN ((((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0)))) * 30) * 12  --FOR BSE
							ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN ((((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0)))) * 30) * 12    --FOR NSE
							ELSE 
						0 END END,2) AS  'Anually ROI',
						0 As'DividendAmount' 
						FROM #mainoutputtable_1_Final_Summary
						GROUP BY holding_type,script_name,closing_Date,consultant_name
						HAVING SUM(closing_qty) != 0
					END
			END
		ELSE  
			BEGIN
				IF(@ConsultantCode <> '')
						BEGIN					 
							SELECT   max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',
							isnull (SUM(closing_qty),0) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date','' 'Gain/Loss',
							MAX(ISNULL(bse_rate,0))  AS  'BSERATE',
							MAX(ISNULL(bse_rate,0)) * SUM(closing_qty)  AS  'BSE_Valuation',
							CASE WHEN MAX(ISNULL(bse_rate,0)) = 0 THEn 0 ELSE MAX(ISNULL(bse_rate,0)) * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
							MAX(ISNULL(nse_rate,0)) AS  'NSERATE',
							MAX(ISNULL(nse_rate,0)) * SUM(closing_qty) AS  'NSE_Valuation',
							CASE WHEN MAX(ISNULL(nse_rate,0)) =0 THEN 0 ELSE  MAX(ISNULL(nse_rate,0)) * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
							SUM(gain_loss) AS 'Profit/Loss',
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
								ELSE
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
								0 END 
								END AS 'Avg. Rate',

							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
								ELSE
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
								0 END 
								END AS 'Value After Profit/Loss',
							SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,0 NoOfDays,0 ROI,0 'Actual ROI',0 'Monthly ROI',0 'Anually ROI','a' sort,0 As'DividendAmount' 
							FROM #mainoutputtable_1_Final_Summary
							GROUP BY consultant_name,holding_type,script_name
							HAVING SUM(closing_qty) != 0
							ORDER BY  	consultant_name,script_name,Holding_Type						 
						END
					ELSE
						BEGIN
							IF(@DateWiseClosinStock=1)
								BEGIN
									SELECT holding_type,script_name 'Script Name', ROUND(SUM(isnull(closing_value,0)),2) AS 'Closing Value',
									SUM(isnull(closing_qty,0)) AS 'Closing Qty', 
									ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(isnull(Gain_Loss,0)) 'Gain/Loss',
									Max(ISNULL(bse_rate,0)) AS  'BSERATE',
									Max(ISNULL(bse_rate,0))* SUM(closing_qty)  AS  'BSE_Valuation',
									CASE WHEN Max(ISNULL(bse_rate,0))= 0 THEn 0 ELSE Max(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0)) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
									Max(ISNULL(nse_rate,0)) AS  'NSERATE',
									Max(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0)) AS  'NSE_Valuation',
									CASE WHEN Max(ISNULL(nse_rate,0)) = 0 THEN 0 ELSE  Max(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0)) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
									SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
										END AS 'Avg. Rate',

									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
									CASE WHEN 
											SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
										END AS 'Value After Profit/Loss',
									0 Other_amt, '' consultant_name,
									closing_Date,sum(NoOfDays) NoOfDays,
									ABS((ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,@Todate,101)), CONVERT(DATETIME,closing_Date,103)),0))) NoOfDays,
						
									CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0   AND Max(ISNULL(bse_rate,0)) <> 0 THEN (Max(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100 --FOR BSE
										ELSE
									CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND Max(ISNULL(bse_rate,0)) <> 0 THEN (Max(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100     --FOR NSE
										ELSE 
									0 END END AS 'ROI',

									ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0   AND Max(ISNULL(bse_rate,0)) <> 0 THEN (((Max(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / 
									(
									 NULLIF
										( 
										   ABS(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103))),0
										)   
									)
										ELSE
								
									CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND Max(ISNULL(nse_rate,0)) <> 0 THEN (((Max(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / 
									NULLIF(SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0))),0)    --FOR NSE
										ELSE 
									0 END END,2) AS 'Actual ROI',

									ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0  AND Max(ISNULL(bse_rate,0)) <> 0  THEN (((Max(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / NULLIF(SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0))),0) * 30 --FOR BSE
										ELSE
									CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND Max(ISNULL(nse_rate,0)) <> 0 THEN ((( Max(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / NULLIF(SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0))),0) * 30    --FOR NSE
										ELSE 
									0 END END,2) AS  'Monthly ROI',

									ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0   AND Max(ISNULL(bse_rate,0)) <> 0 THEN ((((Max(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / NULLIF(SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0))),0) * 30) * 12  --FOR BSE
										ELSE
									CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND Max(ISNULL(nse_rate,0)) <> 0 THEN (((( Max(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / NULLIF(SUM(ABS(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0))),0) * 30) * 12    --FOR NSE
										ELSE 
									0 END END,2) AS  'Anually ROI',
									0 As'DividendAmount' 					
									FROM #mainoutputtable_1_Final_Summary
									GROUP BY holding_type,script_name ,closing_Date--,NoOfDays--,sold_date,opening_date,purchase_date
									HAVING SUM(closing_qty) != 0
									ORDER BY holding_type,script_name
								END
							ELSE
								BEGIN
							 -- 	Select * from  #mainoutputtable_1_Final_Summary
									SELECT holding_type,script_name 'Script Name', ROUND(SUM(isnull(closing_value,0)),2) AS 'Closing Value',SUM(isnull(closing_qty,0)) AS 'Closing Qty', 
									ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(isnull(Gain_Loss,0)) 'Gain/Loss',
									MAX(ISNULL(bse_rate,0))  AS  'BSERATE',
									MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))  AS  'BSE_Valuation',
									CASE WHEN Max(ISNULL(bse_rate,0)) = 0 THEn 0 ELSE Max(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0)) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
									MAX(ISNULL(nse_rate,0)) AS  'NSERATE',
									MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0)) AS  'NSE_Valuation',
									CASE WHEN MAX(ISNULL(nse_rate,0)) = 0 THEn 0 ELSE MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0)) - SUM(closing_value)  END  AS  'NSE_UnRealizedGainLoss',
									0 'BSE_UnRealizedGainLoss',
									0 'NSE_UnRealizedGainLoss',
									0 'Profit/Loss',
									0 'Avg. Rate',
									0 'Value After Profit/Loss',
									0 Other_amt, 
									  consultant_name,
									'' closing_Date,
									0 NoOfDays,
									0 'ROI',
									0 'Actual ROI',
									0 'Monthly ROI',
									0 'Anually ROI',
									ISNULL(EQ.amount,0) As'DividendAmount' 
									FROM #mainoutputtable_1_Final_Summary
									Left Join #Dividend  EQ On EQ.DivideScriptCode=#mainoutputtable_1_Final_Summary.script_Code
									GROUP BY holding_type,script_name,consultant_name, EQ.DivideScriptCode,EQ.amount
									HAVING SUM(closing_qty) != 0
									ORDER BY holding_type,script_name
								END
						END						
					END
					Select Round(Sum(ISNULL (gain_loss,0)),4) from #mainoutputtable_1_Final_Summary		          	
			        Having Sum(ISNULL (gain_loss,0))!=0
			        Order by 1		
			       	Select  sum(Other_amt) from BrokerBill where Member_code=@memcode and Yearcode=@yearcode and isfnoBill=@Investmenttype and Trans_Dt<=@Todate

			DROP TABLE #alldata
END


































GO
/****** Object:  StoredProcedure [dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency] AS' 
END
GO


 --[dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency] 0,0,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','1', '0' ,'0','scriptwisetotal'
ALTER  PROCEDURE [dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency] --0,0,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','Details'
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX), @IsWithTax as bit = 0,
@Script_Name varchar(max) = '')
AS 
  BEGIN  
  SET NOCOUNT ON;
		DECLARE @StartYearDate varchar(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101)

		CREATE TABLE #mainoutputtable_1
        ( 
		   pkid INT identity(1,1), 
		   Dup_pkid int, 
           Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT,
		   Trans_Type  VARCHAR(50), 
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(10),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name  VARCHAR(500),
		   flag_holding_type VARCHAR(200), 
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(10),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount AS( [opening_qty] * [opening_rate] ), 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount AS( purchase_qty * purchase_rate ), 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount AS ( sold_qty * sold_rate ), 
           gain_loss float,
		   closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 

           closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
		   closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
		   short_term FLOAT DEFAULT 0,
		   long_term  FLOAT DEFAULT 0,
           speculation  FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   NoOfDays FLOAT DEFAULT 0,
		   ROI FLOAT DEFAULT 0,
		   [Actual ROI] FLOAT DEFAULT 0,
		   [Monthly ROI] FLOAT DEFAULT 0,
		   [Anually ROI] FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(20) ,
		   ScriptCode Varchar(50),
		   Strike_Price float DEFAULT 0,
		   OptionType VARCHAR(100),
		   Last_Date VARCHAR(100) 
        )  

		CREATE TABLE #mainoutputtable_1_Final
        ( 
		   Dup_pkid int, 
		   OrderBy varchar(100),
           Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT   ,
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(10),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name  VARCHAR(500),
		   flag_holding_type VARCHAR(200), 
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(10),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
		   gain_loss FLOAT DEFAULT 0,
		   gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(20),
		   sort   VARCHAR(5),
		   NoOfDays  AS
		   (
		   CASE WHEN ISNULL(opening_date,'')  !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR , CONVERT(DATETIME , opening_date , 103)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),103)))  ELSE 
		   CASE WHEN ISNULL(purchase_date,'') !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME , purchase_date , 103)) , CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),103))) ELSE 0 END END
		   ) ,
		   ROI AS 
		   (
				CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (Gain_Loss / NULLIF(Opening_Amount,0)) * 100 WHEN ISNULL(Purchase_Amount,0) != 0 
				THEN  (Gain_Loss/Purchase_Amount)*100	END
		   ) ,
		   [Actual ROI]  AS
		   (
			   CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ((Gain_Loss / NULLIF(Opening_Amount,0)) * 100) /  
			   NULLIF(CASE WHEN ISNULL(opening_date,'')  !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR , CONVERT(DATETIME , opening_date , 103)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),103)))  ELSE 
			   CASE WHEN ISNULL(purchase_date,'') !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME , purchase_date , 103)) , CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),103))) ELSE 0 END END,0) 
			ELSE
			   CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN ((Gain_Loss / Purchase_Amount) * 100) / 
			   NULLIF(CASE WHEN ISNULL(opening_date,'')  !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR , CONVERT(DATETIME , opening_date , 103)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),103)))  ELSE 
			   CASE WHEN ISNULL(purchase_date,'') !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME , purchase_date , 103)) , CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),103))) ELSE 0 END END,0) 
			   END END
		   )
		   ,
		   [Monthly ROI] AS
		   (
				CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((Gain_Loss / NULLIF(Opening_Amount,0)) * 100) /  
				NULLIF(CASE WHEN ISNULL(opening_date,'')  !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR , CONVERT(DATETIME , opening_date , 103)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),103)))  ELSE 
				CASE WHEN ISNULL(purchase_date,'') !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME , purchase_date , 103)) , CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),103))) ELSE 0 END END,0))  * 30  
			ELSE
				CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN  (((Gain_Loss / NULLIF(Purchase_Amount,0)) * 100) / 
				NULLIF(CASE WHEN ISNULL(opening_date,'')  !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR , CONVERT(DATETIME , opening_date , 103)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),103)))  ELSE 
				CASE WHEN ISNULL(purchase_date,'') !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME , purchase_date , 103)) , CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),103))) ELSE 0 END END,0)) * 30 
				END END 
		   )
		   ,
		   [Anually ROI]  AS
		   (
				CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((Gain_Loss / NULLIF(Opening_Amount,0)) * 100) / 
				NULLIF(CASE WHEN ISNULL(opening_date,'')  !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR , CONVERT(DATETIME , opening_date , 103)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),103)))  ELSE 
				CASE WHEN ISNULL(purchase_date,'') !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME , purchase_date , 103)) , CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),103))) ELSE 0 END END,0)) * 365 
		   ELSE
				CASE WHEN ISNULL(Purchase_Amount,0)!=0 THEN  (((Gain_Loss / NULLIF(Purchase_Amount,0))*100) / 
				NULLIF(CASE WHEN ISNULL(opening_date,'')  !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR , CONVERT(DATETIME , opening_date , 103)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),103)))  ELSE 
				CASE WHEN ISNULL(purchase_date,'') !='' AND ISNULL(Sold_date,'')  !='' THEN  DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME , purchase_date , 103)) , CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),103))) ELSE 0 END END,0))*365 
				END END 
		   ),ScriptCode Varchar(50),
		   Strike_Price float DEFAULT 0,
		   OptionType VARCHAR(100),
		   Last_Date VARCHAR(100) 
	     ) 

		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty INT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT  
		DECLARE @tablerowscount INT
      IF(@status = 0) 
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
				@openingDate DATETIME,@openingRate FLOAT,@openingQty INT,@openingAmount FLOAT,
				@purchaseDate DATETIME,@PurchaseBillNo  VARCHAR(50),@purchaseRate FLOAT,@purchaseQty INT,@purchaseAmount FLOAT,
				@soldDate DATETIME,@soldBillNo  VARCHAR(50),@soldRate FLOAT,@soldQty INT,@soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50),@Consultant_Name  VARCHAR(100), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(10),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,@PurchaseIntraFlag VARCHAR(100),@SaleIntraFlag VARCHAR(10) 
				DECLARE @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@Bse_Rate float,@Nse_Rate float ,@ScriptId Varchar(50),@Dup_pkid int, @Pkid int,@idcount int  ,@Strike_Price FLOAT,@OptionType VARCHAR(50),@Last_Date VARCHAR(50)

				CREATE TABLE #SCriptName
				(
					ScriptName varchar(MAX)
				)

				IF(@Script_Name != '')
					INSERT INTO #SCriptName SELECT value FROM Fn_split(@Script_Name, ',') 
				ELSE 
					BEGIN
						INSERT INTO #SCriptName 
						Select distinct (Ms.script_name 
								+ '/' + CONVERT(VARCHAR(10),t.Last_Date,103) 
								+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
								+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' END) 
						from brokerbill_Trans t
						Left Join mst_Script ms on ms.script_Code = t.script_Code 
					END

				CREATE TABLE #ConsultantCodes
				(
					ConsultantCodes varchar(MAX)
				)

				
				IF(@ConsultantCode = '0')	
					BEGIN
						
						SELECT DISTINCT p.member_code,p.year_code,
							STUFF((	SELECT distinct ',' + p1.Consultant_Code
									FROM Mst_Consultant p1
									--WHERE p.member_code = p1.member_code AND p.year_code = p1.year_code
									FOR XML PATH(''), TYPE
									).value('.', 'NVARCHAR(MAX)')
							,1,1,'') ConsultantCode
						into #temoConsultant
						FROM Mst_Consultant p

						SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant WHERE member_code = @memcode AND year_code = @yearcode)
						DROP table #temoConsultant
		
					END
				 
				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes select Consultant_Code from Mst_Consultant

				SELECT	ROW_NUMBER ( ) OVER (ORDER BY t.script_code, t.trans_dt ) AS NameId,
						t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,t.TransType,t.Ac_Type,t.Script_Code,t.Last_Date,t.Qty,
						Case When @IsWithTax = 0 Then t.Rate Else t.Exp_Rate END As 'Rate',--t.Rate,`
						max(isnull(dr.BSE_Rate,0))BSE_Rate,MAX(isnull(dr.NSE_Rate,0))NSE_Rate,
						t.Member_code,t.YearCode,t.Consultant_code,t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,t.Exp_Rate,t.FrmNm,t.ID,
						Ms.bse_code,Ms.nse_code,
						Ms.script_name 
							+ '/' +   CONVERT(VARCHAR(10),t.Last_Date,103) 
							+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
							+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' 
						END script_name,
						'Empty' AS 'Holding Type',
						CASE WHEN (((t.Bill_no   = 'Opening' AND ISNULL(t.Frmnm,'') != 'BB') OR ISNULL(t.Frmnm,'') = 'OP' OR CONVERT(date,t.trans_dt,101)  < CONVERT(date ,@StartYearDate,101))AND t.TransType='Bought') THEN 'Opening'
							 WHEN t.TransType='Bought' AND  t.Bill_no != 'Opening'  THEN 'Bought' 
							 WHEN TransType='Sold' THEN 'Sold' 
						END AS 'Flag_Type', cm.Consultant_Name,t.isstock
						INTO #alldata 
				FROM brokerbill_trans t 
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN  Mst_Consultant  cm ON t.Consultant_code = cm.Consultant_code  
				LEFT JOIN DailyRate DR ON DR.Script_Code = Ms.script_code and dr.Trans_Dt=t.Trans_Dt

				WHERE  isfnobill = @Investmenttype AND t.trans_dt <= @Todate AND t.member_code = @memcode AND yearcode = @yearcode  AND 
				Ac_Type =(CASE WHEN  @Ac_Type='0' THEN Ac_Type  ELSE  @Ac_Type END)
				AND  (Ms.script_name 
							+ '/' +   CONVERT(VARCHAR(10),t.Last_Date,103) 
							+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
							+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' 
						END) IN (SELECT * FROM #SCriptName)
				AND	 t.Consultant_code IN (SELECT * FROM #ConsultantCodes)
				AND  ISNULL(t.isIntraDay,0) =(CASE WHEN ISNULL(@IsIntraDay,0)=0 THEN   ISNULL(isIntraDay,0) ELSE  ISNULL(@IsIntraDay,0) END) 
				AND t.isstock=(select case when @Is_BFCF = 1 then  '' else  t.isstock end)
				GROUP BY t.Trans_Dt,Trans_No,Sr_No,Bill_no,TransType,Ac_Type,t.Script_Code,MonthYear,Last_Date,LotSize,Qty,LotQty,Disp_qty,
				Bal_qty,G_Rate,Brok_Amt,ServTax_Amount,Rate,Amount,Stt_Amount,t.Member_Code,YearCode,t.Consultant_code,
				EntrySource,Ref_TransNo,Ref_SrNo,MergedEntry,isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay,Brok_PerUnit,lockedbymerger,
				frac_Qty,Org_Trans_No,Org_SrNo,isDeleteMerger,isstock,ScripwiseExpense,isClient_code,isClient_Brokrage,c_Qty,C_Gross_Rate,
				C_Net_Rate,C_Amount,C_STT,C_STax,C_MisChg,TransactionChg,C_StampDuty,Exp_Rate,PerExp_Unit,FrmNm,ID,bse_code,nse_code,script_name, cm.Consultant_Name,t.isstock--,dr.BSE_Rate,dr.NSE_Rate
				
			--	Select * from #alldata

				DECLARE @isIntradayCol INT 
				DECLARE  @COUNT INT=0
				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT id,Trans_No,script_name,Script_Code,  [holding type],bill_no,CONVERT(DATETIME,trans_dt,103),qty,rate,ISNULL(qty, 0) * ISNULL(rate, 0),ISNULL(isintraday, 0),consultant_name,BSE_Rate,NSE_Rate,Strike_Price,OptionType,Last_Date   
				FROM #alldata			
				WHERE ((#alldata.bill_no IN('Opening') OR  CONVERT(date,trans_dt,101)  < CONVERT(date ,@StartYearDate,101))AND #alldata.TransType='Bought')
			
				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@Bse_rate,@Nse_rate,@Strike_Price,@OptionType,@Last_Date
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
							IF(@Investmenttype=2)
								SET @holding_type='Mutual Fund'

							SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
							SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
							SET @Dup_pkid = ISNULL(@Dup_pkid,0)
							SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
							SET @Dup_pkid = @Dup_pkid + 1

							DECLARE @IDs INT=0
							DECLARE @Flag_Types VARCHAR(10)
							SET @Flag_Types = (SELECT CASE WHEN @billno = 'Opening' THEN 'Opening' ELSE 'Bought' END)
							 
							INSERT INTO #mainoutputtable_1   
							(
								id, Trans_No,Dup_pkid, ScriptCode, Flag_Type,opening_bill_no, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,consultant_name,bse_rate,nse_rate,Strike_Price,OptionType,Last_Date
							) 
							SELECT @ID, @Trans_No,@Dup_pkid,@ScriptId, 'Opening', @billno,@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Consultant_Name,@Bse_Rate,@Nse_Rate,@Strike_Price,@OptionType,@Last_Date
			 				
							IF(@idcount>0)
								BEGIN
									UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
								END
						FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@Bse_rate,@Nse_rate,@Strike_Price,@OptionType,@Last_Date
					END 

				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 
				DECLARE @salecount INT=0,@Boughtcount INT=0,@Flag_Type VARCHAR(20)
							
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
				SELECT id,Bill_no,Flag_Type,TransType,Script_Code,script_name,[holding type],Trans_No,CONVERT(DATETIME, trans_dt,103), qty,rate,qty * rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name,BSE_Rate,NSE_Rate,Strike_Price,OptionType,Last_Date
				FROM #alldata 
				WHERE    
				(TransType in('Bought','Sold')  OR CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name ,@BSE_Rate,@NSE_Rate,@Strike_Price,@OptionType,@Last_Date
				
				WHILE (@@FETCH_STATUS = 0) 
						BEGIN
							SET @COUNT = 0
							DECLARE @IsOpening INT =0
							DECLARE @prioritysId INT=0
							DECLARE @str VARCHAR(MAX)=''	
							DECLARE @purchase_Op_Qty FLOAT =0
							DECLARE @purchase_Op_Bill VARCHAR(20)=''
							DECLARE @purchase_Op_Date VARCHAR(20)=''
							DECLARE @purchase_Op_Rate FLOAT=0
							DECLARE	@PurQTY FLOAT=0
							DECLARE	@BalPurQTY FLOAT=0
							DECLARE @BalSoldQTY FLOAT=0
							DECLARE @Balpurchase_Op_Qty FLOAT=0
							DECLARE @BalOpeningQTY FLOAT=0
							DECLARE	@Sold_Qty FLOAT=0
							DECLARE @tempID int = 0
							
							IF(@isIntradayCol=0)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and Flag_Type ='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=0  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
																					
											IF (@COUNT > 0)
												BEGIN
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* 
													INTO #tempSoldValExists 
													FROM
													#MainOutputtable_1 
													WHERE script_name=@scriptname AND holding_type=@holding_type  AND isintradaycol=0 
													AND (consultant_name = CASE WHEN  @Consultant_Name <> '' then  @Consultant_Name ELSE consultant_name END)
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold IN('Sold')  and Flag_Type ='Sold' AND isintradaycol=0
													DECLARE @R_Sold_COUNT INT=(SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty INT 
													
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists  ORDER BY Dup_pkid)
															SET @str=@TransType
															SET @Temppurchase_Op_Qty=(SELECT TOP(1) sold_qty  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @soldDate=(SELECT TOP (1) sold_date  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @soldRate=(SELECT TOP (1) sold_rate  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @soldBillNo=(SELECT TOP (1) sold_bill_no  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @purchase_Op_Qty=@qty
															IF(@TransType='Opening')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	
																	opening_date=@dates,
																	opening_rate=@rate,
																	opening_qty= CASE WHEN @Temppurchase_Op_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Temppurchase_Op_Qty END,
																	Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND pkid = @pkid
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	
																	purchase_date=@dates,
																	purchase_bill_no=@billno,
																	purchase_rate=@rate,
																	purchase_qty= CASE WHEN @Temppurchase_Op_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Temppurchase_Op_Qty END,
																	Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND pkid = @pkid
																END
															

															IF(@Temppurchase_Op_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET sold_qty=@purchase_Op_Qty 
																	WHERE Flag_Type_Sold='Sold' AND   id = @tempSaleID  AND pkid = @pkid
																END

															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND pkid = @pkid
															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempSoldValExists )

															DECLARE @Balancedval   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Temppurchase_Op_Qty)
															IF(@Balancedval  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty=ABS(@Balancedval) 
																	SET @prioritysId  =(SELECT MAX(ISNULL(@prioritysId,0)+1) FROM #MainOutputtable_1)-- WHERE id=@tempSaleID )
																	 
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode, Flag_Type,Flag_Type_Sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name,bse_rate,nse_rate,Strike_Price,OptionType,Last_Date)
																	VALUES(@Dup_pkid,@tempSaleID ,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name,@bse_rate,@nse_rate,@Strike_Price,@OptionType,@Last_Date)
																	
																	UPDATE #MainOutputtable_1 SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempSaleID 

																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																		END
																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @prioritysId = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	IF(@TransType='Opening')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode, Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name,bse_rate,nse_rate,Strike_Price,OptionType,Last_Date)
																			VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name,@bse_rate,@nse_rate,@Strike_Price,@OptionType,@Last_Date)
																		END
																	ELSE IF(@TransType='Bought')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name,bse_rate,nse_rate,Strike_Price,OptionType,Last_Date)
																			VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name,@bse_rate,@nse_rate,@Strike_Price,@OptionType,@Last_Date)
																		END
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																		END
																ENd
															
															SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
															SET @qty=@Balancedval
														END
												

													DROP TABLE #tempSoldValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
													INSERT INTO #mainoutputtable_1 (Dup_pkid,id,Trans_No, prioritys,ScriptCode, Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name,bse_rate,nse_rate,Strike_Price,OptionType,Last_Date) 
													VALUES (@Dup_pkid, @ID,@Trans_No, @prioritysId,@ScriptId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name,@bse_rate,@nse_rate,@Strike_Price,@OptionType,@Last_Date) 
												END
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */

											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN( 'Split','Other','Transfer','Opening','Bought') AND ISNULL(sold_qty,0)=0  AND isintradaycol=0 AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
											
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* INTO #tempValExists 
													FROM
													#MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('IPO', 'Bonus', 'Rights','Split','Other','Transfer','Opening','Bought') 
													AND (consultant_name = CASE WHEN  @ConsultantCode <> '' THEN  @Consultant_Name ELSE consultant_name END) 
													AND ISNULL(sold_qty,0) = 0  AND isintradaycol = 0 
													 
													
													DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty int 
													
													WHILE(@RCOUNT > 0 )
														BEGIN 
															SET @Sold_Qty= @qty
															SET @tempID = (SELECT TOP(1) id FROM #tempValExists  ORDER BY Dup_pkid)
															SET @str = (SELECT TOP(1) Flag_Type FROM #tempValExists WHERE id  = @tempID)
														
															IF(@str='Opening')
																BEGIN
																	SET @TempSoldQty=(SELECT TOP(1) opening_qty  FROM #tempValExists WHERE id  = @tempID)
																	SET @openingDate=(SELECT TOP(1) opening_date FROM #tempValExists WHERE id  = @tempID)
																	SET @openingrate=(SELECT TOP(1) opening_rate FROM #tempValExists WHERE id  = @tempID)
																	SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempValExists WHERE id  = @tempID )
																END
															ELSE IF(@str='Bought')
																BEGIN
																	SET @TempSoldQty=(SELECT TOP(1) purchase_qty FROM #tempValExists WHERE id  = @tempID)
																	SET @PurchaseDate=(SELECT TOP(1) purchase_date FROM #tempValExists WHERE id  = @tempID)
																	SET @Purchaserate=(SELECT TOP(1) purchase_rate FROM #tempValExists WHERE id  = @tempID)
																	SET @PurchaseBillNo=(SELECT TOP(1) purchase_bill_no FROM #tempValExists WHERE id  = @tempID)
																	SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempValExists WHERE id  = @tempID )
																END
															IF(@Sold_Qty > 0)
																BEGIN
																	UPDATE #MainOutputtable_1  
																		SET	
																			opening_qty = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							END,
																			purchase_qty  = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							END,
																			sold_date=@dates,
																			sold_bill_no=@billno,
																			sold_rate=@rate,
																			sold_qty= CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold='Sold'
																	WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND pkid = @pkid
																	SET @Balanceval = ABS(@Sold_Qty) - ABS(@TempSoldQty)
																END
															
															DELETE FROM #tempValExists WHERE id = @tempID AND pkid = @pkid
															SET @tablerowscount = (SELECT COUNT(*) FROM  #tempValExists )
															SET @RCOUNT = @RCOUNT - 1
															SET @qty = @Balanceval
															SET @Sold_Qty = @qty
													
															IF(@Balanceval  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  =(SELECT MAX(ISNULL(@prioritysId,0)+1) FROM #MainOutputtable_1) 

																	IF(@str='Opening')
																		BEGIN
																			SET @openingQty = ABS(@Balanceval) 
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name,bse_rate,nse_rate,Strike_Price,OptionType,Last_Date)
																			VALUES(@Dup_pkid,@tempID,@Trans_No,@ScriptId, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name,@bse_rate,@nse_rate,@Strike_Price,@OptionType,@Last_Date)
																			UPDATE #MainOutputtable_1 SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempID
																		END
																	ELSE 
																		BEGIN
																			SET @PurchaseQty = ABS(@Sold_Qty) 
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No, ScriptCode, Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name,bse_rate,nse_rate,Strike_Price,OptionType,Last_Date)
																			VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name,@bse_rate,@nse_rate,@Strike_Price,@OptionType,@Last_Date)
																			UPDATE #MainOutputtable_1 SET prioritys=@prioritysId  WHERE prioritys > @prioritysId AND ID<>@tempID
																		END
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																		END
																	BREAK;
																END
															ELSE IF(ISNULL(@Balanceval,0) > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	
																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,bse_rate,nse_rate,Strike_Price,OptionType,Last_Date)
																	VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name,@bse_rate,@nse_rate,@Strike_Price,@OptionType,@Last_Date)
																	
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																		END
																END
														END 

													 DROP TABLE #tempValExists
												END
											
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
													INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,bse_rate,nse_rate,Strike_Price,OptionType,Last_Date)
													VALUES(@Dup_pkid,@ID,@Trans_No, @ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name,@bse_rate,@nse_rate,@Strike_Price,@OptionType,@Last_Date)
												END
											SET @purchase_Op_Date=''
											SET @purchase_Op_Rate=''
											SET @purchase_Op_Qty=''
											SET @purchase_Op_Bill=''

										END
								END
							 
							FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name ,@BSE_Rate,@NSE_Rate,@Strike_Price,@OptionType,@Last_Date
						END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 


		 
		IF(@Investmenttype=2)
			BEGIN
				INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss , closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

				SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
						case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
							 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  
							CONVERT(DATE,sold_date,101) END desc)  AS NameId, opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name,'Empty', flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount , 
				 Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) < 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365) --short term for purchase
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
						
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365) --short term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) = 0) 
							AND (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol 
				FROM #mainoutputtable_1 
				order by NameId
			END

		ELSE
			BEGIN
				INSERT INTO #mainoutputtable_1_Final (OrderBy,id,Trans_No, prioritys,ScriptCode,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol ,Strike_Price,OptionType,Last_Date)

				SELECT 
				ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,Dup_Pkid, case when CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) else CONVERT(DATE,purchase_date,103) END,prioritys DESC, sold_date DESC ) AS NameId,
				id,Trans_No, prioritys,ScriptCode,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount , 
				 Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103)) < 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365) --short term for purchase
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
						
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365) --short term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,103), CONVERT(DATETIME,sold_date,103), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,103), CONVERT(DATETIME,sold_date,103), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) = 0) 
							AND (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol ,Strike_Price,OptionType,Last_Date
				FROM #mainoutputtable_1 
				order by NameId

			END
			 
			UPDATE #mainoutputtable_1_Final SET prioritys=0
			DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
			UPDATE #mainoutputtable_1_Final
			SET prioritys  = @i , @i = @i + 1
	  
		IF(@OUTPUT_Flag='Details')
			BEGIN
		 
				 
					IF(@ConsultantCode <> '')
						BEGIN
							SELECT id,prioritys,ScriptCode,script_name 'Script Name',Holding_Type,opening_bill_no,
							CONVERT(date, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
							CONVERT(date, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
							CONVERT(date, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
							ISNULL(gain_loss,0) 'Gain/Loss',ISNULL(gain,0) 'Gain',ISNULL(loss,0) 'Loss',ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
							ISNULL(short_term,0)short_term,
							ISNULL(long_term,0)long_term,
							ISNULL(speculation,0)speculation,
				
							CASE WHEN isintradaycol=1 and ISNULL(gain,0)!=0 THEN ISNULL(gain ,0) ELSE '' END gain_speculation,
							CASE WHEN isintradaycol=1 and ISNULL(loss,0)!=0  THEN ISNULL(loss ,0) ELSE '' END loss_speculation,
							consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,isintradaycol,
							ISNULL(NoOfDays,0)NoOfDays,

							CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ISNULL((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100 ,0)
								 WHEN ISNULL(Purchase_Amount,0) != 0 THEN  ISNULL((ISNULL(Gain_Loss,0) /NULLIF(Purchase_Amount,0)) * 100,0)	END AS 	'ROI',

							CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ISNULL(((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0),0) ELSE
							CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN ISNULL(((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0),0) END END AS 'Actual ROI',

							CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ISNULL((((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0))  * 30,0)  ELSE
							CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN  ISNULL((((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 30 ,0)
							END END AS 'Monthly ROI',

							(CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ISNULL((((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 365,0) ELSE
							CASE WHEN ISNULL(Purchase_Amount,0)!=0 THEN  ISNULL((((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0))*100) / NULLIF(NoOfDays,0))*365,0) 
							END END ) AS 'Anually ROI', 
							1 sort 
							FROM #mainoutputtable_1_Final
							WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
							ORDER By consultant_name,script_name,Holding_Type
						END
					ELSE
						BEGIN
							SELECT id,prioritys,  ScriptCode, script_name 'Script Name',Holding_Type,opening_bill_no,
							CONVERT(date, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
							CONVERT(date, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
							CONVERT(date, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
							ISNULL(gain_loss,0) 'Gain/Loss',
							CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
							ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
							ISNULL(short_term,0)short_term,
							ISNULL(long_term,0)long_term,
							ISNULL(speculation,0)speculation,
						
							CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
							CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
							'' consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,isintradaycol,
							ISNULL(NoOfDays,0)NoOfDays,

							CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ISNULL(ISNULL((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100 ,0),0)
							     WHEN ISNULL(Purchase_Amount,0) != 0 THEN  ISNULL(ISNULL((ISNULL(Gain_Loss,0)/NULLIF(Purchase_Amount,0)) * 100	,0),0)END AS 	'ROI',

							CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ISNULL(ISNULL(((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0) ,0),0) ELSE
							CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN ISNULL(ISNULL(((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0),0),0) END END AS 'Actual ROI',

							CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ISNULL(ISNULL((((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0))  * 30 ,0),0) ELSE
							CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN  ISNULL(ISNULL((((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 30,0),0) 
							END END AS 'Monthly ROI',

							(CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ISNULL(ISNULL((((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 365,0),0) ELSE
							CASE WHEN ISNULL(Purchase_Amount,0)!=0 THEN  ISNULL(ISNULL((((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0))*100) / NULLIF(NoOfDays,0))*365 ,0),0)
							END END ) AS 'Anually ROI',
							ISNULL(bse_rate,0)bse_rate,ISNULL(nse_rate,0)nse_rate,1 sort 
							FROM #mainoutputtable_1_Final
							WHERE (opening_qty != 0  OR purchase_qty != 0  or sold_qty != 0)  
				
						 
							ORDER BY   script_name--,id
						 
					END
				 
			--ELSE
			--	BEGIN
			--		IF(@ConsultantCode <> '')
			--			BEGIN
			--				SELECT id,prioritys,ScriptCode,script_name 'Script Name',Holding_Type,
			--				CONVERT(date, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
			--				CONVERT(date, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
			--				CONVERT(date, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
			--				ISNULL(gain_loss,0) 'Gain/Loss',ISNULL(gain,0) 'Gain',ISNULL(loss,0) 'Loss',
			--				ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
			--				ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
				
			--				CASE WHEN isintradaycol=1 and ISNULL(gain,0)!=0 THEN ISNULL(gain ,0) ELSE '' END gain_speculation,
			--				CASE WHEN isintradaycol=1 and ISNULL(loss,0)!=0  THEN ISNULL(loss ,0) ELSE '' END loss_speculation,
			--				consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,ISNULL(isintradaycol,0)isintradaycol,
			--				ISNULL(NoOfDays,0)NoOfDays,

			--				CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100 
			--					 WHEN ISNULL(Purchase_Amount,0) != 0 THEN  (ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0)) * 100	END AS 	'ROI',

			--				CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0) ELSE
			--				CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN ((ISNULL(Gain_Loss,0) / ISNULL(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0) END END AS 'Actual ROI',

			--				CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0))  * 30  ELSE
			--				CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 30 
			--				END END AS 'Monthly ROI',

			--				(CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 365 ELSE
			--				CASE WHEN ISNULL(Purchase_Amount,0)!=0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0))*100) / NULLIF(NoOfDays,0))*365 
			--				END END ) AS 'Anually ROI', 
			--				1 sort 
			--				FROM #mainoutputtable_1_Final
			--				WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
			--				ORDER By consultant_name,script_name
			--			END
			--		ELSE
			--			BEGIN
						
			--			SELECT id,prioritys,  ScriptCode, script_name 'Script Name',Holding_Type,
			--			CONVERT(date, opening_date,103) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
			--			CONVERT(date, purchase_date,103) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
			--			CONVERT(date, sold_date,103) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
			--			ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',
			--			ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
			--			ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
						
			--			CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
			--			CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
			--			'' consultant_name,ISNULL(nse_rate,0) nse_rate,ISNULL(bse_rate,0) bse_rate,isintradaycol,
			--			ISNULL(NoOfDays,0)NoOfDays,

			--			CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100 
			--				 WHEN ISNULL(Purchase_Amount,0) != 0 THEN  (ISNULL(Gain_Loss,0) /NULLIF(Purchase_Amount,0)) * 100	END AS 	'ROI',

			--			CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  ((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0) ELSE
			--			CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN ((ISNULL(Gain_Loss ,0) / NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0) END END AS 'Actual ROI',

			--			CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) /  NULLIF(NoOfDays,0))  * 30  ELSE
			--			CASE WHEN ISNULL(Purchase_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss ,0) / NULLIF(Purchase_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 30 
			--			END END AS 'Monthly ROI',

			--			(CASE WHEN ISNULL(Opening_Amount,0) != 0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Opening_Amount,0)) * 100) / NULLIF(NoOfDays,0)) * 365 ELSE
			--			CASE WHEN ISNULL(Purchase_Amount,0)!=0 THEN  (((ISNULL(Gain_Loss,0) / NULLIF(Purchase_Amount,0))*100) / NULLIF(NoOfDays,0))*365 
			--			END END ) AS 'Anually ROI',
			--			ISNULL(bse_rate,0)bse_rate,ISNULL(nse_rate,0)nse_rate,1 sort 
			--			FROM #mainoutputtable_1_Final
			--			WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
			--			ORDER BY  script_name,id
			--		END

			--	END		
			END

		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN
				SELECT  prioritys ,Trans_No,id,ScriptCode,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,
				CONVERT(date, opening_date,103),ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),
				CONVERT(date, purchase_date,103),purchase_bill_no,ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,
				CONVERT(date, sold_date,103) ,sold_bill_no ,ISNULL(sold_qty,0) ,ISNULL(sold_rate,0),ISNULL(sold_amount ,0),
				ISNULL(gain_loss,0) ,ISNULL(gain,0) ,ISNULL(loss,0),ISNULL(closing_qty ,0),ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
				ISNULL(short_term,0),ISNULL(long_term,0),ISNULL(speculation,0),ISNULL(gain_speculation,0),ISNULL(loss_speculation,0),
				consultant_name,isnull(nse_rate,0),isnull(bse_rate,0),0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol,
				NoOfDays,0 	'ROI',0 'Actual ROI',0 'Monthly ROI',0 'Anually ROI',ISNULL(Strike_Price,0),OptionType,Last_Date
				FROM #mainoutputtable_1_Final
			END
		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			BEGIN
				SELECT 0 id,0 prioritys,'' ScriptCode,script_name 'Script Name','' Holding_Type,'' opening_bill_no,
				'' 'Opening Date', SUM(ISNULL(opening_qty,0)) 'Opening Qty',ISNULL(SUM(ISNULL(opening_amount,0)) / NULLIF(SUM(ISNULL(opening_qty,0)),0),0) 'Opening Rate',SUM(ISNULL(opening_amount,0)) 'Opening Amount',
				'' 'Purchase Date', '' 'Purchase BillNo',SUM(ISNULL(purchase_qty,0)) 'Purchase Qty',ISNULL(SUM(ISNULL(purchase_amount,0))/ NULLIF(SUM(ISNULL(purchase_qty,0)),0),0) 'Purchase Rate',SUM(ISNULL(purchase_amount ,0))'Purchase Amount',
				'' 'Sold Date','' 'Sold BillNo',SUM(ISNULL(sold_qty ,0))'Sold Qty',
				ISNULL(SUM(ISNULL(sold_amount,0)) / NULLIF(SUM(ISNULL(sold_qty ,0)),0) ,0)'Sold Rate',SUM(ISNULL(sold_amount,0)) 'Sold Amount',
				SUM(ISNULL(gain_loss,0)) 'Gain/Loss',CASE WHEN (SUM(ISNULL(gain_loss,0))) > 0 THEN SUM(ISNULL(gain_loss,0)) ELSE 0 END  AS 'Gain',CASE WHEN(SUM(ISNULL(gain_loss,0))) < 0 THEN SUM(ISNULL(gain_loss,0)) ELSE 0 END  AS  'Loss',
				SUM(ISNULL(closing_qty,0)) 'Closing Qty',SUM(ISNULL(closing_value,0)) / NULLIF(SUM(ISNULL(closing_qty,0)),0) 'Closing Rate',SUM(ISNULL(closing_value,0)) 'Closing Value',
				SUM(ISNULL(short_term,0))short_term,SUM(ISNULL(long_term,0))long_term,SUM(ISNULL(speculation,0))speculation,
				0 gain_speculation,0 loss_speculation,
				'' consultant_name,SUM(ISNULL(nse_rate,0)),SUM(ISNULL(bse_rate,0)),0 isintradaycol, SUM(ISNULL(NoOfDays,0)) NoOfDays,

				CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0 THEN  ISNULL((SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100 ,0)
					 WHEN SUM(ISNULL(Purchase_Amount,0)) != 0 THEN ISNULL((SUM(ISNULL(Gain_Loss,0)) / SUM(ISNULL(Purchase_Amount,0)))   * 100	,0)END AS 	'ROI',

				CASE WHEN SUM(ISNULL(Opening_Amount,0))  != 0  THEN ISNULL(((SUM(ISNULL(Gain_Loss,0))) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100  /  NULLIF(SUM(ISNULL(NoOfDays,0)),0),0) ELSE
				CASE WHEN SUM(ISNULL(Purchase_Amount,0)) != 0  THEN ISNULL(((SUM(ISNULL(Gain_Loss,0))) / NULLIF(SUM(ISNULL(Purchase_Amount,0)),0)) * 100  / NULLIF(SUM(ISNULL(NoOfDays,0)),0),0) END END AS 'Actual ROI',

				CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0  THEN  ISNULL((((SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100 /  NULLIF(SUM(ISNULL(NoOfDays,0)),0)))  * 30,0)  ELSE
				CASE WHEN SUM(ISNULL(Purchase_Amount,0)) != 0 THEN  ISNULL((((SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Purchase_Amount,0)),0))) * 100 / NULLIF(SUM(ISNULL(NoOfDays,0)),0)) * 30,0) 
				END END AS 'Monthly ROI',

				(CASE WHEN SUM(ISNULL(Opening_Amount,0)) != 0 THEN  ISNULL(((SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Opening_Amount,0)),0)) * 100 / NULLIF(SUM(ISNULL(NoOfDays,0)),0)) * 365,0) ELSE
				 CASE WHEN SUM(ISNULL(Purchase_Amount,0)) !=0 THEN  ISNULL(((SUM(ISNULL(Gain_Loss,0)) / NULLIF(SUM(ISNULL(Purchase_Amount,0)),0))* 100 / NULLIF(SUM(ISNULL(NoOfDays,0)),0)) * 365,0) 
				END END ) AS 'Anually ROI', 
				1 sort 
				FROM #mainoutputtable_1_Final
				--WHERE  SUM(ISNULL(opening_qty,0)) != 0  OR SUM(ISNULL(purchase_qty,0)) != 0  or SUM(ISNULL(sold_qty,0)) != 0   
				GROUP BY script_name  --,  isintradaycol
					ORDER BY   script_name--,id
			END
		DROP TABLE #mainoutputtable_1 
		DROP TABLE #alldata 
  END  








































GO
/****** Object:  StoredProcedure [dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency_Summary] AS' 
END
GO



--Execute  [dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency_Summary] 0,1,'','V0001','1120182019'  ,'2015-02-01 12:00:00:00','2018-03-31 03:50:37:50','','', 0 ,0,0,0, 0 
--Execute  proc_Stockholdingposition_Equity_Summary    0,0,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','0','', '0' ,'0',0,0,0
ALTER PROCEDURE [dbo].[proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency_Summary]  --''
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate Datetime,@Todate Datetime, 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,
@DateWiseClosinStock as bit, @IsWithTax as bit = 0,
@Script_Name varchar(max) = '')
AS
BEGIN
SET NOCOUNT ON;
		CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
           prioritys INT,Trans_No VARCHAR(50), id INT,script_Code  VARCHAR(500),script_name  VARCHAR(500),holding_type VARCHAR(200),flag_script_name  VARCHAR(500),flag_holding_type VARCHAR(200),
           opening_date VARCHAR(50),opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
           purchase_date VARCHAR(50),purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
           sold_date VARCHAR(50),sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0,
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   closing_Date 
		   as 
		   CASE WHEN closing_qty < 0 THEN sold_date ELSE
		   CASE WHEN ISNULL(opening_date,'') != '' THEN opening_date ELSE
		   CASE WHEN ISNULL(purchase_date,'') != '' THEN purchase_date ELSE '' 
								END END END,

		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   Other_amt FLOAT DEFAULT 0,
		   ServTax_Amt FLOAT DEFAULT 0,
		   Stt_amt FLOAT DEFAULT 0,
		   sort   VARCHAR(5),
		   isintradaycol  INT ,
		   NoOfDays INT ,
		   ROI FLOAT DEFAULT 0,
		   [Actual ROI] FLOAT DEFAULT 0,
		   [Monthly ROI] FLOAT DEFAULT 0,
		   [Anually ROI] FLOAT DEFAULT 0,
			Strike_Price float,
			OptionType varchar(max),
		   	Last_Date dateTime
        ) 

		
		IF(@ConsultantCode = '0')	
			BEGIN
						
				SELECT DISTINCT p.member_code,p.year_code,
					STUFF((	SELECT distinct ',' + p1.Consultant_Code
							FROM Mst_Consultant p1
							WHERE p.member_code = p1.member_code AND p.year_code = p1.year_code
							FOR XML PATH(''), TYPE
							).value('.', 'NVARCHAR(MAX)')
					,1,1,'') ConsultantCode
				into #temoConsultant
				FROM Mst_Consultant p

				SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant WHERE member_code = @memcode AND year_code = @yearcode)
				DROP table #temoConsultant
			END

		INSERT INTO #mainoutputtable_1_Final_Summary
		EXEC [proc_Stockposition_ROI_F_And_O_AND_MCX_And_Currency]   @status,@Investmenttype,@Ac_Type,@memcode,@yearcode,@Fromdate,@Todate,@ScriptCode,@ConsultantCode,@BSE_NSE_Code,@Is_BFCF,@IsIntraDay,@short_Long_Term,'ALLData',@IsWithTax,@Script_Name
		
	
		SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
		T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
		T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
		T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
		T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
		T1.consultant_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,
		T1.NoOfDays,T1.ROI,T1.[Actual ROI],  T1.[Monthly ROI],T1.[Anually ROI] ,
		Isnull(Dr.Bse_FO_Rate,0) AS 'bse_rate', /**/
		Isnull(Dr.Nse_FO_Rate,0) AS 'nse_rate' /**/
		INTO #alldata_Summary 
		FROM #mainoutputtable_1_Final_Summary  T1
		LEFT JOIN BrokerBill T2 ON T1.Trans_No=T2.Trans_no
		LEFT JOIN DailyRate  DR  
		ON 
			DR.InvestmentType != 0 and Dr.InvestmentType != 2 AND
			DR.Script_Code = T1.script_Code and  Convert(varchar,dr.Trans_Dt,101) =  Convert(varchar,@Todate,101) AND 
			Convert(varchar,DR.Expir_Date ,101) =  Convert(varchar,T1.Last_Date,101) AND
			ISNULL(Substring(RTRIM(LTRIM(T1.OptionType)),0,3),'') = ISNULL( DR.OptionType,'') AND
			ISNULL(DR.Strike_Price,0) = ISNULL(T1.Strike_Price,'')
	
		
		TRUNCATE TABLE #mainoutputtable_1_Final_Summary
		
		INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt,
		T1.NoOfDays,T1.ROI,T1.[Actual ROI],  T1.[Monthly ROI],T1.[Anually ROI] ) 

		SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,
		max(isnull(nse_rate,0)),max(isnull(bse_rate,0)),
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt ,
		 NoOfDays,  ROI, [Actual ROI],  [Monthly ROI], [Anually ROI] 
		FROM #alldata_Summary  
		GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt ,
		NoOfDays, ROI, [Actual ROI],  [Monthly ROI], [Anually ROI] 
		 
		IF(@DateWiseClosinStock = 1)
			BEGIN
				IF(@ConsultantCode<>'')
					BEGIN
						select 1
						SELECT  MAX(id+0)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
						Closing_date 'Closing Date',
						MAX(bse_rate)  AS  'BSERATE',
						MAX(bse_rate) * SUM(closing_qty)  AS  'BSE_Valuation',
						CASE WHEN MAX(bse_rate) = 0 THEn 0 ELSE max(bse_rate) * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
						MAX(nse_rate) AS  'NSERATE',
						MAX(nse_rate) * SUM(closing_qty) AS  'NSE_Valuation',
						CASE WHEN MAX(nse_rate)=0 THEN 0 ELSE  MAX(nse_rate) * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
						SUM(gain_loss) AS 'Profit/Loss',
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
							ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
							0 END 
							END AS 'Avg. Rate',

						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
							ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
							0 END 
							END AS 'Value After Profit/Loss',
						SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,
						
						(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,@Todate,101)), CONVERT(DATETIME,closing_Date,101)),0)) NoOfDays,
								
						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0  AND MAX(ISNULL(bse_rate,0)) <> 0 THEN ((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100 --FOR BSE
							ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0  THEN ((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100     --FOR NSE
							ELSE 
						0 END END,2) AS 'ROI',

						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0   AND MAX(ISNULL(bse_rate,0)) <> 0  THEN (((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / 
						NULLIF(
							
								DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,@Todate,101)), CONVERT(DATETIME,closing_Date,103))
							,0)
						ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN (((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0)))    --FOR NSE
							ELSE 
						0 END END,2) AS 'Actual ROI',

						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0   AND MAX(ISNULL(bse_rate,0)) <> 0 THEN (((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0))) * 30 --FOR BSE
							ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN (((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0))) * 30    --FOR NSE
							ELSE 
						0 END END,2) AS  'Monthly ROI',

						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0  AND MAX(ISNULL(bse_rate,0)) <> 0  THEN ((((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0))) * 30) * 12  --FOR BSE
							ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN ((((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0))) * 30) * 12    --FOR NSE
							ELSE 
						0 END END,2) AS  'Anually ROI',
						'a' sort

						FROM #mainoutputtable_1_Final_Summary
						GROUP BY consultant_name,holding_type,script_name,closing_Date, bse_rate,nse_rate 

						HAVING SUM(closing_qty) != 0
						ORDER BY  	consultant_name,script_name,Holding_Type
					END
				ELSE
					BEGIN
						SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
						closing_Date  'Closing Date',
						MAX(ISNULL(bse_rate,0))  AS  'BSERATE',
						MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,''))  AS  'BSE_Valuation',
						CASE WHEN MAX(ISNULL(bse_rate,0)) = 0 THEn 0 ELSE MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0)) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
						MAX(ISNULL(nse_rate,0)) AS  'NSERATE',
						MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0)) AS  'NSE_Valuation',
						CASE WHEN MAX(ISNULL(nse_rate,0))=0 THEN 0 ELSE  MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0)) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
						SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(ISNULL(closing_qty,0)),0)) 
								ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(ISNULL(closing_qty,0)),0)) ELSE
								0 END 
								END AS 'Avg. Rate',

						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(ISNULL(closing_qty,0)),0)) * (SUM(ISNULL(closing_qty,0))) 
								ELSE
						CASE WHEN 
								SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(ISNULL(closing_qty,0)),0)) * (SUM(ISNULL(closing_qty,0))) ELSE
								0 END 
								END AS 'Value After Profit/Loss',

						SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,
						
						(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,@Todate,101)), CONVERT(DATETIME,closing_Date,101)),0)) NoOfDays,
								
						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0  AND MAX(ISNULL(bse_rate,0)) <> 0 THEN ((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100 --FOR BSE
							ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0  THEN ((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100     --FOR NSE
							ELSE 
						0 END END,2) AS 'ROI',

						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0   AND MAX(ISNULL(bse_rate,0)) <> 0  THEN (((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / 
						NULLIF(
							
								DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,@Todate,101)), CONVERT(DATETIME,closing_Date,103))
							,0)
						ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN (((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0)))    --FOR NSE
							ELSE 
						0 END END,2) AS 'Actual ROI',

						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0   AND MAX(ISNULL(bse_rate,0)) <> 0 THEN (((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0))) * 30 --FOR BSE
							ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN (((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0))) * 30    --FOR NSE
							ELSE 
						0 END END,2) AS  'Monthly ROI',

						ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0  AND MAX(ISNULL(bse_rate,0)) <> 0  THEN ((((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0))) * 30) * 12  --FOR BSE
							ELSE
						CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN ((((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / (SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0))) * 30) * 12    --FOR NSE
							ELSE 
						0 END END,2) AS  'Anually ROI'
						FROM #mainoutputtable_1_Final_Summary
						GROUP BY holding_type,script_name,closing_Date,--bse_rate,nse_rate,
						 consultant_name
						HAVING SUM(closing_qty) != 0
					END
				END
			ELSE  
				BEGIN
					IF(@ConsultantCode<>'')
						BEGIN
							SELECT   max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date','' 'Gain/Loss',
							MAX(ISNULL(bse_rate,0))  AS  'BSERATE',
							MAX(ISNULL(bse_rate,0)) * SUM(closing_qty)  AS  'BSE_Valuation',
							CASE WHEN MAX(ISNULL(bse_rate,0)) = 0 THEn 0 ELSE MAX(ISNULL(bse_rate,0)) * SUM(closing_qty) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
							MAX(ISNULL(nse_rate,0)) AS  'NSERATE',
							MAX(ISNULL(nse_rate,0)) * SUM(closing_qty) AS  'NSE_Valuation',
							CASE WHEN MAX(ISNULL(nse_rate,0)) =0 THEN 0 ELSE  MAX(ISNULL(nse_rate,0)) * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
							SUM(gain_loss) AS 'Profit/Loss',
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
								ELSE
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
								0 END 
								END AS 'Avg. Rate',

							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
								ELSE
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
								0 END 
								END AS 'Value After Profit/Loss',
							SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,0 NoOfDays,0 ROI,0 'Actual ROI',0 'Monthly ROI',0 'Anually ROI','a' sort
							FROM #mainoutputtable_1_Final_Summary
							GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
							HAVING SUM(closing_qty) != 0
							ORDER BY  	consultant_name,script_name,Holding_Type
						END
					ELSE
						BEGIN
							SELECT holding_type,script_name 'Script Name', ROUND(SUM(isnull(closing_value,0)),2) AS 'Closing Value',SUM(isnull(closing_qty,0)) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(isnull(Gain_Loss,0)) 'Gain/Loss',
							MAX(ISNULL(bse_rate,00))  AS  'BSERATE',
							MAX(ISNULL(bse_rate,0)) * SUM(closing_qty)  AS  'BSE_Valuation',
							CASE WHEN MAX(ISNULL(bse_rate,0)) = 0 THEn 0 ELSE MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0)) - SUM(closing_value)  END  AS  'BSE_UnRealizedGainLoss',
							MAX(ISNULL(nse_rate,0)) AS  'NSERATE',
							MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0)) AS  'NSE_Valuation',
							CASE WHEN MAX(ISNULL(nse_rate,0)) = 0 THEN 0 ELSE  SUM(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0)) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
							SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) 
								ELSE
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) ELSE
								0 END 
								END AS 'Avg. Rate',

							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
								ELSE
							CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  SUM(ISNULL(gain_loss,0))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
								0 END 
								END AS 'Value After Profit/Loss',
							0 Other_amt, '' consultant_name,
								
							(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,@Todate,101)), CONVERT(DATETIME,closing_Date,101)),0)) NoOfDays,
								
							CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0   AND MAX(ISNULL(bse_rate,0)) <> 0 THEN ((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100 --FOR BSE
								ELSE
							CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN ((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100     --FOR NSE
								ELSE 
							0 END END AS 'ROI',

							ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0   AND MAX(ISNULL(bse_rate,0)) <> 0 THEN (((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / 
							(
							 NULLIF
								( 
								   DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),103)),0
								)   
							)
								ELSE
								
							CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN (((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / NULLIF(SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0)),0)    --FOR NSE
								ELSE 
							0 END END,2) AS 'Actual ROI',

							ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0  AND MAX(ISNULL(bse_rate,0)) <> 0  THEN (((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / NULLIF(SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0)),0) * 30 --FOR BSE
								ELSE
							CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN (((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / NULLIF(SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0)),0) * 30    --FOR NSE
								ELSE 
							0 END END,2) AS  'Monthly ROI',

							ROUND(CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 0   AND MAX(ISNULL(bse_rate,0)) <> 0 THEN ((((MAX(ISNULL(bse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / NULLIF(SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0)),0) * 30) * 12  --FOR BSE
								ELSE
							CASE WHEN (ISNULL(@BSE_NSE_Code,0)) = 1   AND MAX(ISNULL(nse_rate,0)) <> 0 THEN ((((MAX(ISNULL(nse_rate,0)) * SUM(ISNULL(closing_qty,0))) - (SUM(ISNULL(closing_value,0)))) / NULLIF(SUM(ISNULL(closing_value,0)),0) * 100) / NULLIF(SUM(ISNULL(DATEDIFF(DAY,CONVERT(DATETIME,CONVERT(VARCHAR ,isnull(@Todate,0),101)), CONVERT(DATETIME,isnull(closing_Date,0),101)),0)),0) * 30) * 12    --FOR NSE
								ELSE 
							0 END END,2) AS  'Anually ROI'
								
							FROM #mainoutputtable_1_Final_Summary
							GROUP BY holding_type,script_name ,closing_Date
							HAVING SUM(closing_qty) != 0
							ORDER BY holding_type,script_name
						END
					END

					Select Round(Sum(ISNULL (gain_loss,0)),4) from #mainoutputtable_1_Final_Summary		          	
			        Having Sum(ISNULL (gain_loss,0))!=0
			        Order by 1
			
			       	Select  sum(Other_amt) from BrokerBill where Member_code=@memcode and Yearcode=@yearcode and isfnoBill=@Investmenttype and Trans_Dt<=@Todate

			DROP TABLE #alldata_Summary
END

































GO
/****** Object:  StoredProcedure [dbo].[Proc_TransferClosingBalanceTo_Mst_Account]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TransferClosingBalanceTo_Mst_Account]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TransferClosingBalanceTo_Mst_Account] AS' 
END
GO
ALTER procedure [dbo].[Proc_TransferClosingBalanceTo_Mst_Account]
(
	@InvestmentType int,@Ac_Type_Code varchar(20),@MemberCode varchar(Max),@YearCode varchar(20),@Mode varchar(20),@ClosingAmount float 
 )
 AS
	BEGIN
	SET NOCOUNT ON;
	IF(@InvestmentType=0)
		BEGIN
			UPDATE Mst_Account SET Op_Bal=@ClosingAmount WHERE Member_Code=@MemberCode AND Year_Code=@YearCode and AC_Code= @Ac_Type_Code
		END
	ELSE IF(@InvestmentType=1)
		BEGIN
			set @Ac_Type_Code =(SELECT   distinct(Ac_Code) AS 'Account Code'   FROM Mst_Account  where Ac_name='F & O SHARE TRADING A/C')

			UPDATE Mst_Account SET Op_Bal=@ClosingAmount 
			WHERE Member_Code=@MemberCode AND Year_Code=@YearCode and AC_Code= @Ac_Type_Code
		END
	ELSE IF(@InvestmentType=2)
		BEGIN
			set @Ac_Type_Code =(SELECT   distinct(Ac_Code) AS 'Account Code'   FROM Mst_Account  where Ac_name='MUTUAL FUND INVESTMENT A/C')
			UPDATE Mst_Account SET Op_Bal=@ClosingAmount WHERE Member_Code=@MemberCode AND Year_Code=@YearCode and AC_Code= @Ac_Type_Code
		END
	ELSE IF(@InvestmentType=3)
		BEGIN
			set @Ac_Type_Code =(SELECT   distinct(Ac_Code) AS 'Account Code'   FROM Mst_Account  where Ac_name='COMMODITY SHARE TRADING A/C')
			UPDATE Mst_Account SET Op_Bal=@ClosingAmount WHERE Member_Code=@MemberCode AND Year_Code=@YearCode and AC_Code= @Ac_Type_Code
		END
	ELSE IF(@InvestmentType=4)
		BEGIN
			set @Ac_Type_Code =(SELECT   distinct(Ac_Code) AS 'Account Code'   FROM Mst_Account  where Ac_name='CURRENCY SHARE TRADING A/C')
			UPDATE Mst_Account SET Op_Bal=@ClosingAmount WHERE Member_Code=@MemberCode AND Year_Code=@YearCode and AC_Code= @Ac_Type_Code
		END
	ELSE IF(@InvestmentType=5)
		BEGIN
			set @Ac_Type_Code =(SELECT   distinct(Ac_Code) AS 'Account Code'   FROM Mst_Account  where Ac_name='NCDEX SHARE TRADING A/C')
			UPDATE Mst_Account SET Op_Bal=@ClosingAmount WHERE Member_Code=@MemberCode AND Year_Code=@YearCode and AC_Code= @Ac_Type_Code
		END
	ELSE IF(@Mode='BrokerClosingBal')
		BEGIN
			UPDATE Mst_Account SET Op_Bal = @ClosingAmount WHERE Member_Code = @MemberCode AND Year_Code = @YearCode AND AC_Code= @Ac_Type_Code
		END
	END
	-- select * from Mst_Account	 where AC_Name like 'cu%'
	--select * from Ent_EntryTypes

	 
	 























GO
/****** Object:  StoredProcedure [dbo].[proc_transferEntries]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_transferEntries]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_transferEntries] AS' 
END
GO
--proc_Stockholdingposition_Equity 0,0,'0','D0002','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0','Details'
--SELECT * FROM AC_Trans

ALTER PROCEDURE [dbo].[proc_transferEntries]
@Trans_No VARCHAR(20),@Sr_No VARCHAR(20),@Trans_Dt VARCHAR(20),@Vouch_No VARCHAR(20),@Dr_Code VARCHAR(Max),@Cr_Code VARCHAR(Max),
@Book_Type1 VARCHAR(20),@Narr1 VARCHAR(100),@Internal  VARCHAR(20),@Amount  FLOAT,@PayAgtBill  INT,@Member_Code VARCHAR(Max),
@Year_Code VARCHAR(20),@InvestmentType INT,@EntryType INT,@Reco INT,@isImported INT,@IsDisplayInAc INT,@Mode VARCHAR(50)
AS
	BEGIN
	SET NOCOUNT ON;
		IF(@Mode='AutoJv_Transfer')
			BEGIN
				IF NOT EXISTS(SELECT 1 FROM Ac_Trans WHERE Vouch_No=@Vouch_No AND Member_Code=@Member_Code AND Year_Code=@Year_code)
					BEGIN
						INSERT INTO AC_Trans
						(Trans_No,Sr_No ,Trans_Dt ,Vouch_No ,Dr_Code ,Cr_Code ,Book_Type1 ,Narr1 ,Internal  ,Amount  ,
						 PayAgtBill  ,Member_Code ,Year_Code ,InvestmentType ,EntryType ,Reco ,isImported  ,IsDisplayInAc)	
						VALUES
						(@Trans_No ,@Sr_No ,@Trans_Dt ,@Vouch_No ,@Dr_Code ,@Cr_Code ,@Book_Type1 ,@Narr1 ,@Internal  ,@Amount  ,
						@PayAgtBill  ,@Member_Code ,@Year_Code ,@InvestmentType ,@EntryType ,@Reco ,@isImported  ,@IsDisplayInAc)
						select '1'
					END
				ELSE
					BEGIN
						UPDATE Ac_Trans SET
						--Trans_No=@Trans_No, 
						Sr_No =@Sr_No, Trans_Dt=@Trans_Dt, Vouch_No=@Vouch_No  ,Dr_Code=@Dr_Code  ,Cr_Code=@Cr_Code  ,
						Book_Type1=@Book_Type1  ,Narr1 =@Narr1 ,Internal=@Internal,Amount=@Amount,PayAgtBill=@PayAgtBill  ,
						Member_Code=@Member_Code  ,Year_Code=@Year_Code  ,InvestmentType=@InvestmentType  ,EntryType=@EntryType  ,
						Reco=@Reco  ,isImported=@isImported    ,IsDisplayInAc=@IsDisplayInAc
						WHERE 	Vouch_No=@Vouch_No AND Member_Code=@Member_Code AND Year_Code=@Year_code
						select '1'
					END
			END
	END


























GO
/****** Object:  StoredProcedure [dbo].[proc_TransferStock_BrokerBill_Entries]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TransferStock_BrokerBill_Entries]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_TransferStock_BrokerBill_Entries] AS' 
END
GO
ALTER PROCEDURE [dbo].[proc_TransferStock_BrokerBill_Entries]
@Trans_no VARCHAR(50),@Bill_no VARCHAR(50),@Trans_Dt DateTime,@Valan_code VARCHAR(50),@Member_Code VARCHAR(Max),@Broker_Code VARCHAR(Max),@Ac_Type VARCHAR(50),@Brok_Rate float,
@Brok_Amt float,@Amount float,@Stt_amt float,@ServTax_Amt float,@Other_amt float,@Net_amt float,@Book_Type VARCHAR(50),@YearCode VARCHAR(50),@Ref_TransNo VARCHAR(50),
@isInternalEntry VARCHAR(50),@isFNOBill VARCHAR(50),@Narrat1 VARCHAR(50),@StampDuty float,@Trn_charges float,@Misc_Charges float,@Mode_Type VARCHAR(50),@IsTransferOpening VARCHAR(50),
@IsCommodity VARCHAR(50),@IsDiv_Reinvestment VARCHAR(50),@InvestmentType int
AS
	BEGIN
	SET NOCOUNT ON;
		--IF(@InvestmentType=0)
			--BEGIN
				INSERT INTO BrokerBill  
				(
					Trans_no ,Bill_no ,Trans_Dt ,Valan_code ,Member_Code ,Broker_Code ,Ac_Type ,Brok_Rate ,Brok_Amt ,Amount ,
					Stt_amt ,ServTax_Amt ,Other_amt ,Net_amt ,Book_Type ,YearCode ,Ref_TransNo ,isInternalEntry ,isFNOBill ,
					Narrat1 ,StampDuty ,Trn_charges ,Misc_Charges ,Mode_Type ,IsTransferOpening ,IsCommodity ,IsDiv_Reinvestment  
				)
			VALUES
				(	
					@Trans_no ,@Bill_no ,@Trans_Dt ,@Valan_code ,@Member_Code ,@Broker_Code ,@Ac_Type ,@Brok_Rate ,@Brok_Amt ,
					@Amount ,@Stt_amt ,@ServTax_Amt ,@Other_amt ,@Net_amt ,@Book_Type ,@YearCode ,@Ref_TransNo ,@isInternalEntry ,
					@isFNOBill ,@Narrat1 ,@StampDuty ,@Trn_charges ,@Misc_Charges ,@Mode_Type ,@IsTransferOpening ,@IsCommodity ,@IsDiv_Reinvestment  
				)
				select 1
			--END
	END

	--select * from brokerbill_trans where Member_code='D0002'



























GO
/****** Object:  StoredProcedure [dbo].[proc_TransferStockEntries]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TransferStockEntries]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_TransferStockEntries] AS' 
END
GO
--[proc_TransferStockEntries] '' ,''  ,''  ,''  ,''  ,''  ,''  ,''  ,''  ,''  ,''  ,''  ,''  ,''  ,''  ,'' ,'' ,'' ,'A0001' , '1120182019' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'0' ,''  , 'Get_TransNo_BrokerBillTrans_Openings',1
ALTER PROCEDURE [dbo].[proc_TransferStockEntries] 
@Trans_No VARCHAR(Max),@Sr_No VARCHAR(50),@Bill_no VARCHAR(Max),@Trans_Dt datetime,@TransType VARCHAR(50),@Ac_Type VARCHAR(50),@Script_Code VARCHAR(Max),@MonthYear VARCHAR(50),@Last_Date VARCHAR(50),
@LotSize VARCHAR(50),@LotQty VARCHAR(Max),@Qty VARCHAR(Max),@G_Rate VARCHAR(50),@Brok_Amt VARCHAR(50),@ServTax_Amount VARCHAR(50),@Rate VARCHAR(50),@Amount VARCHAR(500),@Stt_Amount VARCHAR(50),
@Member_code VARCHAR(Max),@YearCode VARCHAR(50),@Consultant_code VARCHAR(Max),@EntrySource VARCHAR(50),@Ref_TransNo VARCHAR(50),@Ref_SrNo VARCHAR(50),@MergedEntry VARCHAR(50),@isFNOBill VARCHAR(50),
@Strike_Price VARCHAR(50),@OptionType VARCHAR(50),@isIntraDay VARCHAR(50),@Brok_PerUnit VARCHAR(50),@frac_Qty VARCHAR(50),@isstock VARCHAR(50),@c_Qty VARCHAR(50),@C_Gross_Rate VARCHAR(50),
@C_Net_Rate VARCHAR(50),@C_Amount VARCHAR(50),@C_STT VARCHAR(50),@C_STax VARCHAR(50),@C_MisChg VARCHAR(50),@TransactionChg VARCHAR(50),@C_StampDuty VARCHAR(50),@Exp_Rate VARCHAR(50),
@PerExp_Unit VARCHAR(50),@FrmNm VARCHAR(50),@ID VARCHAR(50),@InvestmentType VARCHAR(50),@Dp_code  VARCHAR(50), @mode VARCHAR(500),@count int
AS
	BEGIN
	SET NOCOUNT ON;
		IF(@mode='BrokerBillTrans')
			BEGIN
				IF EXISTS(SELECT 1 FROM BrokerBill_Trans WHERE Bill_no='Opening' AND Ac_Type =@Ac_Type  AND Sr_No =@Sr_No  AND Trans_No=@Trans_No and  YearCode=@YearCode and Member_code=@Member_code AND isFNOBill=@InvestmentType and Script_Code=@Script_Code)
					BEGIN
						UPDATE BrokerBill_Trans SET 
						Bill_no =@Bill_no ,Trans_Dt =@Trans_Dt ,TransType =@TransType ,Ac_Type =@Ac_Type ,Script_Code =@Script_Code ,MonthYear =@MonthYear ,
						Last_Date =@Last_Date ,LotSize =@LotSize ,LotQty =@LotQty ,Qty =@Qty ,G_Rate =@G_Rate ,Brok_Amt =@Brok_Amt ,ServTax_Amount =@ServTax_Amount ,Rate =@Rate ,
						Amount =@Amount ,Stt_Amount =@Stt_Amount ,Member_code =@Member_code ,YearCode =@YearCode ,Consultant_code =@Consultant_code ,EntrySource =@EntrySource ,Ref_TransNo =@Ref_TransNo ,
						Ref_SrNo =@Ref_SrNo ,MergedEntry =@MergedEntry ,isFNOBill =@isFNOBill ,Strike_Price =@Strike_Price ,OptionType =@OptionType ,isIntraDay =@isIntraDay ,Brok_PerUnit =@Brok_PerUnit ,
						frac_Qty =@frac_Qty ,isstock =@isstock ,c_Qty =@c_Qty ,C_Gross_Rate =@C_Gross_Rate ,C_Net_Rate =@C_Net_Rate ,C_Amount =@C_Amount ,C_STT =@C_STT ,C_STax =@C_STax ,C_MisChg =@C_MisChg ,
						TransactionChg =@TransactionChg ,C_StampDuty =@C_StampDuty ,--Exp_Rate ,
						PerExp_Unit =@PerExp_Unit ,FrmNm =@FrmNm  
						WHERE Bill_no = 'Opening' AND YearCode=@YearCode AND Member_code=@Member_code AND isFNOBill=@InvestmentType AND  Script_Code= @Script_Code
						AND  ISNULL(Strike_Price,'') = ISNULL(@Strike_Price,'') AND   ISNULL(Last_Date,'') = ISNULL(@Last_Date,'') 
						select concat('0111',@Script_Code,@Sr_No)
					END
				ELSE
					BEGIN
						INSERT INTO BrokerBill_Trans 
						(
							Trans_No ,Sr_No ,Bill_no ,Trans_Dt ,TransType ,Ac_Type ,Script_Code ,MonthYear ,
							Last_Date ,LotSize ,LotQty ,Qty ,G_Rate ,Brok_Amt ,ServTax_Amount ,Rate ,
							Amount ,Stt_Amount ,Member_code ,YearCode ,Consultant_code ,EntrySource ,Ref_TransNo ,
							Ref_SrNo ,MergedEntry ,isFNOBill ,Strike_Price ,OptionType ,isIntraDay ,Brok_PerUnit ,frac_Qty ,
							isstock ,c_Qty ,C_Gross_Rate ,C_Net_Rate ,C_Amount ,C_STT ,C_STax ,C_MisChg ,
							TransactionChg ,C_StampDuty ,--Exp_Rate ,
							PerExp_Unit ,FrmNm 
						)
					VALUES
						(	
							@Trans_No,@Sr_No ,@Bill_no ,@Trans_Dt ,@TransType ,@Ac_Type ,@Script_Code ,@MonthYear ,
							@Last_Date ,@LotSize ,@LotQty ,@Qty ,@G_Rate ,@Brok_Amt ,@ServTax_Amount ,@Rate ,
							@Amount ,@Stt_Amount ,@Member_code ,@YearCode ,@Consultant_code ,@EntrySource ,@Ref_TransNo ,
							@Ref_SrNo ,@MergedEntry ,@isFNOBill ,@Strike_Price ,@OptionType ,@isIntraDay ,@Brok_PerUnit ,
							@frac_Qty ,@isstock ,@c_Qty ,@C_Gross_Rate ,@C_Net_Rate ,@C_Amount ,@C_STT ,@C_STax ,@C_MisChg ,
							@TransactionChg ,@C_StampDuty ,--@Exp_Rate ,
							@PerExp_Unit ,@FrmNm  
						)
						SELECT 1
					END
				
			END
		ELSE IF(@InvestmentType=0 AND @mode='BrokerBillDematInfo')
			BEGIN
				IF EXISTS(SELECT 1 FROM BrokerBill  WHERE YearCode=@YearCode and Member_code=@Member_code AND  isFNOBill=@InvestmentType  AND Trans_no = @Trans_no  )
					BEGIN
						UPDATE BrokerBill_DmatInfo SET 
						--Trans_No=@Trans_No,
						Sr_No=@Sr_No,Local_SrNo=1,Trans_Dt=@Trans_Dt,Member_code=@Member_code,YearCode=@YearCode,dp_code=@Dp_code,Script_Code=@Script_Code,
						Qty=@Qty,Trans_Type=@TransType,internalEntry=@isIntraDay,
						Ref_Trans_No=NULL,Ref_Sr_No=NULL,entrySource=NULL,Consultant_Code=@Consultant_code,Ref_Local_SrNo=NULL,MergedEntry=0,Ac_Type=@Ac_Type,frmpg='OP'
					END
				ELSE
					BEGIN
						INSERT INTO BrokerBill_DmatInfo 
						(
							Trans_No,Sr_No,Local_SrNo,Trans_Dt,Member_code,YearCode,dp_code,Script_Code,Qty,Trans_Type,internalEntry,
							Ref_Trans_No,Ref_Sr_No,entrySource,Consultant_Code,Ref_Local_SrNo,MergedEntry,Ac_Type,frmpg
						)
					VALUES
						(	
							@Trans_No,@Sr_No ,1 ,@Trans_Dt ,@Member_code ,@YearCode ,@Dp_code,@Script_Code ,
							@Qty ,@TransType ,@isIntraDay ,NULL,NULL,NULL,@Consultant_code ,NULL,0,@Ac_Type ,'OP'
						)
					END
					 
				SELECT 1
			END

		ELSE IF(@mode='Get_TransNo_BrokerBillTrans_Openings')
			BEGIN
				DECLARE @tmp VARCHAR(MAX)
				SET @tmp = ''
				SELECT @tmp = @tmp + CONVERT(VARCHAR(MAX),Trans_No) + ', ' FROM BrokerBill_trans 
				WHERE Member_code=@Member_code AND YearCode=@YearCode AND Bill_no='Opening' and Sr_No=@Sr_No AND isFNOBill=@InvestmentType
				ORDER BY Script_Code
				--GROUP BY Trans_No
				SELECT SUBSTRING(@tmp, 0, LEN(@tmp))
			END
		
		ELSE IF(@mode='Delete_All_Openings_BB_BBT_BBDM') --Brokerbill,Brokerbill_Trans,BrokerbillDemateinfo
			BEGIN
				DELETE FROM BrokerBill_trans WHERE Member_code = @Member_code AND YearCode = @YearCode AND Bill_no='Opening' AND Trans_no IN(@Trans_No) 
				DELETE FROM BrokerBill WHERE Member_code = @Member_code AND YearCode = @YearCode AND Bill_no='Opening' AND Trans_no IN(@Trans_No)
				DELETE FROM BrokerBill_DmatInfo WHERE Member_code = @Member_code AND YearCode = @YearCode  AND convert(varchar(MAX),Trans_no) IN(@Trans_No)
				SELECT 1
			END
	END



	--select * from brokerbill_trans where Member_code='D0002'
























GO
/****** Object:  StoredProcedure [dbo].[proc_TransferStockEntriesNew]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TransferStockEntriesNew]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_TransferStockEntriesNew] AS' 
END
GO
-- Execute proc_TransferStockEntriesNew  '2018-04-01','2019-03-31' ,'1120182019','1120192020','Y0001','',0

ALTER PROCEDURE [dbo].[proc_TransferStockEntriesNew] 
	@FromDate DateTime,
	@ToDate Datetime,
	@OldYearCode varchar(Max),
	@NewYearCode VARCHAR(Max),
	@MemeberCode VARCHAR(max),
	@ScriptCode VARCHAR(Max),
	@InvestmentType int
AS
	BEGIN

		SET NOCOUNT ON;
		DECLARE @IsYearExist bit = 0
		if((Select Count(*)  from Mst_Year Where Member_Code = @MemeberCode and  Year_Code = @NewYearCode) != 0) 
			SET @IsYearExist = 1

		
		IF(@IsYearExist = 0)  -- Year Code Not Exists
			BEGIN
				---- FY Year
				INSERT INTO [dbo].[Mst_Year]  ([Member_Code],[Year_Code],[Period_FromDate],[Period_ToDate])
				VALUES (@MemeberCode,@NewYearCode,@FromDate,@ToDate)

				-- Mst Accounts
				INSERT INTO [dbo].[Mst_Account]
				   ( [Member_Code],[Year_Code],[AC_Code],[AC_Name],[Grp_Name],[Grp_id],[Effect],[Effect1],
					 [Op_Bal],[Op_Cal],[InternalEntry],[Contact_Person],[Add1],[Add2],[Add3],[Mobile_No],
					 [Tel_No],[Fax_No],[email],[website],[Pan_No],[UCC_Code],[DecimalPlaces],[DefaultAcInBrokerBill],
					 [IsBrokeragePerUnit],[EQB_Brokerage],[EQS_Brokerage],[FOB_Brokerage],[FOS_Brokerage],[IDB_Brokerage],[IDS_Brokerage],[Investment_Code],
					 [CURB_Brokerage],[CURS_Brokerage],[MCXB],[MCXS],[MFB],[MFS],[eqintradaybuy],[eqintradaysell],[NCDEXB_Brokerage],[NCDEXS_Brokerage])
				
				Select	[Member_Code],@NewYearCode,[AC_Code],[AC_Name],[Grp_Name],[Grp_id],[Effect],[Effect1],
						0,1,[InternalEntry],[Contact_Person],[Add1],[Add2],[Add3],[Mobile_No],
						[Tel_No],[Fax_No],[email],[website],[Pan_No],[UCC_Code],[DecimalPlaces],[DefaultAcInBrokerBill],
						[IsBrokeragePerUnit],[EQB_Brokerage],[EQS_Brokerage],[FOB_Brokerage],[FOS_Brokerage],[IDB_Brokerage],[IDS_Brokerage],[Investment_Code],
						[CURB_Brokerage],[CURS_Brokerage],[MCXB],[MCXS],[MFB],[MFS],[eqintradaybuy],[eqintradaysell],[NCDEXB_Brokerage],[NCDEXS_Brokerage] 
				FROM  mst_Account 
				WHERE  Member_Code = @MemeberCode and Year_Code = @OldYearCode

				---- MST Demat
				INSERT INTO [dbo].[Mst_Demat]
					(	[Member_Code] ,[Year_Code],[DP_Code],[DP_Name] ,[InternalEntry])
				
				Select [Member_Code] ,@NewYearCode,[DP_Code],[DP_Name] ,[InternalEntry]
				FROM  [Mst_Demat] 
				WHERE Member_Code = @MemeberCode and Year_Code = @OldYearCode

				--- Mst Account Opening
				INSERT INTO [dbo].[Mst_Account_Opening]
					( [Member_Code],[Year_Code],[AC_Code],[Op_Bal],[Op_Cal],[cl_bl],[cl_calc],[InternalEntry])
				SELECT [Member_Code],@NewYearCode,[AC_Code],0,[Op_Cal],[cl_bl],[cl_calc],[InternalEntry] 
				FROM Mst_Account_Opening 
				WHERE Member_Code = @MemeberCode and Year_Code = @OldYearCode 

				--- MST Investment

				INSERT INTO [dbo].[Mst_Investment]
					(	[Member_Code] ,[Year_Code],[Investment_Code],[Investment_Name],[InternalEntry])

				SELECT [Member_Code] ,@NewYearCode,[Investment_Code],[Investment_Name],[InternalEntry] 
				FROM Mst_Investment
				WHERE Member_Code = @MemeberCode AND Year_Code = @OldYearCode

				--- Ac Setting
					-- Mst Accounts
				INSERT INTO [dbo].AC_Settings
				   ( [Member_Code],[Year_Code],[AC_Code],[Description],[InternalEntry])
				
				Select	[Member_Code],@NewYearCode,[AC_Code],[AC_Name],[InternalEntry] 
				FROM  mst_Account 
				WHERE  Member_Code = @MemeberCode and Year_Code = @OldYearCode AND AC_Code IN ('1100014','1100001')



			END
		ELSE
			BEGIN
				------- MST Account
				INSERT INTO [dbo].[Mst_Account]
				   ( [Member_Code],[Year_Code],[AC_Code],[AC_Name],[Grp_Name],[Grp_id],[Effect],[Effect1],
					 [Op_Bal],[Op_Cal],[InternalEntry],[Contact_Person],[Add1],[Add2],[Add3],[Mobile_No],
					 [Tel_No],[Fax_No],[email],[website],[Pan_No],[UCC_Code],[DecimalPlaces],[DefaultAcInBrokerBill],
					 [IsBrokeragePerUnit],[EQB_Brokerage],[EQS_Brokerage],[FOB_Brokerage],[FOS_Brokerage],[IDB_Brokerage],[IDS_Brokerage],[Investment_Code],
					 [CURB_Brokerage],[CURS_Brokerage],[MCXB],[MCXS],[MFB],[MFS],[eqintradaybuy],[eqintradaysell],[NCDEXB_Brokerage],[NCDEXS_Brokerage])
				
				SELECT  [Member_Code],@NewYearCode,[AC_Code],[AC_Name],[Grp_Name],[Grp_id],[Effect],[Effect1],
						0,1,[InternalEntry],[Contact_Person],[Add1],[Add2],[Add3],[Mobile_No],
						[Tel_No],[Fax_No],[email],[website],[Pan_No],[UCC_Code],[DecimalPlaces],[DefaultAcInBrokerBill],
						[IsBrokeragePerUnit],[EQB_Brokerage],[EQS_Brokerage],[FOB_Brokerage],[FOS_Brokerage],[IDB_Brokerage],[IDS_Brokerage],[Investment_Code],
						[CURB_Brokerage],[CURS_Brokerage],[MCXB],[MCXS],[MFB],[MFS],[eqintradaybuy],[eqintradaysell],[NCDEXB_Brokerage],[NCDEXS_Brokerage]
				FROM  mst_Account m1
				Where m1.Member_Code = @MemeberCode and m1.Year_Code = @OldYearCode
				AND Ac_Code NOT IN (
										SELECT  Ac_Code	
										FROM    mst_Account m2
										Where m2.Member_Code = @MemeberCode and m2.Year_Code = @NewYearCode
									)

				---------- MST DEMAT
				---- MST Demat
				INSERT INTO [dbo].[Mst_Demat]
					(	[Member_Code] ,[Year_Code],[DP_Code],[DP_Name] ,[InternalEntry])
				
				Select [Member_Code] ,@NewYearCode,[DP_Code],[DP_Name] ,[InternalEntry]
				FROM  [Mst_Demat] D1
				Where Member_Code = @MemeberCode and Year_Code = @OldYearCode
				AND [DP_Code] NOT IN (
										SELECT  [DP_Code]	
										FROM    [Mst_Demat] D2
										Where D2.Member_Code = @MemeberCode and D2.Year_Code = @NewYearCode
									)


			
				--- Mst Account Opening
				INSERT INTO [dbo].[Mst_Account_Opening]
					( [Member_Code],[Year_Code],[AC_Code],[Op_Bal],[Op_Cal],[cl_bl],[cl_calc],[InternalEntry])
				
				SELECT [Member_Code],@NewYearCode,[AC_Code],0,[Op_Cal],[cl_bl],[cl_calc],[InternalEntry] 
				FROM Mst_Account_Opening MO1
				WHERE Member_Code = @MemeberCode and Year_Code = @OldYearCode 
				AND [AC_Code] NOT IN (
										SELECT  [AC_Code]	
										FROM    Mst_Account_Opening MO2
										Where MO2.Member_Code = @MemeberCode and MO2.[Year_Code] = @NewYearCode
									)
				

				--- MST Investment

				INSERT INTO [dbo].[Mst_Investment]
					(	[Member_Code] ,[Year_Code],[Investment_Code],[Investment_Name],[InternalEntry])

				SELECT [Member_Code] ,@NewYearCode,[Investment_Code],[Investment_Name],[InternalEntry] 
				FROM Mst_Investment  MI1
				WHERE Member_Code = @MemeberCode AND Year_Code = @OldYearCode
				AND [Investment_Code] NOT IN (
										SELECT  [Investment_Code]	
										FROM    Mst_Investment MI2
										Where MI2.Member_Code = @MemeberCode and MI2.[Year_Code] = @NewYearCode
									)


				--- Ac Setting
					-- Mst Accounts
				INSERT INTO [dbo].AC_Settings
				   ( [Member_Code],[Year_Code],[AC_Code],[Description],[InternalEntry])
				
				Select	[Member_Code],@NewYearCode,[AC_Code],[AC_Name],[InternalEntry] 
				FROM  mst_Account ma1
				WHERE  Member_Code = @MemeberCode and Year_Code = @OldYearCode AND AC_Code IN ('1100014','1100001')
				AND [AC_Code] NOT IN (
										SELECT  [AC_Code]	
										FROM    AC_Settings AC
										Where AC.Member_Code = @MemeberCode and AC.[Year_Code] = @NewYearCode and  AC.AC_Code IN ('1100014','1100001')
									)
				

			END 


	END


	









GO
/****** Object:  StoredProcedure [dbo].[proc_TransferStocksToNewYear]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TransferStocksToNewYear]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_TransferStocksToNewYear] AS' 
END
GO

-- Execute proc_TransferStocksToNewYear  '2018-04-01','2019-03-31' ,'1120172018','1120182019','D0001','',1, 0,0

ALTER PROCEDURE [dbo].[proc_TransferStocksToNewYear] 
	@FromDate DateTime,
	@ToDate Datetime,
	@OldYearCode varchar(Max),
	@NewYearCode VARCHAR(Max),
	@MemberCode VARCHAR(max),
	@ScriptCode VARCHAR(Max),
	@InvestmentType int,
	@Ac_Type varchar(100),
	@ConsultantCode varchar(100),
	@IsBalanceTransfer bit = 1,
	@IsStockTransfer bit = 1,
	@Is_BFCF bit = 0
AS
	BEGIN
	SET NOCOUNT ON;
---------------------------------------------------------------- Account Transfer Start-----------------------------------------------------------------------------------		
	DECLARE @IsYearExist bit = 0
	DECLARE @NewFromDate DateTime = DateAdd(yy, -1, @FromDate)
	DECLARE @NewEndDate DateTime = DateAdd(yy, -1, @ToDate)

	if((Select Count(*)  from Mst_Year Where Member_Code = @MemberCode and  Year_Code = @NewYearCode) != 0) 
		SET @IsYearExist = 1

		
	IF(@IsYearExist = 0)  -- Year Code Not Exists
		BEGIN
			---- FY Year
			INSERT INTO [dbo].[Mst_Year]  ([Member_Code],[Year_Code],[Period_FromDate],[Period_ToDate])
			VALUES (@MemberCode,@NewYearCode,@FromDate,@ToDate)

			-- Mst Accounts
			INSERT INTO [dbo].[Mst_Account]
				( [Member_Code],[Year_Code],[AC_Code],[AC_Name],[Grp_Name],[Grp_id],[Effect],[Effect1],
					[Op_Bal],[Op_Cal],[InternalEntry],[Contact_Person],[Add1],[Add2],[Add3],[Mobile_No],
					[Tel_No],[Fax_No],[email],[website],[Pan_No],[UCC_Code],[DecimalPlaces],[DefaultAcInBrokerBill],
					[IsBrokeragePerUnit],[EQB_Brokerage],[EQS_Brokerage],[FOB_Brokerage],[FOS_Brokerage],[IDB_Brokerage],[IDS_Brokerage],[Investment_Code],
					[CURB_Brokerage],[CURS_Brokerage],[MCXB],[MCXS],[MFB],[MFS],[eqintradaybuy],[eqintradaysell],[NCDEXB_Brokerage],[NCDEXS_Brokerage])
				
			Select	[Member_Code],@NewYearCode,[AC_Code],[AC_Name],[Grp_Name],[Grp_id],[Effect],[Effect1],
					0,1,[InternalEntry],[Contact_Person],[Add1],[Add2],[Add3],[Mobile_No],
					[Tel_No],[Fax_No],[email],[website],[Pan_No],[UCC_Code],[DecimalPlaces],[DefaultAcInBrokerBill],
					[IsBrokeragePerUnit],[EQB_Brokerage],[EQS_Brokerage],[FOB_Brokerage],[FOS_Brokerage],[IDB_Brokerage],[IDS_Brokerage],[Investment_Code],
					[CURB_Brokerage],[CURS_Brokerage],[MCXB],[MCXS],[MFB],[MFS],[eqintradaybuy],[eqintradaysell],[NCDEXB_Brokerage],[NCDEXS_Brokerage] 
			FROM  mst_Account 
			WHERE  Member_Code = @MemberCode and Year_Code = @OldYearCode

			---- MST Demat
			INSERT INTO [dbo].[Mst_Demat]
				(	[Member_Code] ,[Year_Code],[DP_Code],[DP_Name] ,[InternalEntry])
				
			Select [Member_Code] ,@NewYearCode,[DP_Code],[DP_Name] ,[InternalEntry]
			FROM  [Mst_Demat] 
			WHERE Member_Code = @MemberCode and Year_Code = @OldYearCode

			--- Mst Account Opening
			INSERT INTO [dbo].[Mst_Account_Opening]
				( [Member_Code],[Year_Code],[AC_Code],[Op_Bal],[Op_Cal],[cl_bl],[cl_calc],[InternalEntry])
			SELECT [Member_Code],@NewYearCode,[AC_Code],0,[Op_Cal],[cl_bl],[cl_calc],[InternalEntry] 
			FROM Mst_Account_Opening 
			WHERE Member_Code = @MemberCode and Year_Code = @OldYearCode 

			--- MST Investment

			INSERT INTO [dbo].[Mst_Investment]
				(	[Member_Code] ,[Year_Code],[Investment_Code],[Investment_Name],[InternalEntry])

			SELECT [Member_Code] ,@NewYearCode,[Investment_Code],[Investment_Name],[InternalEntry] 
			FROM Mst_Investment
			WHERE Member_Code = @MemberCode AND Year_Code = @OldYearCode

			--- Ac Setting
		
			INSERT INTO [dbo].AC_Settings
				( [Member_Code],[Year_Code],[AC_Code],[Description],[InternalEntry])
				
			Select	[Member_Code],@NewYearCode,[AC_Code],[AC_Name],[InternalEntry] 
			FROM  mst_Account 
			WHERE  Member_Code = @MemberCode and Year_Code = @OldYearCode AND AC_Code IN ('1100014','1100001')

		END
	ELSE
		BEGIN
			------- MST Account
			INSERT INTO [dbo].[Mst_Account]
				( [Member_Code],[Year_Code],[AC_Code],[AC_Name],[Grp_Name],[Grp_id],[Effect],[Effect1],
					[Op_Bal],[Op_Cal],[InternalEntry],[Contact_Person],[Add1],[Add2],[Add3],[Mobile_No],
					[Tel_No],[Fax_No],[email],[website],[Pan_No],[UCC_Code],[DecimalPlaces],[DefaultAcInBrokerBill],
					[IsBrokeragePerUnit],[EQB_Brokerage],[EQS_Brokerage],[FOB_Brokerage],[FOS_Brokerage],[IDB_Brokerage],[IDS_Brokerage],[Investment_Code],
					[CURB_Brokerage],[CURS_Brokerage],[MCXB],[MCXS],[MFB],[MFS],[eqintradaybuy],[eqintradaysell],[NCDEXB_Brokerage],[NCDEXS_Brokerage])
				
			SELECT  [Member_Code],@NewYearCode,[AC_Code],[AC_Name],[Grp_Name],[Grp_id],[Effect],[Effect1],
					0,1,[InternalEntry],[Contact_Person],[Add1],[Add2],[Add3],[Mobile_No],
					[Tel_No],[Fax_No],[email],[website],[Pan_No],[UCC_Code],[DecimalPlaces],[DefaultAcInBrokerBill],
					[IsBrokeragePerUnit],[EQB_Brokerage],[EQS_Brokerage],[FOB_Brokerage],[FOS_Brokerage],[IDB_Brokerage],[IDS_Brokerage],[Investment_Code],
					[CURB_Brokerage],[CURS_Brokerage],[MCXB],[MCXS],[MFB],[MFS],[eqintradaybuy],[eqintradaysell],[NCDEXB_Brokerage],[NCDEXS_Brokerage]
			FROM  mst_Account m1
			Where m1.Member_Code = @MemberCode and m1.Year_Code = @OldYearCode
			AND Ac_Code NOT IN (
									SELECT  Ac_Code	
									FROM    mst_Account m2
									Where m2.Member_Code = @MemberCode and m2.Year_Code = @NewYearCode
								)

			---------- MST DEMAT
			---- MST Demat
			INSERT INTO [dbo].[Mst_Demat]
				(	[Member_Code] ,[Year_Code],[DP_Code],[DP_Name] ,[InternalEntry])
				
			Select [Member_Code] ,@NewYearCode,[DP_Code],[DP_Name] ,[InternalEntry]
			FROM  [Mst_Demat] D1
			Where Member_Code = @MemberCode and Year_Code = @OldYearCode
			AND [DP_Code] NOT IN (
									SELECT  [DP_Code]	
									FROM    [Mst_Demat] D2
									Where D2.Member_Code = @MemberCode and D2.Year_Code = @NewYearCode
								)

			
			--- Mst Account Opening
			INSERT INTO [dbo].[Mst_Account_Opening]
				( [Member_Code],[Year_Code],[AC_Code],[Op_Bal],[Op_Cal],[cl_bl],[cl_calc],[InternalEntry])
				
			SELECT [Member_Code],@NewYearCode,[AC_Code],0,[Op_Cal],[cl_bl],[cl_calc],[InternalEntry] 
			FROM Mst_Account_Opening MO1
			WHERE Member_Code = @MemberCode and Year_Code = @OldYearCode 
			AND [AC_Code] NOT IN (
									SELECT  [AC_Code]	
									FROM    Mst_Account_Opening MO2
									Where MO2.Member_Code = @MemberCode and MO2.[Year_Code] = @NewYearCode
								)
				
			--- MST Investment

			INSERT INTO [dbo].[Mst_Investment]
				(	[Member_Code] ,[Year_Code],[Investment_Code],[Investment_Name],[InternalEntry])

			SELECT [Member_Code] ,@NewYearCode,[Investment_Code],[Investment_Name],[InternalEntry] 
			FROM Mst_Investment  MI1
			WHERE Member_Code = @MemberCode AND Year_Code = @OldYearCode
			AND [Investment_Code] NOT IN (
									SELECT  [Investment_Code]	
									FROM    Mst_Investment MI2
									Where MI2.Member_Code = @MemberCode and MI2.[Year_Code] = @NewYearCode
								)


			--- Ac Setting
			INSERT INTO [dbo].AC_Settings
				( [Member_Code],[Year_Code],[AC_Code],[Description],[InternalEntry])
				
			Select	[Member_Code],@NewYearCode,[AC_Code],[AC_Name],[InternalEntry] 
			FROM  mst_Account ma1
			WHERE  Member_Code = @MemberCode and Year_Code = @OldYearCode AND AC_Code IN ('1100014','1100001')
			AND [AC_Code] NOT IN (
									SELECT  [AC_Code]	
									FROM    AC_Settings AC
									Where AC.Member_Code = @MemberCode and AC.[Year_Code] = @NewYearCode and  AC.AC_Code IN ('1100014','1100001')
								)
				
		END	
---------------------------------------------------------------- Account Transfer End-----------------------------------------------------------------------------------
---------------------------------------------------------------- Balance Transfer start---------------------------------------------------------------------------------
	If (@IsBalanceTransfer = 1)
		BEGIN

			Create Table #tempBalance
			(
				Ac_Code varchar(10),
				Ac_Name varchar(500),
				Debit_Amount float,
				Credit_Amount float,
				Group_id int,
				Groupname Varchar(500),
				HGroup varchar(500),
				Libilities_Assets_Type Varchar(500)
			)		
				Insert INTO #tempBalance
     			Execute rpt_Final_Statement_Report @Membercode,@OldYearCode,@NewFromDate, @NewEndDate,0
			 
				Update MA
				SET MA.OP_BAL = CASE WHEN  B.Debit_Amount > 0 THEN ABS(B.Debit_Amount) ELSE ABS(B.Credit_Amount) END ,
					MA.OP_CAL = CASE WHEN  B.Debit_Amount > 0 THEN 1 ELSE -1 END 
				FROM MST_Account MA
				JOIN #tempBalance B ON B.Ac_Code = MA.Ac_Code
				WHERE  Member_Code = @MemberCode and Year_Code = @NewYearCode 
		END		 
---------------------------------------------------------------- Balance Transfer End---------------------------------------------------------------------------------

---------------------------------------------------------------- Stock Transfer start---------------------------------------------------------------------------------
	If (@IsStocktransfer = 1)
		BEGIN

			CREATE TABLE #ClosingBalanceEquity
			(
			   id INT, 
			   Trans_No VARCHAR(20),
			   sr_no int,
			   script_name  VARCHAR(500),
			   script_Code  VARCHAR(50),
			   holding_type VARCHAR(200),
			   Act_Type     varchar(20),
			   Broker_Code  VARCHAR(100),
			   Consultant_Code  VARCHAR(20),
			   DP_Code  VARCHAR(50),
			   bill_no VARCHAR(100),		     
			   trans_dt Datetime,
			   qty  FLOAT DEFAULT 0,
			   rate  FLOAT DEFAULT 0,
			   amount FLOAT DEFAULT 0, 
			   isintraday bit DEFAULT 0, 
			   consultant_name VARCHAR(500),
			   BillType varchar(20)
		   ) 

		   CREATE TABLE #ClosingBalanceFNO
			(
			   id INT, 
			   sr_no int,
			   Trans_No VARCHAR(20),
			   script_name  VARCHAR(500),
			   script_code VARCHAR(50),
			   holding_type VARCHAR(200),
			   bill_no VARCHAR(100),	
			   trans_dt Datetime,
			   StrikePrice float,
			   OptionType VARCHAR(100),
			   MonthYear VARCHAR(100),
			   Last_dt Datetime,
			   Exp_Rate float,
			   Broker_Code  VARCHAR(100),
			   DP_Code  VARCHAR(50),
			   qty  FLOAT DEFAULT 0,
			   rate  FLOAT DEFAULT 0,
			   amount FLOAT DEFAULT 0, 
			   isintraday bit DEFAULT 0, 
			   consultant_name VARCHAR(500),
			   Consultant_Code  VARCHAR(20),
			   BillType varchar(20)
		   ) 


		      IF(@Investmenttype = 0)
				BEGIN
					INSERT INTO #ClosingBalanceEquity
					EXECUTE proc_Stockholdingposition_Equity 0,@Investmenttype,@Ac_Type,@MemberCode,@OldYearCode,@NewFromDate, @NewEndDate,@ScriptCode,@ConsultantCode,0,@Is_BFCF, 0 ,'0','ClosingStocks',0,0
					--SELECT  id,Trans_No,sr_no,script_name,script_Code,holding_type,Act_Type,Broker_Code,Consultant_Code,DP_Code,bill_no,trans_dt,qty,rate,amount,isintraday,consultant_name,BillType from TransferData				
				END
		   ELSE IF(@Investmenttype = 2)
				BEGIN
					INSERT INTO #ClosingBalanceEquity
					EXECUTE proc_Stockholdingposition_Equity 0,@Investmenttype,@Ac_Type,@MemberCode,@OldYearCode,@NewFromDate, @NewEndDate,@ScriptCode,@ConsultantCode,0,@Is_BFCF, 0 ,'0','ClosingStocks',0,0						
				END
			ELSE 
				BEGIN
					INSERT INTO #ClosingBalanceFNO
					EXECUTE proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency 0,@Investmenttype,@Ac_Type,@MemberCode,@OldYearCode,@NewFromDate, @NewEndDate,@ScriptCode,@ConsultantCode,0,@Is_BFCF, 0 ,'0','ClosingStocks','',''	       
				   --  SELECT id,Trans_No,sr_no,script_name,script_Code,holding_type,bill_no,trans_dt,StrikePrice,OptionType,MonthYear,Last_dt,Exp_Rate,Broker_Code,DP_Code,qty,rate,amount,isintraday,consultant_name,Consultant_Code,BillType from TransferData
				   -- EXECUTE [proc_Stockholdingposition_F_And_O_AND_MCX_And_Currency] 0,1,'0','D0001','1120172018','2017-04-01 12:00:00:00','2018-03-31 03:50:37:50','','','','', '0' ,'0','ClosingStocks'
				END

			-------------------------------------------------------- Broker Bill start---------------------------------------------------------------
			   Declare @iCount int, @BrokerCode varchar(50), @Amount float,@TransactionNumber bigint
			   IF(@Investmenttype = 0 OR @Investmenttype = 2)
				   BEGIN
						Select Broker_Code, sum(amount) as amount
						Into #TempBrokerGroupEquity
						From #ClosingBalanceEquity
						Group By Broker_Code

						SET @iCount = (Select Count(*) From #TempBrokerGroupEquity)
		
						While(@iCount > 0)
							BEGIN
								Select Top 1 @BrokerCode = Broker_Code,@Amount = amount  FROM #TempBrokerGroupEquity
								IF((Select count(*) From BrokerBill Where Broker_Code = @BrokerCode AND Member_Code = @MemberCode AND YearCode = @NewyearCode and [Bill_no]  = 'Opening' and [isFNOBill] = @InvestmentType) = 0)
									BEGIN
										INSERT INTO  Global_no (Book_typ, dt )
										VALUES ('OP',GETDATE())
										SELECT @TransactionNumber = SCOPE_IDENTITY();
							
										INSERT INTO [dbo].[BrokerBill]
										   ( [Trans_no] ,[Bill_no] ,[Trans_Dt],[Valan_code] ,[Member_Code] ,[Broker_Code] ,[Ac_Type],[Brok_Rate],[Brok_Amt],[Amount],[Stt_amt],
											 [ServTax_Amt],[Other_amt],[Net_amt],[Book_Type],[YearCode],[Ref_TransNo],[isInternalEntry],[isFNOBill],[Narrat1],[StampDuty],
											 [Trn_charges],[Misc_Charges],[Mode_Type],[IsTransferOpening],[IsCommodity],[IsDiv_Reinvestment])
										VALUES
											(   @TransactionNumber,'Opening', @FromDate ,NULL,@MemberCode,@BrokerCode,
												CASE WHEN @Amount > 0 THEN 'C' ELSE 'D' END,
												0,0,ABS(@Amount),0,0,0,ABS(@Amount),'OP',@NewYearCode,NULl,0,@InvestmentType,NULL,0,0,0,0,0,0,0
											)
									END
					
								Delete From #TempBrokerGroupEquity Where Broker_Code = @BrokerCode
								Select @iCount = Count(*) From #TempBrokerGroupEquity
							END
					END
			  ELSE
					BEGIN
						Select Broker_Code, sum(amount) as amount
						Into #TempBrokerGroupFNO
						From #ClosingBalanceFNO
						Group By Broker_Code

						SET @iCount = (Select Count(*) From #TempBrokerGroupFNO)
		
						While(@iCount > 0)
							BEGIN
								
								Select Top 1 @BrokerCode = Broker_Code,@Amount = amount  FROM #TempBrokerGroupFNO
								IF((Select count(*) From BrokerBill Where Broker_Code = @BrokerCode AND Member_Code = @MemberCode AND YearCode = @NewyearCode and [Bill_no]  = 'Opening' and [isFNOBill] = @InvestmentType) = 0)
									BEGIN
										INSERT INTO  Global_no (Book_typ, dt )
										VALUES ('OP',GETDATE())
										SELECT @TransactionNumber = SCOPE_IDENTITY();
							
										INSERT INTO [dbo].[BrokerBill]
										   ( [Trans_no] ,[Bill_no] ,[Trans_Dt],[Valan_code] ,[Member_Code] ,[Broker_Code] ,[Ac_Type],[Brok_Rate],[Brok_Amt],[Amount],[Stt_amt],
											 [ServTax_Amt],[Other_amt],[Net_amt],[Book_Type],[YearCode],[Ref_TransNo],[isInternalEntry],[isFNOBill],[Narrat1],[StampDuty],
											 [Trn_charges],[Misc_Charges],[Mode_Type],[IsTransferOpening],[IsCommodity],[IsDiv_Reinvestment])
										VALUES
											(   @TransactionNumber,'Opening', @FromDate ,NULL,@MemberCode,@BrokerCode,
												CASE WHEN @Amount > 0 THEN 'C' ELSE 'D' END,
												0,0,ABS(@Amount),0,0,0,ABS(@Amount),'OP',@NewYearCode,NULl,0,@InvestmentType,NULL,0,0,0,0,0,0,0
											)
									END
					
								Delete From #TempBrokerGroupFNO Where Broker_Code = @BrokerCode
								Select @iCount = Count(*) From #TempBrokerGroupFNO
							END

					END


			
			
			-------------------------------------------------------- Broker Bill END---------------------------------------------------------------

			-------------------------------------------------------- Broker Bill trans Start ---------------------------------------------------------------

			CREATE TABLE #TempBrokerGroupBrokeBillTrans
			(
				Broker_Code varchar(MAX),
				amount float
			)
			IF(@Investmenttype = 0 OR @Investmenttype = 2)
				BEGIN
					INSERT INTO #TempBrokerGroupBrokeBillTrans
					Select Broker_Code, sum(amount) as amount
					From #ClosingBalanceEquity
					Group By Broker_Code
				END
			ELSE 
				BEGIN
					INSERT INTO #TempBrokerGroupBrokeBillTrans
					Select Broker_Code, sum(amount) as amount
					From #ClosingBalanceFNO
					Group By Broker_Code
				END
			Select @iCount = (Select Count(*) From #TempBrokerGroupBrokeBillTrans)


			While(@iCount > 0)
				BEGIN
					Select Top 1 @BrokerCode = Broker_Code,@Amount = amount  FROM #TempBrokerGroupBrokeBillTrans
					Select @TransactionNumber = Trans_No From BrokerBill Where Broker_Code = @BrokerCode AND Member_Code = @MemberCode AND YearCode = @NewyearCode AND Bill_No = 'Opening' and isFNOBill = @InvestmentType
					IF(@TransactionNumber > 0)
						BEGIN
							if(@ScriptCode is NULL OR  @ScriptCode = '')
								BEGIN
									Delete From [BrokerBill_Trans] Where Trans_No = @TransactionNumber  
									Delete from BrokerBill_DmatInfo Where  Trans_No = @TransactionNumber  
								END
							ELSE
								BEGIN
									Delete From [BrokerBill_Trans] Where Trans_No = @TransactionNumber 
										AND Script_Code in (SELECT Value FROM membercodestable(@ScriptCode,','))  

									Delete From [BrokerBill_DmatInfo] Where Trans_No = @TransactionNumber 
										AND Script_Code in (SELECT Value FROM membercodestable(@ScriptCode,',')) 
								END
							
						    if(@InvestmentType = 0) --Equity
								BEGIN
									INSERT INTO [dbo].[BrokerBill_Trans]
									(	[Trans_No] ,[Sr_No] ,[Bill_no],[Trans_Dt],[TransType],[Ac_Type],[Script_Code],[MonthYear],[Last_Date],[LotSize],[LotQty],[Qty],
										[Disp_qty],[Bal_qty],[G_Rate],[Brok_Amt],[ServTax_Amount],[Rate],[Amount],[Stt_Amount],[Member_code],[YearCode],
										[Consultant_code],[EntrySource],[Ref_TransNo],[Ref_SrNo],[MergedEntry],[isFNOBill],[Strike_Price],[OptionType],[isIntraDay],
										[Brok_PerUnit],[lockedbymerger],[frac_Qty],[Org_Trans_No],[Org_SrNo],[isDeleteMerger],[isstock],[ScripwiseExpense],
										[isClient_code],[isClient_Brokrage],[c_Qty],[C_Gross_Rate],[C_Net_Rate],[C_Amount],
										[C_STT],[C_STax],[C_MisChg],[TransactionChg],[C_StampDuty],[Exp_Rate],[PerExp_Unit],[FrmNm],[IsSLBS]
									)
									SELECT @TransactionNumber, sr_no, 'Opening',trans_dt,
									CASE WHEN BillType = 'Opening' THEN 'Bought' ELSE BillType END,
									Act_Type,script_Code,NULL,NULL,0,0,qty,qty,qty,ABS(rate),0,0,
									ABS(rate), ABS(amount),0,@MemberCode,@NewYearCode, Consultant_Code, 0,
									0,0,0,@InvestmentType,0,NULL,0,NULL,0,0,0,0,0,Null,NULL,NULL,NULL,0,0,0,0,
									0,0,0,0,0,ABS(rate),0,'OP',0
									FROM #ClosingBalanceEquity
									Where Broker_Code = @BrokerCode
								    Order by sr_no,trans_dt,Trans_No
						
									DECLARE @SerialNmber int = 0
									UPDATE BrokerBill_Trans
									set    @SerialNmber = @SerialNmber + 1,    
									Sr_No = ISNULL(Sr_No, 0) + @SerialNmber
									WHERE [Trans_No] = @TransactionNumber

									Update BB
									SET Amount =  (Select SUM([Amount]) FROM [BrokerBill_Trans] WHERE Trans_No = @TransactionNumber )
									FROM BrokerBill BB
									WHERE BB.Trans_no = @TransactionNumber

									---------------Dmate Stock Insert Start---

									INSERT INTO [dbo].[BrokerBill_DmatInfo]
									(
									[Trans_No],[Sr_No] ,[Local_SrNo],[Trans_Dt] ,[Member_code],[YearCode],[dp_code],[Script_Code]  
                                    ,[Qty] ,[Trans_Type],[internalEntry],[Ref_Trans_No] ,[Ref_Sr_No],[entrySource],[Consultant_Code] ,
									[Ref_Local_SrNo],[MergedEntry],[Ac_Type],[frmpg]
                                     )								
							        SELECT @TransactionNumber, sr_no, '1',trans_dt,@MemberCode,@NewYearCode,DP_Code								
									,script_Code,qty,
									CASE WHEN BillType = 'Opening' OR  BillType = 'Bought' THEN 'I' ELSE 'O' END,
									0,0,0,0,Consultant_Code,0,0,Act_Type,'OP'
																
									FROM #ClosingBalanceEquity
									Where Broker_Code = @BrokerCode
									Order by sr_no,trans_dt,Trans_No
						
									Set @SerialNmber = 0
									UPDATE BrokerBill_DmatInfo
									set    @SerialNmber = @SerialNmber + 1,    
									Sr_No = ISNULL(Sr_No, 0) + @SerialNmber
									WHERE [Trans_No] = @TransactionNumber


									--------------- Dmate Stock END---------


								ENd
							else if(@InvestmentType = 1) -- FNO
								BEGIN
							--	Select * from #ClosingBalanceFNO
									INSERT INTO [dbo].[BrokerBill_Trans]
									(	[Trans_No] ,[Sr_No] ,[Bill_no],[Trans_Dt],[TransType],[Ac_Type],[Script_Code],[MonthYear],[Last_Date],[LotSize],[LotQty],[Qty],
										[Disp_qty],[Bal_qty],[G_Rate],[Brok_Amt],[ServTax_Amount],[Rate],[Amount],[Stt_Amount],[Member_code],[YearCode],
										[Consultant_code],[EntrySource],[Ref_TransNo],[Ref_SrNo],[MergedEntry],[isFNOBill],[Strike_Price],[OptionType],[isIntraDay],
										[Brok_PerUnit],[lockedbymerger],[frac_Qty],[Org_Trans_No],[Org_SrNo],[isDeleteMerger],[isstock],[ScripwiseExpense],
										[isClient_code],[isClient_Brokrage],[c_Qty],[C_Gross_Rate],[C_Net_Rate],[C_Amount],
										[C_STT],[C_STax],[C_MisChg],[TransactionChg],[C_StampDuty],[Exp_Rate],[PerExp_Unit],[FrmNm],[IsSLBS]
									)
									SELECT @TransactionNumber, 0, 'Opening',trans_dt,
									CASE WHEN BillType = 'Opening' THEN 'Bought' ELSE BillType END,
									'',script_Code,MonthYear,Last_dt,qty,1,qty,qty,qty,ABS(rate),0,0,
									ABS(rate), ABS(amount),0,@MemberCode,@NewYearCode, Consultant_Code, 0,
									0,0,0,@InvestmentType,StrikePrice,OptionType,0,NULL,0,0,0,0,0,Null,NULL,NULL,NULL,0,0,0,0,
									0,0,0,0,0,ABS(rate),0,'OP',0
									FROM #ClosingBalanceFNO
									Where Broker_Code = @BrokerCode
									Order By trans_dt,Trans_No
						
									SET @SerialNmber = 0
									UPDATE BrokerBill_Trans
									set    @SerialNmber = @SerialNmber + 1,    
									Sr_No = ISNULL(Sr_No, 0) + @SerialNmber
									WHERE [Trans_No] = @TransactionNumber

									Update BB
									SET Amount =  (Select SUM([Amount]) FROM [BrokerBill_Trans] WHERE Trans_No = @TransactionNumber )
									FROM BrokerBill BB
									WHERE BB.Trans_no = @TransactionNumber
								ENd
							else if(@InvestmentType = 2) -- MF
								BEGIN
									INSERT INTO [dbo].[BrokerBill_Trans]
									(	[Trans_No] ,[Sr_No] ,[Bill_no],[Trans_Dt],[TransType],[Ac_Type],[Script_Code],[MonthYear],[Last_Date],[LotSize],[LotQty],[Qty],
										[Disp_qty],[Bal_qty],[G_Rate],[Brok_Amt],[ServTax_Amount],[Rate],[Amount],[Stt_Amount],[Member_code],[YearCode],
										[Consultant_code],[EntrySource],[Ref_TransNo],[Ref_SrNo],[MergedEntry],[isFNOBill],[Strike_Price],[OptionType],[isIntraDay],
										[Brok_PerUnit],[lockedbymerger],[frac_Qty],[Org_Trans_No],[Org_SrNo],[isDeleteMerger],[isstock],[ScripwiseExpense],
										[isClient_code],[isClient_Brokrage],[c_Qty],[C_Gross_Rate],[C_Net_Rate],[C_Amount],
										[C_STT],[C_STax],[C_MisChg],[TransactionChg],[C_StampDuty],[Exp_Rate],[PerExp_Unit],[FrmNm],[IsSLBS]
									)
									SELECT @TransactionNumber, 0, Bill_No,trans_dt,
									CASE WHEN BillType = 'Opening' THEN 'Bought' ELSE BillType END,
									'',script_Code,NULL,NULL,0,0,qty,qty,qty,ABS(rate),0,0,
									ABS(rate), ABS(amount),0,@MemberCode,@NewYearCode, Consultant_Code, 0,
									0,0,0,@InvestmentType,0,NULL,0,NULL,0,0,0,0,0,Null,NULL,NULL,NULL,0,0,0,0,
									0,0,0,0,0,ABS(rate),0,'OP',0
									FROM #ClosingBalanceEquity
									Where Broker_Code = @BrokerCode
						            Order By trans_dt,Trans_No

									SET @SerialNmber = 0
									UPDATE BrokerBill_Trans
									set    @SerialNmber = @SerialNmber + 1,    
									Sr_No = ISNULL(Sr_No, 0) + @SerialNmber
									WHERE [Trans_No] = @TransactionNumber

									Update BB
									SET Amount =  (Select SUM([Amount]) FROM [BrokerBill_Trans] WHERE Trans_No = @TransactionNumber )
									FROM BrokerBill BB
									WHERE BB.Trans_no = @TransactionNumber
								ENd
							else if(@InvestmentType = 3) -- MCX
								BEGIN
									INSERT INTO [dbo].[BrokerBill_Trans]
									(	[Trans_No] ,[Sr_No] ,[Bill_no],[Trans_Dt],[TransType],[Ac_Type],[Script_Code],[MonthYear],[Last_Date],[LotSize],[LotQty],[Qty],
										[Disp_qty],[Bal_qty],[G_Rate],[Brok_Amt],[ServTax_Amount],[Rate],[Amount],[Stt_Amount],[Member_code],[YearCode],
										[Consultant_code],[EntrySource],[Ref_TransNo],[Ref_SrNo],[MergedEntry],[isFNOBill],[Strike_Price],[OptionType],[isIntraDay],
										[Brok_PerUnit],[lockedbymerger],[frac_Qty],[Org_Trans_No],[Org_SrNo],[isDeleteMerger],[isstock],[ScripwiseExpense],
										[isClient_code],[isClient_Brokrage],[c_Qty],[C_Gross_Rate],[C_Net_Rate],[C_Amount],
										[C_STT],[C_STax],[C_MisChg],[TransactionChg],[C_StampDuty],[Exp_Rate],[PerExp_Unit],[FrmNm],[IsSLBS]
									)
								    SELECT @TransactionNumber, 0, 'Opening',trans_dt,
									CASE WHEN BillType = 'Opening' THEN 'Bought' ELSE BillType END,
									'',script_Code,MonthYear,Last_dt,qty,1,qty,qty,qty,ABS(rate),0,0,
									ABS(rate), ABS(amount),0,@MemberCode,@NewYearCode, Consultant_Code, 0,
									0,0,0,@InvestmentType,StrikePrice,OptionType,0,NULL,0,0,0,0,0,Null,NULL,NULL,NULL,0,0,0,0,
									0,0,0,0,0,ABS(rate),0,'OP',0
									FROM #ClosingBalanceFNO
									Where Broker_Code = @BrokerCode
									Order By trans_dt,Trans_No
						
									SET @SerialNmber = 0
									UPDATE BrokerBill_Trans
									set    @SerialNmber = @SerialNmber + 1,    
									Sr_No = ISNULL(Sr_No, 0) + @SerialNmber
									WHERE [Trans_No] = @TransactionNumber

									Update BB
									SET Amount =  (Select SUM([Amount]) FROM [BrokerBill_Trans] WHERE Trans_No = @TransactionNumber )
									FROM BrokerBill BB
									WHERE BB.Trans_no = @TransactionNumber
								ENd
							else if(@InvestmentType = 4) -- Currency
								BEGIN
									INSERT INTO [dbo].[BrokerBill_Trans]
									(	[Trans_No] ,[Sr_No] ,[Bill_no],[Trans_Dt],[TransType],[Ac_Type],[Script_Code],[MonthYear],[Last_Date],[LotSize],[LotQty],[Qty],
										[Disp_qty],[Bal_qty],[G_Rate],[Brok_Amt],[ServTax_Amount],[Rate],[Amount],[Stt_Amount],[Member_code],[YearCode],
										[Consultant_code],[EntrySource],[Ref_TransNo],[Ref_SrNo],[MergedEntry],[isFNOBill],[Strike_Price],[OptionType],[isIntraDay],
										[Brok_PerUnit],[lockedbymerger],[frac_Qty],[Org_Trans_No],[Org_SrNo],[isDeleteMerger],[isstock],[ScripwiseExpense],
										[isClient_code],[isClient_Brokrage],[c_Qty],[C_Gross_Rate],[C_Net_Rate],[C_Amount],
										[C_STT],[C_STax],[C_MisChg],[TransactionChg],[C_StampDuty],[Exp_Rate],[PerExp_Unit],[FrmNm],[IsSLBS]
									)
								    SELECT @TransactionNumber, 0, 'Opening',trans_dt,
									CASE WHEN BillType = 'Opening' THEN 'Bought' ELSE BillType END,
									'',script_Code,MonthYear,Last_dt,qty,1,qty,qty,qty,ABS(rate),0,0,
									ABS(rate), ABS(amount),0,@MemberCode,@NewYearCode, Consultant_Code, 0,
									0,0,0,@InvestmentType,StrikePrice,OptionType,0,NULL,0,0,0,0,0,Null,NULL,NULL,NULL,0,0,0,0,
									0,0,0,0,0,ABS(rate),0,'OP',0
									FROM #ClosingBalanceFNO
									Where Broker_Code = @BrokerCode
									Order By trans_dt,Trans_No
						
									SET @SerialNmber = 0
									UPDATE BrokerBill_Trans
									set    @SerialNmber = @SerialNmber + 1,    
									Sr_No = ISNULL(Sr_No, 0) + @SerialNmber
									WHERE [Trans_No] = @TransactionNumber

									Update BB
									SET Amount =  (Select SUM([Amount]) FROM [BrokerBill_Trans] WHERE Trans_No = @TransactionNumber )
									FROM BrokerBill BB
									WHERE BB.Trans_no = @TransactionNumber
								ENd
							else if(@InvestmentType = 5) -- NCDEX
								BEGIN
									INSERT INTO [dbo].[BrokerBill_Trans]
									(	[Trans_No] ,[Sr_No] ,[Bill_no],[Trans_Dt],[TransType],[Ac_Type],[Script_Code],[MonthYear],[Last_Date],[LotSize],[LotQty],[Qty],
										[Disp_qty],[Bal_qty],[G_Rate],[Brok_Amt],[ServTax_Amount],[Rate],[Amount],[Stt_Amount],[Member_code],[YearCode],
										[Consultant_code],[EntrySource],[Ref_TransNo],[Ref_SrNo],[MergedEntry],[isFNOBill],[Strike_Price],[OptionType],[isIntraDay],
										[Brok_PerUnit],[lockedbymerger],[frac_Qty],[Org_Trans_No],[Org_SrNo],[isDeleteMerger],[isstock],[ScripwiseExpense],
										[isClient_code],[isClient_Brokrage],[c_Qty],[C_Gross_Rate],[C_Net_Rate],[C_Amount],
										[C_STT],[C_STax],[C_MisChg],[TransactionChg],[C_StampDuty],[Exp_Rate],[PerExp_Unit],[FrmNm],[IsSLBS]
									)
									SELECT @TransactionNumber, 0, 'Opening',trans_dt,
									CASE WHEN BillType = 'Opening' THEN 'Bought' ELSE BillType END,
									'',script_Code,MonthYear,Last_dt,qty,1,qty,qty,qty,ABS(rate),0,0,
									ABS(rate), ABS(amount),0,@MemberCode,@NewYearCode, Consultant_Code, 0,
									0,0,0,@InvestmentType,StrikePrice,OptionType,0,NULL,0,0,0,0,0,Null,NULL,NULL,NULL,0,0,0,0,
									0,0,0,0,0,ABS(rate),0,'OP',0
									FROM #ClosingBalanceFNO
									Where Broker_Code = @BrokerCode
									Order By trans_dt,Trans_No
						
									SET @SerialNmber = 0
									UPDATE BrokerBill_Trans
									set    @SerialNmber = @SerialNmber + 1,    
									Sr_No = ISNULL(Sr_No, 0) + @SerialNmber
									WHERE [Trans_No] = @TransactionNumber

									Update BB
									SET Amount =  (Select SUM([Amount]) FROM [BrokerBill_Trans] WHERE Trans_No = @TransactionNumber )
									FROM BrokerBill BB
									WHERE BB.Trans_no = @TransactionNumber
								ENd
						END
					
					Delete From #TempBrokerGroupBrokeBillTrans Where Broker_Code = @BrokerCode
					Select @iCount = Count(*) From #TempBrokerGroupBrokeBillTrans				
				END	
		END
END


	











GO
/****** Object:  StoredProcedure [dbo].[proc_TransferStocksToNewYear_Imp]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TransferStocksToNewYear_Imp]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_TransferStocksToNewYear_Imp] AS' 
END
GO

-- Execute proc_TransferStocksToNewYear  '2018-04-01','2019-03-31' ,'1120172018','1120182019','D0001','',1, 0,0

ALTER PROCEDURE [dbo].[proc_TransferStocksToNewYear_Imp] 
	@FromDate DateTime,
	@ToDate Datetime,
	@OldYearCode varchar(Max),
	@NewYearCode VARCHAR(Max),
	@MemberCode VARCHAR(max),
	@ScriptCode VARCHAR(Max),
	@InvestmentType int,
	@Ac_Type varchar(100),
	@ConsultantCode varchar(100),
	@IsBalanceTransfer bit = 1,
	@IsStockTransfer bit = 1,
	@Is_BFCF bit = 0
AS
	BEGIN
	SET NOCOUNT ON;
---------------------------------------------------------------- Account Transfer Start-----------------------------------------------------------------------------------		
	DECLARE @IsYearExist bit = 0
	DECLARE @NewFromDate DateTime = DateAdd(yy, -1, @FromDate)
	DECLARE @NewEndDate DateTime = DateAdd(yy, -1, @ToDate)

	if((Select Count(*)  from Mst_Year Where Member_Code = @MemberCode and  Year_Code = @NewYearCode) != 0) 
		SET @IsYearExist = 1

		
	IF(@IsYearExist = 0)  -- Year Code Not Exists
		BEGIN
			---- FY Year
			INSERT INTO [dbo].[Mst_Year]  ([Member_Code],[Year_Code],[Period_FromDate],[Period_ToDate])
			VALUES (@MemberCode,@NewYearCode,@FromDate,@ToDate)

			-- Mst Accounts
			INSERT INTO [dbo].[Mst_Account]
				( [Member_Code],[Year_Code],[AC_Code],[AC_Name],[Grp_Name],[Grp_id],[Effect],[Effect1],
					[Op_Bal],[Op_Cal],[InternalEntry],[Contact_Person],[Add1],[Add2],[Add3],[Mobile_No],
					[Tel_No],[Fax_No],[email],[website],[Pan_No],[UCC_Code],[DecimalPlaces],[DefaultAcInBrokerBill],
					[IsBrokeragePerUnit],[EQB_Brokerage],[EQS_Brokerage],[FOB_Brokerage],[FOS_Brokerage],[IDB_Brokerage],[IDS_Brokerage],[Investment_Code],
					[CURB_Brokerage],[CURS_Brokerage],[MCXB],[MCXS],[MFB],[MFS],[eqintradaybuy],[eqintradaysell],[NCDEXB_Brokerage],[NCDEXS_Brokerage])
				
			Select	[Member_Code],@NewYearCode,[AC_Code],[AC_Name],[Grp_Name],[Grp_id],[Effect],[Effect1],
					0,1,[InternalEntry],[Contact_Person],[Add1],[Add2],[Add3],[Mobile_No],
					[Tel_No],[Fax_No],[email],[website],[Pan_No],[UCC_Code],[DecimalPlaces],[DefaultAcInBrokerBill],
					[IsBrokeragePerUnit],[EQB_Brokerage],[EQS_Brokerage],[FOB_Brokerage],[FOS_Brokerage],[IDB_Brokerage],[IDS_Brokerage],[Investment_Code],
					[CURB_Brokerage],[CURS_Brokerage],[MCXB],[MCXS],[MFB],[MFS],[eqintradaybuy],[eqintradaysell],[NCDEXB_Brokerage],[NCDEXS_Brokerage] 
			FROM  mst_Account 
			WHERE  Member_Code = @MemberCode and Year_Code = @OldYearCode

			---- MST Demat
			INSERT INTO [dbo].[Mst_Demat]
				(	[Member_Code] ,[Year_Code],[DP_Code],[DP_Name] ,[InternalEntry])
				
			Select [Member_Code] ,@NewYearCode,[DP_Code],[DP_Name] ,[InternalEntry]
			FROM  [Mst_Demat] 
			WHERE Member_Code = @MemberCode and Year_Code = @OldYearCode

			--- Mst Account Opening
			INSERT INTO [dbo].[Mst_Account_Opening]
				( [Member_Code],[Year_Code],[AC_Code],[Op_Bal],[Op_Cal],[cl_bl],[cl_calc],[InternalEntry])
			SELECT [Member_Code],@NewYearCode,[AC_Code],0,[Op_Cal],[cl_bl],[cl_calc],[InternalEntry] 
			FROM Mst_Account_Opening 
			WHERE Member_Code = @MemberCode and Year_Code = @OldYearCode 

			--- MST Investment

			INSERT INTO [dbo].[Mst_Investment]
				(	[Member_Code] ,[Year_Code],[Investment_Code],[Investment_Name],[InternalEntry])

			SELECT [Member_Code] ,@NewYearCode,[Investment_Code],[Investment_Name],[InternalEntry] 
			FROM Mst_Investment
			WHERE Member_Code = @MemberCode AND Year_Code = @OldYearCode

			--- Ac Setting
		
			INSERT INTO [dbo].AC_Settings
				( [Member_Code],[Year_Code],[AC_Code],[Description],[InternalEntry])
				
			Select	[Member_Code],@NewYearCode,[AC_Code],[AC_Name],[InternalEntry] 
			FROM  mst_Account 
			WHERE  Member_Code = @MemberCode and Year_Code = @OldYearCode AND AC_Code IN ('1100014','1100001')

		END
	ELSE
		BEGIN
			------- MST Account
			INSERT INTO [dbo].[Mst_Account]
				( [Member_Code],[Year_Code],[AC_Code],[AC_Name],[Grp_Name],[Grp_id],[Effect],[Effect1],
					[Op_Bal],[Op_Cal],[InternalEntry],[Contact_Person],[Add1],[Add2],[Add3],[Mobile_No],
					[Tel_No],[Fax_No],[email],[website],[Pan_No],[UCC_Code],[DecimalPlaces],[DefaultAcInBrokerBill],
					[IsBrokeragePerUnit],[EQB_Brokerage],[EQS_Brokerage],[FOB_Brokerage],[FOS_Brokerage],[IDB_Brokerage],[IDS_Brokerage],[Investment_Code],
					[CURB_Brokerage],[CURS_Brokerage],[MCXB],[MCXS],[MFB],[MFS],[eqintradaybuy],[eqintradaysell],[NCDEXB_Brokerage],[NCDEXS_Brokerage])
				
			SELECT  [Member_Code],@NewYearCode,[AC_Code],[AC_Name],[Grp_Name],[Grp_id],[Effect],[Effect1],
					0,1,[InternalEntry],[Contact_Person],[Add1],[Add2],[Add3],[Mobile_No],
					[Tel_No],[Fax_No],[email],[website],[Pan_No],[UCC_Code],[DecimalPlaces],[DefaultAcInBrokerBill],
					[IsBrokeragePerUnit],[EQB_Brokerage],[EQS_Brokerage],[FOB_Brokerage],[FOS_Brokerage],[IDB_Brokerage],[IDS_Brokerage],[Investment_Code],
					[CURB_Brokerage],[CURS_Brokerage],[MCXB],[MCXS],[MFB],[MFS],[eqintradaybuy],[eqintradaysell],[NCDEXB_Brokerage],[NCDEXS_Brokerage]
			FROM  mst_Account m1
			Where m1.Member_Code = @MemberCode and m1.Year_Code = @OldYearCode
			AND Ac_Code NOT IN (
									SELECT  Ac_Code	
									FROM    mst_Account m2
									Where m2.Member_Code = @MemberCode and m2.Year_Code = @NewYearCode
								)

			---------- MST DEMAT
			---- MST Demat
			INSERT INTO [dbo].[Mst_Demat]
				(	[Member_Code] ,[Year_Code],[DP_Code],[DP_Name] ,[InternalEntry])
				
			Select [Member_Code] ,@NewYearCode,[DP_Code],[DP_Name] ,[InternalEntry]
			FROM  [Mst_Demat] D1
			Where Member_Code = @MemberCode and Year_Code = @OldYearCode
			AND [DP_Code] NOT IN (
									SELECT  [DP_Code]	
									FROM    [Mst_Demat] D2
									Where D2.Member_Code = @MemberCode and D2.Year_Code = @NewYearCode
								)

			
			--- Mst Account Opening
			INSERT INTO [dbo].[Mst_Account_Opening]
				( [Member_Code],[Year_Code],[AC_Code],[Op_Bal],[Op_Cal],[cl_bl],[cl_calc],[InternalEntry])
				
			SELECT [Member_Code],@NewYearCode,[AC_Code],0,[Op_Cal],[cl_bl],[cl_calc],[InternalEntry] 
			FROM Mst_Account_Opening MO1
			WHERE Member_Code = @MemberCode and Year_Code = @OldYearCode 
			AND [AC_Code] NOT IN (
									SELECT  [AC_Code]	
									FROM    Mst_Account_Opening MO2
									Where MO2.Member_Code = @MemberCode and MO2.[Year_Code] = @NewYearCode
								)
				
			--- MST Investment

			INSERT INTO [dbo].[Mst_Investment]
				(	[Member_Code] ,[Year_Code],[Investment_Code],[Investment_Name],[InternalEntry])

			SELECT [Member_Code] ,@NewYearCode,[Investment_Code],[Investment_Name],[InternalEntry] 
			FROM Mst_Investment  MI1
			WHERE Member_Code = @MemberCode AND Year_Code = @OldYearCode
			AND [Investment_Code] NOT IN (
									SELECT  [Investment_Code]	
									FROM    Mst_Investment MI2
									Where MI2.Member_Code = @MemberCode and MI2.[Year_Code] = @NewYearCode
								)


			--- Ac Setting
			INSERT INTO [dbo].AC_Settings
				( [Member_Code],[Year_Code],[AC_Code],[Description],[InternalEntry])
				
			Select	[Member_Code],@NewYearCode,[AC_Code],[AC_Name],[InternalEntry] 
			FROM  mst_Account ma1
			WHERE  Member_Code = @MemberCode and Year_Code = @OldYearCode AND AC_Code IN ('1100014','1100001')
			AND [AC_Code] NOT IN (
									SELECT  [AC_Code]	
									FROM    AC_Settings AC
									Where AC.Member_Code = @MemberCode and AC.[Year_Code] = @NewYearCode and  AC.AC_Code IN ('1100014','1100001')
								)
				
		END	
---------------------------------------------------------------- Account Transfer End-----------------------------------------------------------------------------------
---------------------------------------------------------------- Balance Transfer start---------------------------------------------------------------------------------
	If (@IsBalanceTransfer = 1)
		BEGIN

			Create Table #tempBalance
			(
				Ac_Code varchar(10),
				Ac_Name varchar(500),
				Debit_Amount float,
				Credit_Amount float,
				Group_id int,
				Groupname Varchar(500),
				HGroup varchar(500),
				Libilities_Assets_Type Varchar(500)
			)		
				Insert INTO #tempBalance
     			Execute rpt_Final_Statement_Report @Membercode,@OldYearCode,@NewFromDate, @NewEndDate,0
			 
				Update MA
				SET MA.OP_BAL = CASE WHEN  B.Debit_Amount > 0 THEN ABS(B.Debit_Amount) ELSE ABS(B.Credit_Amount) END ,
					MA.OP_CAL = CASE WHEN  B.Debit_Amount > 0 THEN 1 ELSE -1 END 
				FROM MST_Account MA
				JOIN #tempBalance B ON B.Ac_Code = MA.Ac_Code
				WHERE  Member_Code = @MemberCode and Year_Code = @NewYearCode 
				AND Effect in ('A','L','D','C')
		END		 
---------------------------------------------------------------- Balance Transfer End---------------------------------------------------------------------------------

---------------------------------------------------------------- Stock Transfer start---------------------------------------------------------------------------------
	If (@IsStocktransfer = 1)
		BEGIN

			CREATE TABLE #ClosingBalanceEquity
			(
			   id INT, 
			   Trans_No VARCHAR(20),
			   sr_no int,
			   script_name  VARCHAR(500),
			   script_Code  VARCHAR(50),
			   holding_type VARCHAR(200),
			   Act_Type     varchar(20),
			   Broker_Code  VARCHAR(100),
			   Consultant_Code  VARCHAR(20),
			   DP_Code  VARCHAR(50),
			   bill_no VARCHAR(100),		     
			   trans_dt Datetime,
			   qty  FLOAT DEFAULT 0,
			   rate  FLOAT DEFAULT 0,
			   amount FLOAT DEFAULT 0, 
			   isintraday bit DEFAULT 0, 
			   consultant_name VARCHAR(500),
			   BillType varchar(20)
		   ) 

		   CREATE TABLE #ClosingBalanceFNO
			(
			   id INT, 
			   sr_no int,
			   Trans_No VARCHAR(20),
			   script_name  VARCHAR(500),
			   script_code VARCHAR(50),
			   holding_type VARCHAR(200),
			   bill_no VARCHAR(100),	
			   trans_dt Datetime,
			   StrikePrice float,
			   OptionType VARCHAR(100),
			   MonthYear VARCHAR(100),
			   Last_dt Datetime,
			   Exp_Rate float,
			   Broker_Code  VARCHAR(100),
			   DP_Code  VARCHAR(50),
			   qty  FLOAT DEFAULT 0,
			   rate  FLOAT DEFAULT 0,
			   amount FLOAT DEFAULT 0, 
			   isintraday bit DEFAULT 0, 
			   consultant_name VARCHAR(500),
			   Consultant_Code  VARCHAR(20),
			   BillType varchar(20)
		   ) 


		      IF(@Investmenttype = 0)
				BEGIN
					INSERT INTO #ClosingBalanceEquity					
					SELECT  id,Trans_No,sr_no,script_name,script_Code,holding_type,Act_Type,Broker_Code,Consultant_Code,DP_Code,bill_no,trans_dt,qty,rate,amount,isintraday,consultant_name,BillType from TransferData				
				END
		   ELSE IF(@Investmenttype = 2)
				BEGIN
					INSERT INTO #ClosingBalanceEquity
					EXECUTE proc_Stockholdingposition_Equity 0,@Investmenttype,@Ac_Type,@MemberCode,@OldYearCode,@NewFromDate, @NewEndDate,@ScriptCode,@ConsultantCode,0,@Is_BFCF, 0 ,'0','ClosingStocks',0,0						
				END
			ELSE 
				BEGIN
					INSERT INTO #ClosingBalanceFNO			
				     SELECT id,Trans_No,sr_no,script_name,script_Code,holding_type,bill_no,trans_dt,StrikePrice,OptionType,MonthYear,Last_dt,Exp_Rate,Broker_Code,DP_Code,qty,rate,amount,isintraday,consultant_name,Consultant_Code,BillType from TransferData				  
				END

			-------------------------------------------------------- Broker Bill start---------------------------------------------------------------
			   Declare @iCount int, @BrokerCode varchar(50), @Amount float,@TransactionNumber bigint
			   IF(@Investmenttype = 0 OR @Investmenttype = 2)
				   BEGIN
						Select Broker_Code, sum(amount) as amount
						Into #TempBrokerGroupEquity
						From #ClosingBalanceEquity
						Group By Broker_Code

						SET @iCount = (Select Count(*) From #TempBrokerGroupEquity)
		
						While(@iCount > 0)
							BEGIN
								Select Top 1 @BrokerCode = Broker_Code,@Amount = amount  FROM #TempBrokerGroupEquity
								IF((Select count(*) From BrokerBill Where Broker_Code = @BrokerCode AND Member_Code = @MemberCode AND YearCode = @NewyearCode and [Bill_no]  = 'Opening' and [isFNOBill] = @InvestmentType) = 0)
									BEGIN
										INSERT INTO  Global_no (Book_typ, dt )
										VALUES ('OP',GETDATE())
										SELECT @TransactionNumber = SCOPE_IDENTITY();
							
										INSERT INTO [dbo].[BrokerBill]
										   ( [Trans_no] ,[Bill_no] ,[Trans_Dt],[Valan_code] ,[Member_Code] ,[Broker_Code] ,[Ac_Type],[Brok_Rate],[Brok_Amt],[Amount],[Stt_amt],
											 [ServTax_Amt],[Other_amt],[Net_amt],[Book_Type],[YearCode],[Ref_TransNo],[isInternalEntry],[isFNOBill],[Narrat1],[StampDuty],
											 [Trn_charges],[Misc_Charges],[Mode_Type],[IsTransferOpening],[IsCommodity],[IsDiv_Reinvestment])
										VALUES
											(   @TransactionNumber,'Opening', @FromDate ,NULL,@MemberCode,@BrokerCode,
												CASE WHEN @Amount > 0 THEN 'C' ELSE 'D' END,
												0,0,ABS(@Amount),0,0,0,ABS(@Amount),'OP',@NewYearCode,NULl,0,@InvestmentType,NULL,0,0,0,0,0,0,0
											)
									END
					
								Delete From #TempBrokerGroupEquity Where Broker_Code = @BrokerCode
								Select @iCount = Count(*) From #TempBrokerGroupEquity
							END
					END
			  ELSE
					BEGIN
						Select Broker_Code, sum(amount) as amount
						Into #TempBrokerGroupFNO
						From #ClosingBalanceFNO
						Group By Broker_Code

						SET @iCount = (Select Count(*) From #TempBrokerGroupFNO)
		
						While(@iCount > 0)
							BEGIN
								
								Select Top 1 @BrokerCode = Broker_Code,@Amount = amount  FROM #TempBrokerGroupFNO
								IF((Select count(*) From BrokerBill Where Broker_Code = @BrokerCode AND Member_Code = @MemberCode AND YearCode = @NewyearCode and [Bill_no]  = 'Opening' and [isFNOBill] = @InvestmentType) = 0)
									BEGIN
										INSERT INTO  Global_no (Book_typ, dt )
										VALUES ('OP',GETDATE())
										SELECT @TransactionNumber = SCOPE_IDENTITY();
							
										INSERT INTO [dbo].[BrokerBill]
										   ( [Trans_no] ,[Bill_no] ,[Trans_Dt],[Valan_code] ,[Member_Code] ,[Broker_Code] ,[Ac_Type],[Brok_Rate],[Brok_Amt],[Amount],[Stt_amt],
											 [ServTax_Amt],[Other_amt],[Net_amt],[Book_Type],[YearCode],[Ref_TransNo],[isInternalEntry],[isFNOBill],[Narrat1],[StampDuty],
											 [Trn_charges],[Misc_Charges],[Mode_Type],[IsTransferOpening],[IsCommodity],[IsDiv_Reinvestment])
										VALUES
											(   @TransactionNumber,'Opening', @FromDate ,NULL,@MemberCode,@BrokerCode,
												CASE WHEN @Amount > 0 THEN 'C' ELSE 'D' END,
												0,0,ABS(@Amount),0,0,0,ABS(@Amount),'OP',@NewYearCode,NULl,0,@InvestmentType,NULL,0,0,0,0,0,0,0
											)
									END
					
								Delete From #TempBrokerGroupFNO Where Broker_Code = @BrokerCode
								Select @iCount = Count(*) From #TempBrokerGroupFNO
							END
					END

			
			-------------------------------------------------------- Broker Bill END---------------------------------------------------------------

			-------------------------------------------------------- Broker Bill trans Start ---------------------------------------------------------------

			CREATE TABLE #TempBrokerGroupBrokeBillTrans
			(
				Broker_Code varchar(MAX),
				amount float
			)
			IF(@Investmenttype = 0 OR @Investmenttype = 2)
				BEGIN
					INSERT INTO #TempBrokerGroupBrokeBillTrans
					Select Broker_Code, sum(amount) as amount
					From #ClosingBalanceEquity
					Group By Broker_Code
				END
			ELSE 
				BEGIN
					INSERT INTO #TempBrokerGroupBrokeBillTrans
					Select Broker_Code, sum(amount) as amount
					From #ClosingBalanceFNO
					Group By Broker_Code
				END
			Select @iCount = (Select Count(*) From #TempBrokerGroupBrokeBillTrans)

			CREATE TABLE #TEMPCORPORATE
			 (
			   Script_code VARCHAR(MAX)
			 )
			 INSERT INTO #TEMPCORPORATE 
			             SELECT DISTINCT Script_code FROM BrokerBill_Trans WHERE 
                         Trans_NO  IN (  SELECT Trans_NO FROM BrokerBill_Trans WHERE(Ref_TransNo != 0 AND Ref_TransNo IS NOT NULL) 
                         AND Member_Code = @MemberCode and YearCode =@NewyearCode OR Trans_NO IN(SELECT Ref_TransNo FROM BrokerBill_Trans 
                         WHERE(Ref_TransNo != 0 AND Ref_TransNo IS NOT NULL) AND Member_Code = @MemberCode and YearCode =@NewyearCode and isFNObill='0')) 
                         AND Member_Code = @MemberCode and YearCode = @NewyearCode AND isFNObill='0' and MergedEntry='1'

			While(@iCount > 0)
				BEGIN
					Select Top 1 @BrokerCode = Broker_Code,@Amount = amount  FROM #TempBrokerGroupBrokeBillTrans
					Select @TransactionNumber = Trans_No From BrokerBill Where Broker_Code = @BrokerCode AND Member_Code = @MemberCode AND YearCode = @NewyearCode AND Bill_No = 'Opening' and isFNOBill = @InvestmentType
					IF(@TransactionNumber > 0)
						BEGIN
							if(@ScriptCode is NULL OR  @ScriptCode = '')
								BEGIN
									Delete From [BrokerBill_Trans] Where Trans_No = @TransactionNumber  
									AND Member_code=@MemberCode AND YearCode=@NewYearCode AND Script_Code NOT IN(SELECT * FROM #TEMPCORPORATE)

									Delete from BrokerBill_DmatInfo Where  Trans_No = @TransactionNumber  
								    AND Member_code=@MemberCode AND YearCode=@NewYearCode AND Script_Code NOT IN(SELECT * FROM #TEMPCORPORATE)
								END
							ELSE
								BEGIN
									Delete From [BrokerBill_Trans] Where Trans_No = @TransactionNumber AND Member_code=@MemberCode
										AND YearCode=@NewYearCode AND Script_Code in (SELECT Value FROM membercodestable(@ScriptCode,',')) 
										AND Script_Code NOT IN(SELECT * FROM #TEMPCORPORATE)
										 
									Delete From [BrokerBill_DmatInfo] Where Trans_No = @TransactionNumber AND Member_code=@MemberCode
										AND YearCode= @NewYearCode AND Script_Code in (SELECT Value FROM membercodestable(@ScriptCode,',')) 
										AND Script_Code NOT IN(SELECT * FROM #TEMPCORPORATE)
								END
							
						    if(@InvestmentType = 0) --Equity
								BEGIN
									INSERT INTO [dbo].[BrokerBill_Trans]
									(	[Trans_No] ,[Sr_No] ,[Bill_no],[Trans_Dt],[TransType],[Ac_Type],[Script_Code],[MonthYear],[Last_Date],[LotSize],[LotQty],[Qty],
										[Disp_qty],[Bal_qty],[G_Rate],[Brok_Amt],[ServTax_Amount],[Rate],[Amount],[Stt_Amount],[Member_code],[YearCode],
										[Consultant_code],[EntrySource],[Ref_TransNo],[Ref_SrNo],[MergedEntry],[isFNOBill],[Strike_Price],[OptionType],[isIntraDay],
										[Brok_PerUnit],[lockedbymerger],[frac_Qty],[Org_Trans_No],[Org_SrNo],[isDeleteMerger],[isstock],[ScripwiseExpense],
										[isClient_code],[isClient_Brokrage],[c_Qty],[C_Gross_Rate],[C_Net_Rate],[C_Amount],
										[C_STT],[C_STax],[C_MisChg],[TransactionChg],[C_StampDuty],[Exp_Rate],[PerExp_Unit],[FrmNm],[IsSLBS]
									)
									SELECT @TransactionNumber, sr_no, 'Opening',trans_dt,
									CASE WHEN BillType = 'Opening' THEN 'Bought' ELSE BillType END,
									Act_Type,script_Code,NULL,NULL,0,0,qty,qty,qty,ABS(rate),0,0,
									ABS(rate), ABS(amount),0,@MemberCode,@NewYearCode, Consultant_Code, 0,
									0,0,0,@InvestmentType,0,NULL,0,NULL,0,0,0,0,0,Null,NULL,NULL,NULL,0,0,0,0,
									0,0,0,0,0,ABS(rate),0,'OP',0
									FROM #ClosingBalanceEquity
									Where Broker_Code = @BrokerCode AND script_Code NOT IN (SELECT * FROM #TEMPCORPORATE)
								    Order by trans_dt,Trans_No
						
									DECLARE @SerialNmber int = 0
								
									Update BB
									SET Amount =  (Select SUM([Amount]) FROM [BrokerBill_Trans] WHERE Trans_No = @TransactionNumber )
									FROM BrokerBill BB
									WHERE BB.Trans_no = @TransactionNumber

									---------------Dmate Stock Insert Start---

									INSERT INTO [dbo].[BrokerBill_DmatInfo]
									(
									[Trans_No],[Sr_No] ,[Local_SrNo],[Trans_Dt] ,[Member_code],[YearCode],[dp_code],[Script_Code]  
                                    ,[Qty] ,[Trans_Type],[internalEntry],[Ref_Trans_No] ,[Ref_Sr_No],[entrySource],[Consultant_Code] ,
									[Ref_Local_SrNo],[MergedEntry],[Ac_Type],[frmpg]
                                     )								
							        SELECT @TransactionNumber, sr_no, '1',trans_dt,@MemberCode,@NewYearCode,DP_Code								
									,script_Code,qty,
									CASE WHEN BillType = 'Opening' OR  BillType = 'Bought' THEN 'I' ELSE 'O' END,
									0,0,0,0,Consultant_Code,0,0,Act_Type,'OP'
																
									FROM #ClosingBalanceEquity
									Where Broker_Code = @BrokerCode AND script_Code NOT IN (SELECT * FROM #TEMPCORPORATE)
									Order by trans_dt,Trans_No
													
									--------------- Dmate Stock END---------


								ENd
							else if(@InvestmentType = 1) -- FNO
								BEGIN
							--	Select * from #ClosingBalanceFNO
									INSERT INTO [dbo].[BrokerBill_Trans]
									(	[Trans_No] ,[Sr_No] ,[Bill_no],[Trans_Dt],[TransType],[Ac_Type],[Script_Code],[MonthYear],[Last_Date],[LotSize],[LotQty],[Qty],
										[Disp_qty],[Bal_qty],[G_Rate],[Brok_Amt],[ServTax_Amount],[Rate],[Amount],[Stt_Amount],[Member_code],[YearCode],
										[Consultant_code],[EntrySource],[Ref_TransNo],[Ref_SrNo],[MergedEntry],[isFNOBill],[Strike_Price],[OptionType],[isIntraDay],
										[Brok_PerUnit],[lockedbymerger],[frac_Qty],[Org_Trans_No],[Org_SrNo],[isDeleteMerger],[isstock],[ScripwiseExpense],
										[isClient_code],[isClient_Brokrage],[c_Qty],[C_Gross_Rate],[C_Net_Rate],[C_Amount],
										[C_STT],[C_STax],[C_MisChg],[TransactionChg],[C_StampDuty],[Exp_Rate],[PerExp_Unit],[FrmNm],[IsSLBS]
									)
									SELECT @TransactionNumber, 0, 'Opening',trans_dt,
									CASE WHEN BillType = 'Opening' THEN 'Bought' ELSE BillType END,
									'',script_Code,MonthYear,Last_dt,qty,1,qty,qty,qty,ABS(rate),0,0,
									ABS(rate), ABS(amount),0,@MemberCode,@NewYearCode, Consultant_Code, 0,
									0,0,0,@InvestmentType,StrikePrice,OptionType,0,NULL,0,0,0,0,0,Null,NULL,NULL,NULL,0,0,0,0,
									0,0,0,0,0,ABS(rate),0,'OP',0
									FROM #ClosingBalanceFNO
									Where Broker_Code = @BrokerCode
									Order By trans_dt,Trans_No
						
									SET @SerialNmber = 0
									UPDATE BrokerBill_Trans
									set    @SerialNmber = @SerialNmber + 1,    
									Sr_No = ISNULL(Sr_No, 0) + @SerialNmber
									WHERE [Trans_No] = @TransactionNumber

									Update BB
									SET Amount =  (Select SUM([Amount]) FROM [BrokerBill_Trans] WHERE Trans_No = @TransactionNumber )
									FROM BrokerBill BB
									WHERE BB.Trans_no = @TransactionNumber
								ENd
							else if(@InvestmentType = 2) -- MF
								BEGIN
									INSERT INTO [dbo].[BrokerBill_Trans]
									(	[Trans_No] ,[Sr_No] ,[Bill_no],[Trans_Dt],[TransType],[Ac_Type],[Script_Code],[MonthYear],[Last_Date],[LotSize],[LotQty],[Qty],
										[Disp_qty],[Bal_qty],[G_Rate],[Brok_Amt],[ServTax_Amount],[Rate],[Amount],[Stt_Amount],[Member_code],[YearCode],
										[Consultant_code],[EntrySource],[Ref_TransNo],[Ref_SrNo],[MergedEntry],[isFNOBill],[Strike_Price],[OptionType],[isIntraDay],
										[Brok_PerUnit],[lockedbymerger],[frac_Qty],[Org_Trans_No],[Org_SrNo],[isDeleteMerger],[isstock],[ScripwiseExpense],
										[isClient_code],[isClient_Brokrage],[c_Qty],[C_Gross_Rate],[C_Net_Rate],[C_Amount],
										[C_STT],[C_STax],[C_MisChg],[TransactionChg],[C_StampDuty],[Exp_Rate],[PerExp_Unit],[FrmNm],[IsSLBS]
									)
									SELECT @TransactionNumber, 0, Bill_No,trans_dt,
									CASE WHEN BillType = 'Opening' THEN 'Bought' ELSE BillType END,
									'',script_Code,NULL,NULL,0,0,qty,qty,qty,ABS(rate),0,0,
									ABS(rate), ABS(amount),0,@MemberCode,@NewYearCode, Consultant_Code, 0,
									0,0,0,@InvestmentType,0,NULL,0,NULL,0,0,0,0,0,Null,NULL,NULL,NULL,0,0,0,0,
									0,0,0,0,0,ABS(rate),0,'OP',0
									FROM #ClosingBalanceEquity
									Where Broker_Code = @BrokerCode
						            Order By trans_dt,Trans_No

									SET @SerialNmber = 0
									UPDATE BrokerBill_Trans
									set    @SerialNmber = @SerialNmber + 1,    
									Sr_No = ISNULL(Sr_No, 0) + @SerialNmber
									WHERE [Trans_No] = @TransactionNumber

									Update BB
									SET Amount =  (Select SUM([Amount]) FROM [BrokerBill_Trans] WHERE Trans_No = @TransactionNumber )
									FROM BrokerBill BB
									WHERE BB.Trans_no = @TransactionNumber
								ENd
							else if(@InvestmentType = 3) -- MCX
								BEGIN
									INSERT INTO [dbo].[BrokerBill_Trans]
									(	[Trans_No] ,[Sr_No] ,[Bill_no],[Trans_Dt],[TransType],[Ac_Type],[Script_Code],[MonthYear],[Last_Date],[LotSize],[LotQty],[Qty],
										[Disp_qty],[Bal_qty],[G_Rate],[Brok_Amt],[ServTax_Amount],[Rate],[Amount],[Stt_Amount],[Member_code],[YearCode],
										[Consultant_code],[EntrySource],[Ref_TransNo],[Ref_SrNo],[MergedEntry],[isFNOBill],[Strike_Price],[OptionType],[isIntraDay],
										[Brok_PerUnit],[lockedbymerger],[frac_Qty],[Org_Trans_No],[Org_SrNo],[isDeleteMerger],[isstock],[ScripwiseExpense],
										[isClient_code],[isClient_Brokrage],[c_Qty],[C_Gross_Rate],[C_Net_Rate],[C_Amount],
										[C_STT],[C_STax],[C_MisChg],[TransactionChg],[C_StampDuty],[Exp_Rate],[PerExp_Unit],[FrmNm],[IsSLBS]
									)
								    SELECT @TransactionNumber, 0, 'Opening',trans_dt,
									CASE WHEN BillType = 'Opening' THEN 'Bought' ELSE BillType END,
									'',script_Code,MonthYear,Last_dt,qty,1,qty,qty,qty,ABS(rate),0,0,
									ABS(rate), ABS(amount),0,@MemberCode,@NewYearCode, Consultant_Code, 0,
									0,0,0,@InvestmentType,StrikePrice,OptionType,0,NULL,0,0,0,0,0,Null,NULL,NULL,NULL,0,0,0,0,
									0,0,0,0,0,ABS(rate),0,'OP',0
									FROM #ClosingBalanceFNO
									Where Broker_Code = @BrokerCode
									Order By trans_dt,Trans_No
						
									SET @SerialNmber = 0
									UPDATE BrokerBill_Trans
									set    @SerialNmber = @SerialNmber + 1,    
									Sr_No = ISNULL(Sr_No, 0) + @SerialNmber
									WHERE [Trans_No] = @TransactionNumber

									Update BB
									SET Amount =  (Select SUM([Amount]) FROM [BrokerBill_Trans] WHERE Trans_No = @TransactionNumber )
									FROM BrokerBill BB
									WHERE BB.Trans_no = @TransactionNumber
								ENd
							else if(@InvestmentType = 4) -- Currency
								BEGIN
									INSERT INTO [dbo].[BrokerBill_Trans]
									(	[Trans_No] ,[Sr_No] ,[Bill_no],[Trans_Dt],[TransType],[Ac_Type],[Script_Code],[MonthYear],[Last_Date],[LotSize],[LotQty],[Qty],
										[Disp_qty],[Bal_qty],[G_Rate],[Brok_Amt],[ServTax_Amount],[Rate],[Amount],[Stt_Amount],[Member_code],[YearCode],
										[Consultant_code],[EntrySource],[Ref_TransNo],[Ref_SrNo],[MergedEntry],[isFNOBill],[Strike_Price],[OptionType],[isIntraDay],
										[Brok_PerUnit],[lockedbymerger],[frac_Qty],[Org_Trans_No],[Org_SrNo],[isDeleteMerger],[isstock],[ScripwiseExpense],
										[isClient_code],[isClient_Brokrage],[c_Qty],[C_Gross_Rate],[C_Net_Rate],[C_Amount],
										[C_STT],[C_STax],[C_MisChg],[TransactionChg],[C_StampDuty],[Exp_Rate],[PerExp_Unit],[FrmNm],[IsSLBS]
									)
								    SELECT @TransactionNumber, 0, 'Opening',trans_dt,
									CASE WHEN BillType = 'Opening' THEN 'Bought' ELSE BillType END,
									'',script_Code,MonthYear,Last_dt,qty,1,qty,qty,qty,ABS(rate),0,0,
									ABS(rate), ABS(amount),0,@MemberCode,@NewYearCode, Consultant_Code, 0,
									0,0,0,@InvestmentType,StrikePrice,OptionType,0,NULL,0,0,0,0,0,Null,NULL,NULL,NULL,0,0,0,0,
									0,0,0,0,0,ABS(rate),0,'OP',0
									FROM #ClosingBalanceFNO
									Where Broker_Code = @BrokerCode
									Order By trans_dt,Trans_No
						
									SET @SerialNmber = 0
									UPDATE BrokerBill_Trans
									set    @SerialNmber = @SerialNmber + 1,    
									Sr_No = ISNULL(Sr_No, 0) + @SerialNmber
									WHERE [Trans_No] = @TransactionNumber

									Update BB
									SET Amount =  (Select SUM([Amount]) FROM [BrokerBill_Trans] WHERE Trans_No = @TransactionNumber )
									FROM BrokerBill BB
									WHERE BB.Trans_no = @TransactionNumber
								ENd
							else if(@InvestmentType = 5) -- NCDEX
								BEGIN
									INSERT INTO [dbo].[BrokerBill_Trans]
									(	[Trans_No] ,[Sr_No] ,[Bill_no],[Trans_Dt],[TransType],[Ac_Type],[Script_Code],[MonthYear],[Last_Date],[LotSize],[LotQty],[Qty],
										[Disp_qty],[Bal_qty],[G_Rate],[Brok_Amt],[ServTax_Amount],[Rate],[Amount],[Stt_Amount],[Member_code],[YearCode],
										[Consultant_code],[EntrySource],[Ref_TransNo],[Ref_SrNo],[MergedEntry],[isFNOBill],[Strike_Price],[OptionType],[isIntraDay],
										[Brok_PerUnit],[lockedbymerger],[frac_Qty],[Org_Trans_No],[Org_SrNo],[isDeleteMerger],[isstock],[ScripwiseExpense],
										[isClient_code],[isClient_Brokrage],[c_Qty],[C_Gross_Rate],[C_Net_Rate],[C_Amount],
										[C_STT],[C_STax],[C_MisChg],[TransactionChg],[C_StampDuty],[Exp_Rate],[PerExp_Unit],[FrmNm],[IsSLBS]
									)
									SELECT @TransactionNumber, 0, 'Opening',trans_dt,
									CASE WHEN BillType = 'Opening' THEN 'Bought' ELSE BillType END,
									'',script_Code,MonthYear,Last_dt,qty,1,qty,qty,qty,ABS(rate),0,0,
									ABS(rate), ABS(amount),0,@MemberCode,@NewYearCode, Consultant_Code, 0,
									0,0,0,@InvestmentType,StrikePrice,OptionType,0,NULL,0,0,0,0,0,Null,NULL,NULL,NULL,0,0,0,0,
									0,0,0,0,0,ABS(rate),0,'OP',0
									FROM #ClosingBalanceFNO
									Where Broker_Code = @BrokerCode
									Order By trans_dt,Trans_No
						
									SET @SerialNmber = 0
									UPDATE BrokerBill_Trans
									set    @SerialNmber = @SerialNmber + 1,    
									Sr_No = ISNULL(Sr_No, 0) + @SerialNmber
									WHERE [Trans_No] = @TransactionNumber

									Update BB
									SET Amount =  (Select SUM([Amount]) FROM [BrokerBill_Trans] WHERE Trans_No = @TransactionNumber )
									FROM BrokerBill BB
									WHERE BB.Trans_no = @TransactionNumber
								ENd
						END
					
					Delete From #TempBrokerGroupBrokeBillTrans Where Broker_Code = @BrokerCode
					Select @iCount = Count(*) From #TempBrokerGroupBrokeBillTrans				
				END	
		END
END


	











GO
/****** Object:  StoredProcedure [dbo].[proc_validation]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_validation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_validation] AS' 
END
GO
ALTER PROCEDURE [dbo].[proc_validation]    --'c','Member_Code','a','a','AC_Settings','delete'
@id VARCHAR(20),
@param1 VARCHAR(50),
@param2 VARCHAR(50),
@param3 VARCHAR(50),
@outputval  VARCHAR(MAX),
@mode VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
	DECLARE @val1 VARCHAR(20)
	DECLARE @val2 VARCHAR(20)
	DECLARE @val3 VARCHAR(100)

	IF(@mode='delete')
		BEGIN
		 DECLARE @tep_table TABLE
			( 
				TABLE_QUALIFIER			NVARCHAR(MAX),	TABLE_OWNER			NVARCHAR(MAX),
				TABLE_NAME              NVARCHAR(MAX),	COLUMN_NAME			NVARCHAR(MAX),
				DATA_TYPE               NVARCHAR(MAX),	TYPE_NAME			NVARCHAR(MAX),
				"PRECISION"             NVARCHAR(MAX),	"LENGTH"			NVARCHAR(MAX),
				SCALE                   NVARCHAR(MAX),	RADIX				NVARCHAR(MAX),
				NULLABLE                NVARCHAR(MAX),	REMARKS				NVARCHAR(MAX),
				COLUMN_DEF              NVARCHAR(MAX),	SQL_DATA_TYPE		NVARCHAR(MAX),
				SQL_DATETIME_SUB        NVARCHAR(MAX),	CHAR_OCTET_LENGTH   NVARCHAR(MAX),
				ORDINAL_POSITION        NVARCHAR(MAX),	IS_NULLABLE NVARCHAR(MAX),
				SS_DATA_TYPE            NVARCHAR(MAX) 
			)
		  	INSERT INTO @tep_table
			EXEC sp_columns NULL,NULL,NULL, @param1,NULL
			SELECT * FROM  @tep_table
		END

	ELSE IF(@mode='checkexistence')
		BEGIN
			DECLARE @qry VARCHAR(MAX)
			SET @qry = 'SELECT ' + @outputval 
			EXEC  @qry
		END

	ELSE IF (@mode='GetInternalAcc')
		BEGIN
			SELECT Member_Code,Year_Code,AC_Code,AC_Name,Grp_Name,Grp_id,Effect,Effect1,Op_Bal,Op_Cal,InternalEntry,Contact_Person,
			Add1,Add2,Add3,Mobile_No,Tel_No,Fax_No,email,website,Pan_No,UCC_Code,DecimalPlaces,DefaultAcInBrokerBill,IsBrokeragePerUnit,
			EQB_Brokerage,		EQS_Brokerage,FOB_Brokerage,FOS_Brokerage,IDB_Brokerage,IDS_Brokerage,Investment_Code,CURB_Brokerage,
			CURS_Brokerage,MCXB,MCXS,MFB,MFS,eqintradaybuy,eqintradaysell ,NCDEXB_Brokerage	,NCDEXS_Brokerage,ExpenseSetting	
			FROM InternalAccountMaster WHERE InternalEntry=1 
		END

	ELSE IF (@mode='GetExternalAcc')
		BEGIN
			SET @val1 = SUBSTRING(@param2, 3, 4); 
			SET @val2 = SUBSTRING(@param2, 7, 4); 
			SET @val1=CONVERT(INT,@val1)-1
			SET @val2=CONVERT(INT,@val2)-1
			SET @val3='11'+ CONVERT(VARCHAR(100),@val1+@val2)

			SELECT * FROM Mst_Account WHERE Member_Code=@param1 and year_code=@val3
		END

	ELSE IF(@mode='checkpreviousentry')
		BEGIN
			DECLARE @par1 VARCHAR(20)
			DECLARE @par2 VARCHAR(20)
			DECLARE @par3 VARCHAR(100)
			SET @par1 = SUBSTRING(@param2, 3, 4); 
			SET @par2 = SUBSTRING(@param2, 7, 4); 
			SET @par1 = CONVERT(INT,@par1)-1
			SET @par2 = CONVERT(INT,@par2)-1
			SET @par3 = '11'+ CONVERT(VARCHAR(100),@par1+@par2)
			SELECT  COUNT(*) AS 'count',@par3 AS 'year' FROM mst_account WHERE Member_Code=@param1 AND Year_Code=@par3
		END
END

--select count(AC_Code) from Mst_Account where Year_Code= '1120172018'   and  Member_Code='V0001'


























GO
/****** Object:  StoredProcedure [dbo].[proc_WithTaxStockholding_Equity]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_WithTaxStockholding_Equity]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_WithTaxStockholding_Equity] AS' 
END
GO





--[proc_WithTaxStockholding_Equity] 0,0,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','H0053','','','', '0' ,'0','Details'
ALTER  PROCEDURE [dbo].[proc_WithTaxStockholding_Equity] 
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX))
AS 
  BEGIN
  SET NOCOUNT ON; 
		DECLARE @StartYearDate varchar(20) = '01/04/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate=CONVERT(VARCHAR(10),@StartYearDate,101)
		CREATE TABLE #mainoutputtable_1
        ( 
		   Dup_pkid int,
		   pkid INT identity(1,1), 
           Trans_No VARCHAR(20),
		   id INT,prioritys INT,
		   Trans_Type  VARCHAR(50), 
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(10),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name  VARCHAR(500),
		   flag_holding_type VARCHAR(200), 
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(10),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount AS( [opening_qty] * [opening_rate] ), 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount AS( purchase_qty * purchase_rate ), 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount AS ( sold_qty * sold_rate ), 
		   gain_loss float,
		   closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 
           closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
		   closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
		   short_term FLOAT DEFAULT 0,
		   long_term  FLOAT DEFAULT 0,
           speculation  FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(20) ,
		   ScriptCode Varchar(50), Consultant_code VARCHAR(20)
        )  

		CREATE TABLE #mainoutputtable_1_Final
        ( 
		   Dup_pkid int,
		   OrderBy varchar(100),
           Trans_No VARCHAR(20),
		   id INT,prioritys INT   ,
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(10),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name  VARCHAR(500),
		   flag_holding_type VARCHAR(200), 
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(10),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(20),
		   sort   VARCHAR(5),
		   ScriptCode Varchar(50), Consultant_code VARCHAR(20)
        ) 

		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates DATETIME,@qty INT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT,@ScriptId Varchar(50)  
		DECLARE @tablerowscount INT
      IF(@status = 0) 
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
				@openingDate DATETIME,@openingRate FLOAT,@openingQty INT,@openingAmount FLOAT,
				@purchaseDate DATETIME,@PurchaseBillNo  VARCHAR(50),@purchaseRate FLOAT,@purchaseQty INT,
				@purchaseAmount FLOAT,@soldDate DATETIME,@soldBillNo  VARCHAR(50),@soldRate FLOAT,@soldQty INT,
				@soldAmount FLOAT,@purchaseScriptId VARCHAR(50),@Consultant_Name  VARCHAR(100), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(10),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,@PurchaseIntraFlag VARCHAR(100),@SaleIntraFlag VARCHAR(10) 
				DECLARE @TransTypes VARCHAR(200),@Trans_No VARCHAR(20), @Consultant_code VARCHAR(20),@Dup_pkid int, @Pkid int,@idcount int

				CREATE TABLE #SCriptCodes
				(
					ScriptCodes varchar(MAX)
				)

				IF(@ScriptCode != '')
					INSERT INTO #SCriptCodes SELECT value FROM Fn_split(@ScriptCode, ',') 
				ELSE 
					INSERT INTO #SCriptCodes select BBT.Script_Code from mst_script 
					INNER JOIN BrokerBill_Trans  BBT ON BBT.Script_Code=Mst_Script.Script_Code  
					GROUP BY BBT.Script_Code

				CREATE TABLE #ConsultantCodes
				(
					ConsultantCodes varchar(MAX)
				)
				
				IF(@ConsultantCode = '0')	
					BEGIN
						SELECT DISTINCT p.member_code,p.year_code,
							STUFF((	SELECT distinct ',' + p1.Consultant_Code
									FROM Mst_Consultant p1
									FOR XML PATH(''), TYPE
									).value('.', 'NVARCHAR(MAX)')
							,1,1,'') ConsultantCode
						into #temoConsultant
						FROM Mst_Consultant p

						SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant)-- WHERE member_code = @memcode AND year_code = @yearcode)
						DROP table #temoConsultant
			
					END
				 
				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes select MC.Consultant_Code from Mst_Consultant MC
					JOIN BrokerBill_Trans BBT ON BBT.Consultant_code = MC.Consultant_Code
					GROUP BY MC.Consultant_Code  

				SELECT	ROW_NUMBER ( ) OVER (ORDER BY t.script_code,t.Ac_Type,t.trans_dt ) AS NameId,t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,t.TransType,t.Ac_Type,t.Script_Code, t.Qty,t.Rate,
				t.Member_code,t.YearCode,t.Consultant_code,t.isFNOBill, t.isIntraDay,t.Exp_Rate,t.FrmNm,t.ID,
				Ms.bse_code,Ms.nse_code,Ms.script_name,ma.ac_name AS 'Holding Type',
						CASE	WHEN t.Bill_no = 'Opening'  THEN 'Opening' 
								WHEN t.TransType='Bought' AND  t.Bill_no != 'Opening'  THEN 'Bought' 
								WHEN TransType='Bought' AND t.Bill_no = 'Bonus' THEN 'Bonus' 
								WHEN TransType='Bought' AND t.Bill_no ='Rights'THEN 'Rights' 
								WHEN TransType='Bought' AND  t.Bill_no ='Split' THEN 'Split' 
								WHEN TransType='Bought' AND  t.Bill_no ='Transfer' THEN 'Transfer' 
								WHEN TransType='Sold' THEN 'Sold' 
								WHEN TransType='Bought' AND Frmnm = 'IPO' THEN 'IPO'  
						END AS 'Flag_Type',
						cm.Consultant_Name  
						INTO #alldata 
				FROM brokerbill_trans t  WITH (NOLOCK)
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN mst_account ma ON t.ac_type = ma.ac_code AND ma.member_code = @memcode
				LEFT JOIN Mst_Consultant cm ON cm.Consultant_code  = t.Consultant_code  
				WHERE  isfnobill = @Investmenttype AND trans_dt <= @Todate AND t.member_code = @memcode AND yearcode = @yearcode  AND 
				Ac_Type =(CASE WHEN  @Ac_Type='0' THEN Ac_Type  ELSE  @Ac_Type END)
				AND  t.script_code IN (SELECT * FROM #SCriptCodes)
				AND	 t.Consultant_code IN (SELECT * FROM #ConsultantCodes)
				AND  ISNULL(t.isIntraDay,0) =(CASE WHEN ISNULL(@IsIntraDay,0)=0 THEN   ISNULL(isIntraDay,0) ELSE  ISNULL(@IsIntraDay,0) END) AND t.MergedEntry=0
				AND t.MergedEntry = 0  AND ISNULL( t.Ref_SrNo,0) != 1
				AND (IsSLBS=0 OR IsSLBS IS NUll) 
				GROUP BY t.Trans_Dt,t.Trans_No,t.Sr_No,t.Script_Code,script_name ,t.Ac_Type,ma.AC_Name,t.Consultant_code,cm.Consultant_Name,t.Bill_no,TransType, t.Qty,Rate,t.Amount,
				t.Member_Code,t.YearCode,Ref_SrNo,t.MergedEntry,t.isFNOBill,isIntraDay,Exp_Rate,FrmNm,ID,bse_code,nse_code
				 
				DECLARE @isIntradayCol INT 
				DECLARE  @COUNT INT = 0
			
				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT id,Trans_No,script_name,Script_Code,  [holding type],bill_no,CONVERT(DATETIME,trans_dt,101),qty,Exp_Rate,ISNULL(qty, 0) * ISNULL(Exp_Rate, 0),ISNULL(isintraday, 0),consultant_name ,Consultant_code  
				FROM #alldata
				WHERE #alldata.bill_no IN('Split','Opening') OR  CONVERT(date,trans_dt,101)  < CONVERT(date ,@StartYearDate,101)
				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@Consultant_code
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
						SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
						SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
						SET @Dup_pkid = ISNULL(@Dup_pkid,0)
						SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
						SET @Dup_pkid = @Dup_pkid + 1

						DECLARE @IDs INT=0
						DECLARE @Flag_Types VARCHAR(10)
						SET @Flag_Types = (SELECT CASE WHEN @billno = 'Opening' THEN 'Opening' ELSE 'Bought' END)
						IF( @Flag_Types = 'Opening'  OR (@billno IN('Split') AND CONVERT(date,@dates,101)  < CONVERT(date ,@StartYearDate,101)))
							BEGIN	
								INSERT INTO #mainoutputtable_1   
								(
									Dup_pkid,opening_bill_no ,id,Trans_No,ScriptCode,Consultant_code ,  Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,consultant_name
								) 
								SELECT @Dup_pkid,@billno,@ID,@Trans_No,@ScriptId,@Consultant_code , @Flag_Types,@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Consultant_Name
							END 
						IF(@idcount>0)
							BEGIN
								UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and ScriptCode<>@ScriptId
							END
			 			FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@Consultant_code
					END 

				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 
				
				DECLARE @salecount INT=0,@Boughtcount INT=0,@Flag_Type VARCHAR(20)
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 

				SELECT id,Bill_no,Flag_Type,TransType,Script_Code,script_name,[holding type],Consultant_code ,Trans_No,CONVERT(DATETIME, trans_dt,101), qty,Exp_Rate,qty * Exp_Rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name
				FROM #alldata 
				WHERE (TransType in('Bought','Sold')  AND CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
				
				OPEN purchaseANDSaledatacursor 
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Consultant_code , @Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
				
				WHILE (@@FETCH_STATUS = 0) 
						BEGIN
							IF(@Investmenttype=2)
								SET	@holding_type='Mutual Fund'
					
							SET @COUNT = 0
							DECLARE @IsOpening INT =0
							DECLARE @prioritysId INT=0
							DECLARE @str VARCHAR(MAX)=''	
							DECLARE @purchase_Op_Qty FLOAT =0
							DECLARE @purchase_Op_Bill VARCHAR(20)=''
							DECLARE @purchase_Op_Date VARCHAR(20)=''
							DECLARE @purchase_Op_Rate FLOAT=0
							DECLARE	@PurQTY FLOAT=0
							DECLARE	@BalPurQTY FLOAT=0
							DECLARE @BalSoldQTY FLOAT=0
							DECLARE @Balpurchase_Op_Qty FLOAT=0
							DECLARE @BalOpeningQTY FLOAT=0
							DECLARE	@Sold_Qty FLOAT=0
							DECLARE @tempID int = 0
							
							IF(@isIntradayCol=0)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and   Flag_Type ='Sold' AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=0  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
											IF (@COUNT > 0)
												BEGIN
													SELECT ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, holding_type,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* INTO #tempSoldValExists 
													FROM
													#MainOutputtable_1 
													WHERE script_name=@scriptname AND holding_type=@holding_type  AND isintradaycol=0 
													AND (consultant_name = CASE WHEN  @Consultant_Name <> '' then  @Consultant_Name ELSE consultant_name END)
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold IN('Sold')  and  Flag_Type ='Sold'  AND isintradaycol=0
													ORDER BY NameId

													DECLARE @R_Sold_COUNT INT=(SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty INT 
													
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															SET @str = @TransType
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists  ORDER BY Dup_pkid,NameId)
															
															SELECT TOP(1)	@Sold_Qty		= sold_qty,
																			@soldDate		= sold_date,
																			@soldRate		= sold_rate,
																			@soldBillNo		= sold_bill_no,
																			@Pkid			= Pkid

															FROM #tempSoldValExists 
															WHERE id  = @tempSaleID

															SET @purchase_Op_Qty = @qty
															IF(@TransType='Opening')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	opening_date = @dates,
																		opening_rate = @rate,
																		opening_qty  = CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSaleID   AND ISNULL(opening_qty,0) = 0 AND pkid = @pkid
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	purchase_date=@dates,
																		purchase_bill_no=@billno,
																		purchase_rate=@rate,
																		purchase_qty= CASE WHEN @Sold_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Sold_Qty END,
																		Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND ISNULL(purchase_qty,0)=0 AND pkid = @pkid
																END
															IF(@Sold_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET sold_qty=@purchase_Op_Qty 
																	WHERE Flag_Type_Sold='Sold' AND   id = @tempSaleID  AND pkid = @pkid
																END

															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND pkid = @pkid
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempSoldValExists )
															DECLARE @Balancedval   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Sold_Qty)

															IF(@Balancedval  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	SET @soldQty=ABS(@Balancedval) 
																	SET @prioritysId  =(SELECT MAX(ISNULL(@prioritysId,0)+1) FROM #MainOutputtable_1) 
																	
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,Consultant_code , Flag_Type,Flag_Type_Sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name)
																	VALUES(@Dup_pkid,@tempSaleID ,@Trans_No,@ScriptId,@Consultant_code , 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name)
																	
																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																		SET @Balancedval = 0
																		break;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
															
																	IF(@TransType='Opening')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,Consultant_code , Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId,@Consultant_code , 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name)
																		END
																	ELSE IF(@TransType='Bought')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,Consultant_code ,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId,@Consultant_code , 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name)
																		END
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 	
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																ENd
															ELSE IF(@Balancedval=0)
																BEGIN
																	break;
																END
															SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
															SET @qty=@Balancedval
														END
												

													DROP TABLE #tempSoldValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
													INSERT INTO #mainoutputtable_1 (Dup_pkid,id,Trans_No,ScriptCode,Consultant_code , prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name) 
													VALUES ( @Dup_pkid,@ID,@Trans_No,@ScriptId  ,@Consultant_code , @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name) 
												END
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split') AND ISNULL(sold_qty,0)=0  AND isintradaycol=0 AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
											
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, holding_type,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* 
													INTO #tempValExists 
													FROM
													#MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split') 
													AND (consultant_name = CASE WHEN  @ConsultantCode <> '' THEN  @Consultant_Name ELSE consultant_name END) 
													AND ISNULL(sold_qty,0) = 0  AND isintradaycol = 0 
													ORDER BY NameId 
													
													DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty int 
													 
													WHILE(@RCOUNT > 0 )
														BEGIN 
															SET @Sold_Qty= @qty
															SET @tempID = (SELECT TOP(1) id FROM #tempValExists  ORDER BY Dup_pkid)
															SET @str = (SELECT TOP(1) Flag_Type FROM #tempValExists WHERE id  = @tempID)
														
															IF(@str='Opening')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= opening_qty,
																					@openingDate	= opening_date,
																					@openingrate	= opening_rate,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID

																END
															ELSE IF(@str='Bought')
																BEGIN
																	SELECT	TOP(1)	@TempSoldQty	= purchase_qty,
																					@PurchaseDate	= purchase_date,
																					@Purchaserate	= purchase_rate,
																					@PurchaseBillNo = purchase_bill_no,
																					@Pkid			= Pkid
																	FROM #tempValExists 
																	WHERE id  = @tempID

																END
															IF(@Sold_Qty > 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	UPDATE #MainOutputtable_1  
																		SET	
																			opening_qty     = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							  END,
																			purchase_qty    = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							   END,
																			sold_date       = @dates,
																			sold_bill_no    = @billno,
																			sold_rate       = @rate,
																			sold_qty        = CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold  = 'Sold',
																			prioritys       = @prioritysId
																	WHERE  id = @tempID AND ISNULL(sold_qty,0)=0 AND pkid = @Pkid
																	SET @Balanceval = ABS(@Sold_Qty) - ABS(@TempSoldQty)
																END
															
															DELETE FROM #tempValExists WHERE id = @tempID AND pkid = @pkid
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempValExists )
															SET @RCOUNT = @RCOUNT - 1
															SET @qty = @Balanceval
															SET @Sold_Qty = @qty
													
															IF(@Balanceval  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  =(SELECT MAX(ISNULL(@prioritysId,0)+1) FROM #MainOutputtable_1)-- WHERE id=@tempID)

																	IF(@str='Opening')
																		BEGIN
																			SET @openingQty = ABS(@Balanceval) 
																			SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																			SET @prioritysId = ISNULL(@prioritysId,0)+1
																			
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,Consultant_code ,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@tempID,@Trans_No,@ScriptId,@Consultant_code , 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name)
																			UPDATE #MainOutputtable_1 SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempID

																			SET @prioritysId = ISNULL(@prioritysId,0)+1
															
																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId   
																			WHERE prioritys >= @prioritysId AND ID <> @tempID
																		END
																	ELSE 
																		BEGIN
																			SET @PurchaseQty = ABS(@Sold_Qty) 
																			SET @prioritysId  = (SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempID)
																			SET @prioritysId = ISNULL(@prioritysId,0)+1

																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,Consultant_code ,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name)
																			VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId,@Consultant_code , 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name)
																			UPDATE #MainOutputtable_1 SET prioritys=@prioritysId  WHERE prioritys > @prioritysId AND ID<>@tempID

																			UPDATE #MainOutputtable_1 
																			SET prioritys=@prioritysId    
																			WHERE prioritys >= @prioritysId AND ID <> @tempID
																		END
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(MAX),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(MAX),(SELECT ISNULL(MAX(pkid),1) FROM #MainOutputtable_1  )) END)  
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			where Dup_pkid >= @Dup_pkid  and ScriptCode<>@ScriptId
																		END
																		SET @Balanceval=0;
																	break;
																END
															ELSE IF(ISNULL(@Balanceval,0) > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE Pkid = @Pkid)
																	SET @Dup_pkid = (Select case when ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)

																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,Consultant_code ,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId,@Consultant_code , 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name)

																	UPDATE #MainOutputtable_1 
																	SET prioritys=@prioritysId+1  
																	WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
																	SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																	

																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 
																			SET Dup_pkid = Dup_pkid + 1 
																			WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																			FROM Fn_split(@Pkid, ',') ) 
																		END
																END
																ELSE IF(ISNULL(@Balanceval,0) =0)
																BEGIN
																	SET @Balanceval=0
																	BREAK;
																END
																 
															SET @qty = @Balanceval
														END
													 DROP TABLE #tempValExists
											END
											
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
													SET @prioritysId = ISNULL(@prioritysId,0)+1
													INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,Consultant_code ,   Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
													VALUES(@Dup_pkid,@ID,@Trans_No, @ScriptId,@Consultant_code , 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name)
												END
											
											SET @purchase_Op_Date  = ''
											SET @purchase_Op_Rate  = ''
											SET @purchase_Op_Qty   = ''
											SET @purchase_Op_Bill  = ''
										END
								END
							ELSE IF(@isIntradayCol=1)
								 BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and  Flag_Type ='Sold'  AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=1  AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
											IF (@COUNT > 0)
												BEGIN
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, holding_type,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* INTO #tempSoldValExists_intra_Bought 
													FROM
													#MainOutputtable_1 
													WHERE script_name=@scriptname AND holding_type=@holding_type AND isintradaycol=1 
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold IN('Sold')  and  Flag_Type ='Sold' 
													AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
													ORDER BY NameId

													DECLARE @R_Sold_COUNT_intra INT=(SELECT COUNT(*) FROM #tempSoldValExists_intra_Bought )
													DECLARE @Temppurchase_Op_Qty_intra int 
													
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID_intra int = (Select top(1) id from #tempSoldValExists_intra_Bought  ORDER BY Dup_pkid,NameId)
															SET @str=@TransType
															SET @Temppurchase_Op_Qty_intra=(SELECT TOP(1) sold_qty  FROM #tempSoldValExists_intra_Bought WHERE id  = @tempSaleID_intra )
															SELECT	@soldDate				= sold_date,
																	@soldRate				= sold_rate,
																	@soldBillNo				= sold_bill_no,
																	@pkid					= pkid
															FROM #tempSoldValExists_intra_Bought 
															WHERE id  = @tempSaleID_intra 

															--SET @Sold_Qty = @purchase_Op_Qty
															SET @purchase_Op_Qty = @qty
																IF(@TransType='Bought')
																	BEGIN
																		UPDATE #MainOutputtable_1  
																		SET	purchase_date=@dates,
																			purchase_bill_no=@billno,
																			purchase_rate=@rate,
																			purchase_qty= CASE WHEN @Temppurchase_Op_Qty_intra > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Temppurchase_Op_Qty_intra END,
																			Flag_Type='Bought'
																		WHERE  id = @tempSaleID_intra  AND pkid = @pkid
																	END
																ELSE
																	BEGIN
																		UPDATE #MainOutputtable_1  
																		SET	opening_date=@dates,
																			opening_rate=@rate,
																			opening_qty= CASE WHEN @Temppurchase_Op_Qty_intra > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Temppurchase_Op_Qty_intra END,
																			Flag_Type='Bought'
																		WHERE  id = @tempSaleID_intra  AND pkid = @pkid
																	END

																IF(@Temppurchase_Op_Qty > @purchase_Op_Qty )
																	BEGIN
																		UPDATE #MainOutputtable_1  
																		SET sold_qty=@purchase_Op_Qty 
																		WHERE Flag_Type_Sold='Sold' AND   id = @tempSaleID_intra  AND pkid = @pkid
																	END
																
																DELETE FROM #tempSoldValExists_intra_Bought  WHERE id = @tempSaleID_intra  AND pkid = @pkid
																SET @R_Sold_COUNT_intra  = @R_Sold_COUNT_intra  - 1
																SET @tablerowscount=(SELECT COUNT(*) FROM  #tempSoldValExists_intra_Bought )
																declare @Balancedval_intra   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Temppurchase_Op_Qty_intra)
																IF(@Balancedval_intra  < 0)
																	BEGIN
																		SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																		SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
																		SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
																		SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																		SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																		SET @Dup_pkid = @Dup_pkid + 1

																		SET @soldQty=ABS(@Balancedval_intra  ) 
																		SET @prioritysId  =(SELECT MAX(prioritys) FROM #MainOutputtable_1 )--WHERE id=@tempSale_ID )
																		SET @prioritysId = ISNULL(@prioritysId,0)+1

																		INSERT INTO #MainOutputtable_1(Dup_pkid,ID, Trans_No,ScriptCode,Consultant_code , Flag_Type, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_Name)
																		VALUES(@Dup_pkid,@tempSaleID_intra ,@Trans_No,@ScriptId,@Consultant_code , 'Opening',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval_intra),@soldRate,@isIntradayCol,@Consultant_Name)
																		
																		UPDATE #MainOutputtable_1 
																		SET prioritys = @prioritysId+1  
																		WHERE prioritys > @prioritysId AND ID<>@tempSaleID_intra 
																	
																		IF(@idcount>0)
																			BEGIN
																				UPDATE #MainOutputtable_1 
																				SET Dup_pkid = Dup_pkid + 1 
																				WHERE  Dup_pkid >= @Dup_pkid and   CONVERT(VARCHAR(200),pkid) NOT IN(SELECT value 
																		        FROM Fn_split(@Pkid, ',') ) 
																			END
																		BREAK;
																	END
																ELSE IF(@Balancedval_intra  > 0 AND @tablerowscount = 0) 
																	BEGIN
																		SET @Pkid = (SELECT ISNULL(MAX(ISNULL(pkid,0)),0) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)-- AND ID = @ID)
																		SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
																		SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
																		SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																		SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																		SET @Dup_pkid = @Dup_pkid + 1
																		SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)

																		IF(@TransType='Opening')
																			BEGIN
																				INSERT INTO #MainOutputtable_1(Dup_pkid ,ID,Trans_No,ScriptCode,Consultant_code ,  Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name)
																				VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId,@Consultant_code , 'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval_intra),@rate,@isIntradayCol,@Consultant_Name)
																			END
																		ELSE if(@TransType='Bought')
																			BEGIN
																				INSERT INTO #MainOutputtable_1(Dup_pkid ,ID,Trans_No,ScriptCode,Consultant_code ,  Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name)
																				VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId,@Consultant_code , 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval_intra)  ,@rate,@isIntradayCol,@Consultant_Name)

																				UPDATE #MainOutputtable_1 
																				SET prioritys=@prioritysId+1  
																				WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																				
																			END
																		SET  @Pkid =(SELECT CASE WHEN ISNULL(@Pkid,0) <> 0 THEN  @Pkid + ',' +   CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) ELSE CONVERT(VARCHAR(20),(SELECT MAX(pkid) FROM #MainOutputtable_1)) END)  
																		IF(@idcount>0)
																			BEGIN
																				UPDATE #MainOutputtable_1 
																				SET Dup_pkid = Dup_pkid + 1 
																				WHERE  Dup_pkid >= @Dup_pkid and   
																				CONVERT(VARCHAR(200),pkid) NOT IN ( SELECT value FROM Fn_split(@Pkid, ',') ) 
																			END
																	ENd
																	SET @qty=@Balancedval_intra
															END
													DROP TABLE #tempSoldValExists_intra_Bought
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
													 
													INSERT INTO #mainoutputtable_1 (Dup_pkid,id,Trans_No,ScriptCode,Consultant_code , prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name) 
													VALUES (@Dup_pkid, @ID,@Trans_No,@ScriptId,@Consultant_code , @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name) 
														 
												END
										END	

									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Enry Already if Purchase or Opening Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') AND ISNULL(sold_qty,0)=0  AND isintradaycol=1 AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END))
											IF (@COUNT > 0)
												BEGIN
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, holding_type,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* 
													INTO #tempValExists_intraBought 
													FROM
													#MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split','Transfer') 
													AND consultant_name=(CASE WHEN @ConsultantCode <>'' THEN @Consultant_Name ELSE consultant_name END)
													AND ISNULL(sold_qty,0)=0  AND isintradaycol=1 
													DECLARE @RCOUNT_intraBought INT=(SELECT COUNT(*) FROM #tempValExists_intraBought)
													DECLARE @TempSoldQty_intra int 
													SET @Sold_Qty=@qty
													WHILE(@RCOUNT_intraBought > 0)
														BEGIN 
															DECLARE @tempID_intraBought int = (Select top(1) id from #tempValExists_intraBought where isintradaycol=1 ORDER BY Dup_pkid)
															SET @str = (Select top(1) Flag_Type From #tempValExists_intraBought Where id  = @tempID_intraBought)
															 
															SET @TempSoldQty_intra=(SELECT TOP(1) purchase_qty FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought)
															SET @PurchaseDate=(SELECT TOP(1) purchase_date FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought)
															SET @Purchaserate=(SELECT TOP(1) purchase_rate FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought)
															SET @PurchaseBillNo=(SELECT TOP(1) purchase_bill_no FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought)
															SET @Sold_Qty= @qty
															SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempValExists_intraBought WHERE id  = @tempID_intraBought )	
																
															UPDATE #MainOutputtable_1  
																SET	
																	sold_date=@dates,
																	sold_bill_no=@billno,
																	sold_rate=@rate,
																	sold_qty= CASE WHEN @TempSoldQty_intra > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty_intra END,
																	Flag_Type_Sold='Sold' 
															WHERE  id = @tempID_intraBought and isnull(sold_qty,0)=0  AND pkid = @pkid
																
															IF(@TempSoldQty_intra > @Sold_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  SET purchase_qty=@Sold_Qty WHERE Flag_Type='Bought' AND   id = @tempID_intraBought AND pkid = @pkid
																END

															DELETE FROM #tempValExists_intraBought WHERE id = @tempID_intraBought AND pkid = @pkid
															SET @RCOUNT_intraBought = @RCOUNT_intraBought - 1
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempValExists_intraBought )
															declare @Balanceval_intraBought FLOAT = ABS(@Sold_Qty) - ABS(@TempSoldQty_intra)
															
															IF(@Balanceval_intraBought  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	
																	SET @PurchaseQty = ABS(@Sold_Qty) 
																	SET @prioritysId  = (SELECT MAX(ISNULL(@prioritysId,0)+1) FROM #MainOutputtable_1) 
																	 
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,Consultant_code ,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@tempID_intraBought,@Trans_No, @ScriptId,@Consultant_code ,'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval_intraBought)  ,@Purchaserate,@isIntradayCol,@Consultant_Name)
																	UPDATE #MainOutputtable_1 SET prioritys=@prioritysId  WHERE prioritys > @prioritysId AND ID<>@tempID_intraBought
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and ScriptCode<>@ScriptId
																		END
																	BREAK;
																END
															ELSE IF(@Balanceval_intraBought  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE ScriptCode = @ScriptId)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 THEN (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) ELSE @Dup_pkid END)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																
																	SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,Consultant_code ,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
																	VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId,@Consultant_code , 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval_intraBought)  ,@rate,@isIntradayCol,@Consultant_Name)
																
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and ScriptCode<>@ScriptId
																		END
																ENd
															
															SET @qty=@Balanceval_intraBought
														END
														

													DROP TABLE #tempValExists_intraBought
												END
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
													INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,Consultant_code ,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name)
													VALUES(@Dup_pkid,@ID, @Trans_No, @ScriptId,@Consultant_code ,'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name)
													 
												END
													SET @purchase_Op_Date=''
													SET @purchase_Op_Rate=''
													SET @purchase_Op_Qty=''
													SET @purchase_Op_Bill=''
										END
								END
							FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Consultant_code , @Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name 
						END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 
		IF(@IsIntraDay = 0 AND @short_Long_Term != 0  )
			BEGIN
				IF(@short_Long_Term = 1)  -- Long Term
					BEGIN

						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no, id,Trans_No, prioritys,ScriptCode,script_name ,Holding_Type,Consultant_code ,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name ,Holding_Type,Consultant_code ,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						 Round(ISNULL( CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
											WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						0,
						 Round(ISNULL( CASE	WHEN isintradaycol = 0 and  opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
											WHEN isintradaycol = 0 and  purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
												THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
											ELSE 0.0	
										END,0) ,4),
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort ,isintradaycol
						FROM #mainoutputtable_1 
						WHERE ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
									(
										 
									       DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME,opening_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365 
									)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									(
										DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME, purchase_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) > 365
									)
								)
							)
							order by NameId
					END

				ELSE If(@short_Long_Term = 2)  -- Short Term
					BEGIN

						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name ,Holding_Type,Consultant_code ,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss , closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name ,Holding_Type,Consultant_code ,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount , 
						Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4) as gain_loss,
						
						closing_qty ,closing_rate ,closing_value ,
						Round(ISNULL(
								CASE	WHEN isintradaycol = 0 and  opening_date IS NOT NULL AND sold_date IS NOT NULL   --openings
											THEN  sold_rate * sold_qty - opening_rate*opening_qty 
										WHEN isintradaycol = 0 and  purchase_date IS NOT NULL AND sold_date IS NOT NULL   --purchase
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  
								END 
						,0),4),
						0,
						0,
						0,
						0,consultant_name,nse_rate,bse_rate,1 sort,isintradaycol 
						FROM #mainoutputtable_1 
						WHERE  ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						AND 
							(
								(ISNULL(opening_date,'') !=''  AND 
										(		
											DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME,opening_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) < 365 
										)
								)
							   OR 
								(ISNULL(purchase_date,'') !=''  AND
									  (		
											DATEDIFF(DAY,CONVERT(VARCHAR,CONVERT(DATETIME, purchase_date,101)),CONVERT(VARCHAR,CONVERT(DATETIME,ISNULL(sold_date,0),101))) < 365
									  )
								)
							)
							order by NameId
					END

				ELSE If(@short_Long_Term = 4)  -- Short Term + Long Term
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name ,Holding_Type,Consultant_code ,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

						SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name ,Holding_Type,Consultant_code ,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365   --short term openings
									THEN  sold_rate * sold_qty - opening_rate * opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term purchase
									THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						(CASE  WHEN  isintradaycol = 0 and ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between  1 AND 365 ) OR
								    (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) between   1 AND 365 )) 
							  THEN  

								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						(CASE WHEN isintradaycol = 0 and ((ISNULL(opening_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,opening_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365) OR
								   (ISNULL(purchase_date,'') !='' AND (ISNULL(sold_date,''))  !='' AND (DATEDIFF(DAY,CONVERT(DATETIME,purchase_date,101),CONVERT(DATETIME,ISNULL(sold_date,0),101))) >= 365))  
							  THEN
								Round(ISNULL(
												CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365   --short term openings
														THEN  sold_rate * sold_qty - opening_rate * opening_qty
														WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term purchase
														THEN  sold_rate * sold_qty - purchase_rate * purchase_qty  -- --long term
														ELSE
												CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- Openings
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
														WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- purchase
														THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
												
												ELSE 0.0
										END
									END,0) ,4)
								ELSE 0 END),
						0,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol 
						FROM #mainoutputtable_1 
						WHERE  ISNULL(closing_qty,0) = 0  AND ISNULL(isintradaycol,0)=0
						order by NameId
					END
			END

		ELSE IF(@short_Long_Term = 3 AND @IsIntraDay = 1 )  -- Only Speculation
			BEGIN
				INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no, id,Trans_No, prioritys,ScriptCode,script_name ,Holding_Type,Consultant_code ,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

				SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,
							case WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
								 WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
						ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name ,Holding_Type,Consultant_code ,opening_date,
				ISNULL(opening_qty,0) ,ISNULL(opening_Rate,0),ISNULL(opening_amount,0),purchase_date,ISNULL(purchase_bill_no,0),
				ISNULL(purchase_qty,0) ,ISNULL(purchase_rate,0) ,ISNULL(purchase_amount,0) ,sold_date ,sold_bill_no ,isnull(sold_qty,0) ,
				ISNULL(sold_rate,0),ISNULL(sold_amount,0) , 
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4) as gain_loss,
				closing_qty ,closing_rate ,closing_value ,
				0,
				0,
				Round(ISNULL(
								CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - opening_rate*opening_qty
										WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL 
											THEN  sold_rate * sold_qty - purchase_rate*purchase_qty
								END 
						,0),4),
				0,
				0,consultant_name,nse_rate,bse_rate,1 sort,isintradaycol 
				FROM #mainoutputtable_1 
				WHERE  (ISNULL(closing_qty,0) = 0)  AND (ISNULL(isintradaycol,0)=1) AND (ISNULL(purchase_qty,0)! = 0 AND  ISNULL(sold_qty,0) ! = 0) 
				order by NameId
			END

		ELSE
			BEGIN
				IF(@Investmenttype=2)
					BEGIN
						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name,Holding_Type,Consultant_code ,flag_script_name,flag_Holding_Type,
						opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

						SELECT
						ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,dup_pkid,case when CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) else CONVERT(DATE,purchase_date,103) END,prioritys DESC, sold_date DESC ) AS NameId,
						opening_bill_no,
						id,Trans_No, prioritys,ScriptCode,script_name,'Empty', flag_script_name,flag_Holding_Type,Consultant_code ,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						CASE WHEN isintradaycol = 0 and ((opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365)) --short term for purchase
						THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
						
						CASE WHEN  isintradaycol = 0 and ((opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365)) --short term for purchase
						THEN  
								CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
											THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
										WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
											THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
										ELSE 0.0
								END
						ELSE 0.0 END,
						CASE WHEN   isintradaycol = 1 and (purchase_bill_no = sold_bill_no) 
						THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
						0,
						0,
						consultant_name,nse_rate,bse_rate,1 sort,isintradaycol 
						FROM #mainoutputtable_1 
						order by NameId
					
					END
				ELSE
					BEGIN
					
						
						INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name,Holding_Type,Consultant_code ,flag_script_name,flag_Holding_Type,
						opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,gain_loss,closing_qty ,closing_rate ,closing_value ,
						short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol )

						SELECT 
						ROW_NUMBER ( ) OVER (ORDER BY   holding_type,ScriptCode,Pkid,
							case	WHEN  CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) 
									WHEN  CONVERT(DATE,purchase_date,101) <> null then CONVERT(DATE,purchase_date,101) 
									ELSE  CONVERT(DATE,sold_date,101) END desc)  AS NameId,
						opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name ,Holding_Type, Consultant_code ,flag_script_name,flag_Holding_Type,opening_date,
						opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
						purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
						sold_rate,sold_amount ,
						 Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
						closing_qty ,closing_rate ,closing_value ,
						CASE	WHEN isintradaycol = 0 AND  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365)     -- short term for openings
									THEN  ISNULL(sold_rate ,0)* ISNULL(sold_qty ,0)- ISNULL(opening_rate,0)*ISNULL(opening_qty ,0)
								WHEN isintradaycol = 0 AND (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365)  -- short term for purchase
									THEN  ISNULL(sold_rate ,0)* ISNULL(sold_qty ,0)- ISNULL(purchase_rate,0)*ISNULL(purchase_qty ,0)
								ELSE 0.0 END,

						CASE WHEN  isintradaycol = 0 and ((opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --short term for openings
									OR
									(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365)) --short term for purchase
							THEN  
								CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
											THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
										WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
											THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
										ELSE 0.0
								END
							ELSE 0.0 
										END,
							CASE WHEN  isintradaycol = 1 AND (purchase_bill_no = sold_bill_no) 
							THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
							0,0,
							consultant_name,nse_rate,bse_rate,1 sort,isintradaycol 
							FROM #mainoutputtable_1 
							ORDER BY NameId
					END
			END
		UPDATE #mainoutputtable_1_Final SET prioritys=0
		DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
		UPDATE #mainoutputtable_1_Final
		SET prioritys  = @i , @i = @i + 1
	  
	  --Select * from #mainoutputtable_1_Final

		IF(@OUTPUT_Flag='Details')
			BEGIN
				IF(@Investmenttype !=2)
				BEGIN
					IF(@ConsultantCode <> '')
						BEGIN
						 
							SELECT id,prioritys,ScriptCode,script_name 'Script Name',Holding_Type,Consultant_code ,opening_bill_no,
							CONVERT(DATE, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
							CONVERT(DATE, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',purchase_rate 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
							CONVERT(DATE, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
							ISNULL(gain_loss,0) 'Gain/Loss',ISNULL(gain,0) 'Gain',ISNULL(loss,0) 'Loss',ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
							ISNULL(short_term,0)short_term,
							ISNULL(long_term,0)long_term,
							ISNULL(speculation,0)speculation,
							CASE WHEN isintradaycol=1 and gain!=0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
							CASE WHEN isintradaycol=1 and loss!=0  THEN ISNULL(loss ,0) ELSE '' END loss_speculation,consultant_name,nse_rate,bse_rate,isintradaycol,1 sort 
							FROM #mainoutputtable_1_Final
							WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
							ORDER By  consultant_name,Holding_Type,script_name
						END
					ELSE
						BEGIN
							SELECT id,prioritys, ScriptCode,script_name 'Script Name',Holding_Type,  Consultant_code ,opening_bill_no,
							CONVERT(date, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
							CONVERT(date, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
							CONVERT(date, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',
							sold_rate 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',ISNULL(closing_qty,0) 'Closing Qty',closing_rate 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
							ISNULL(short_term,0)short_term,
							ISNULL(long_term,0)long_term,
							ISNULL(speculation,0)speculation,
				
							CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE 0 END gain_speculation,
							CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE 0 END loss_speculation,
							'' consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),ISNULL(isintradaycol,0),1 sort 
							FROM #mainoutputtable_1_Final
							WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
							ORDER By  Holding_Type,script_name
						END
					END
				ELSE

				IF(@ConsultantCode <> '')
					BEGIN
						SELECT id,prioritys,ScriptCode,script_name 'Script Name',Holding_Type, Consultant_code ,opening_bill_no,
						CONVERT(date, opening_date,101) 'Opening Date',opening_qty 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(date, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(date, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',ISNULL(gain,0) 'Gain',ISNULL(loss,0) 'Loss',ISNULL(closing_qty,0) 'Closing Qty',ISNULL(closing_rate,0) 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 and gain!=0 THEN ISNULL(gain ,0) ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 and loss!=0  THEN ISNULL(loss ,0) ELSE '' END loss_speculation,consultant_name,
						ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,isintradaycol,1 sort 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
						ORDER By consultant_name,script_name
					END
				ELSE
					BEGIN
						SELECT id,prioritys, ScriptCode,script_name 'Script Name',Holding_Type, Consultant_code ,opening_bill_no,
						CONVERT(date, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',opening_Rate 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(date, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(date, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',
						sold_rate 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',ISNULL(gain_loss,0) 'Gain/Loss',CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS 'Gain',CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END  AS  'Loss',ISNULL(closing_qty,0) 'Closing Qty',closing_rate 'Closing Rate',ISNULL(closing_value,0) 'Closing Value',
						ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						'' consultant_name,ISNULL(nse_rate,0),ISNULL(bse_rate,0),ISNULL(isintradaycol,0),1 sort 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
						ORDER BY  Holding_Type,script_name
					END
			END

		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
				SELECT  0 id ,  0 prioritys, script_name 'Script Name', '' Holding_Type,  
				NULL 'Opening Date', SUM(ISNULL(opening_qty,0)) 'Opening Qty',   ISNULL((ISNULL(SUM(ISNULL(opening_amount,0)),0)  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)  'Opening Rate', SUM(ISNULL(opening_amount,0)) 'Opening Amount',
				NULL 'Purchase Date','' 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty',   ISNULL((ISNULL(SUM(ISNULL(purchase_amount,0)),0)  / SUM(NULLIF(ISNULL(purchase_qty,0),0))),0)   'Purchase Rate', SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
				NULL 'Sold Date', '' 'Sold BillNo', SUM(ISNULL(sold_qty,0)) 'Sold Qty', ISNULL((ISNULL(SUM(ISNULL(sold_amount,0)),0) / NULLIF (SUM(ISNULL(sold_qty,0)),0)),0)'Sold Rate', SUM(ISNULL(sold_amount,0)) 'Sold Amount', 
				SUM(ISNULL(gain_loss ,0)) 'Gain/Loss', SUM(ISNULL(gain,0))  'Gain', SUM(ISNULL(loss,0))  'Loss',
				SUM(ISNULL(closing_qty,0))  'Closing Qty', ISNULL((ISNULL(SUM(ISNULL(closing_value,0)),0) / NULLIF(SUM(ISNULL(closing_qty,0)),0)),0)   'Closing Rate', SUM(ISNULL(closing_value,0))  'Closing Value', SUM(ISNULL(short_term,0))  short_term, SUM(ISNULL(long_term,0))  long_term,
				SUM(ISNULL(speculation,0))speculation, SUM(ISNULL(gain_speculation,0))gain_speculation, SUM(ISNULL(loss_speculation,0))loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
				FROM
					(
						SELECT MAX(id+0)id ,MAX (prioritys+0) prioritys, script_name  ,'' Holding_Type,
						NULL 'Opening Date',SUM(opening_qty) 'Opening_Qty',sum(opening_rate) opening_rate ,SUM(opening_amount) 'Opening_Amount',
						NULL 'Purchase Date',purchase_bill_no,SUM(purchase_qty) 'Purchase_Qty', SUM(purchase_rate) purchase_rate,SUM(purchase_amount) 'Purchase_Amount',
						NULL 'Sold Date',sold_bill_no ,SUM(sold_qty) 'Sold_Qty', SUM(sold_rate)sold_rate  , SUM(sold_amount) 'Sold_Amount',SUM(gain_loss) 'Gain_Loss',SUM(gain) 'Gain',SUM(loss) 'Loss',
						SUM(closing_qty) 'Closing_Qty',0 'Closing_Rate',SUM(closing_value) 'Closing_Value',SUM(short_term) short_term,SUM(long_term) long_term,
						SUM(speculation) speculation,SUM(gain_speculation) gain_speculation,SUM(loss_speculation) loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
						FROM #mainoutputtable_1_Final 
						GROUP BY script_name,Holding_Type,purchase_bill_no,sold_bill_no 
					)a
				GROUP BY  script_name  
				ORDER BY  Holding_Type,script_name,id
			END

		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN
				SELECT  prioritys ,Trans_No,id ,  ScriptCode,script_name ,Holding_Type,  Consultant_code , flag_script_name,flag_Holding_Type,
				CONVERT(DATE, opening_date,101),ISNULL(opening_qty ,0)opening_qty ,ISNULL(opening_Rate,0)opening_Rate,ISNULL(opening_amount,0)opening_amount,
				CONVERT(DATE, purchase_date,101),purchase_bill_no,ISNULL(purchase_qty ,0)purchase_qty ,ISNULL(purchase_rate ,0)purchase_rate ,ISNULL(purchase_amount ,0)purchase_amount ,
				CONVERT(DATE, sold_date,101) ,sold_bill_no ,ISNULL(sold_qty ,0)sold_qty ,ISNULL(sold_rate,0)sold_rate,ISNULL(sold_amount ,0)sold_amount ,
				ISNULL(gain_loss ,0),ISNULL(gain ,0),ISNULL(loss,0),ISNULL(closing_qty ,0),ISNULL(closing_rate ,0),ISNULL(closing_value ,0),
				ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
				ISNULL(gain_speculation,0)gain_speculation,ISNULL(loss_speculation,0)loss_speculation,consultant_name,
				ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol
				FROM #mainoutputtable_1_Final
				order by prioritys
			END

		DROP TABLE #mainoutputtable_1 
	 
		DROP TABLE #alldata 
		
  END  












































GO
/****** Object:  StoredProcedure [dbo].[proc_WithTaxStockholding_Equity_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_WithTaxStockholding_Equity_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_WithTaxStockholding_Equity_Summary] AS' 
END
GO
-- Execute  proc_WithTaxStockholding_Equity_Summary    0,0,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','', '0' ,'0',0,1,0
ALTER PROCEDURE [dbo].[proc_WithTaxStockholding_Equity_Summary]   
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,
@RecordOnlyhavingClosingbalanceZero as bit,@WithActualAvgRate as bit, @DateWiseClosinStock as bit)
AS
BEGIN
SET NOCOUNT ON;
		CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
           prioritys INT,
		   Trans_No VARCHAR(50), 
		   id INT,
		   script_Code  VARCHAR(50),
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200),
		   consultant_Code  VARCHAR(200),
		   flag_script_name  VARCHAR(500),
		   flag_holding_type VARCHAR(200),
           opening_date VARCHAR(50),opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
           purchase_date VARCHAR(50),purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
           sold_date VARCHAR(50),sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   Other_amt FLOAT DEFAULT 0,
		   ServTax_Amt FLOAT DEFAULT 0,
		   Stt_amt FLOAT DEFAULT 0,
		   sort   VARCHAR(5),
		   isintradaycol  INT 
        ) 

		
		IF(@ConsultantCode = '0')	
			BEGIN
						
				SELECT DISTINCT p.member_code,p.year_code,
					STUFF((	SELECT distinct ',' + p1.Consultant_Code
							FROM Mst_Consultant p1
							FOR XML PATH(''), TYPE
							).value('.', 'NVARCHAR(MAX)')
					,1,1,'') ConsultantCode
				into #temoConsultant
				FROM Mst_Consultant p

				SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant WHERE member_code = @memcode AND year_code = @yearcode)
				DROP table #temoConsultant
			END

		Insert into #mainoutputtable_1_Final_Summary
		EXEC proc_WithTaxStockholding_Equity   @status,@Investmenttype,@Ac_Type,@memcode,@yearcode,@Fromdate,@Todate,@ScriptCode,@ConsultantCode,@BSE_NSE_Code,@Is_BFCF,@IsIntraDay,@short_Long_Term,'ALLData'
	 
	
		SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
		T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
		T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
		T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
		T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
		T1.consultant_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt ,
		
	   ISNULL(Dr.BSE_Rate,0)  AS 'bse_rate', /**/
		ISNULL(Dr.BSE_Rate,0) AS 'nse_rate' /**/
		  
		INTO #alldata_Summary 
		FROM #mainoutputtable_1_Final_Summary  T1
		LEFT JOIN BrokerBill T2 ON T1.Trans_No=T2.Trans_no
			LEFT JOIN DailyRate DR ON DR.Script_Code = T1.script_Code  and Dr.Trans_Dt = @Todate /**/
		
		TRUNCATE TABLE #mainoutputtable_1_Final_Summary
		
		INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,
		nse_rate,bse_rate,
		sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt) 

		SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,
		Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 
		FROM #alldata_Summary  
		GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,nse_rate,bse_rate,sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 

	

		IF(@RecordOnlyhavingClosingbalanceZero = 0)
			BEGIn
				IF((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1) OR (@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1))
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT  MAX(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', SUM(gain_loss) AS  'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0 
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', 
								ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', SUM(gain_loss) AS  'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								ISNULL(bse_rate ,0) AS  'BSERATE',
								ISNULL(bse_rate,0) * SUM(ISNULL(closing_qty,0))  AS  'BSE_Valuation',
								CASE WHEN ISNULL(bse_rate,0) = 0 THEn 0 ELSE ISNULL(bse_rate,0) * SUM(ISNULL(closing_qty,0)) - SUM(ISNULL(closing_value,0)) END  AS  'BSE_UnRealizedGainLoss',
								ISNULL(nse_rate,0) AS  'NSERATE',
								ISNULL(nse_rate,0) * SUM(ISNULL(closing_qty,0)) AS  'NSE_Valuation',
								CASE WHEN ISNULL(nse_rate,0) = 0 THEN 0 ELSE  ISNULL(nse_rate,0) * SUM(ISNULL(closing_qty,0)) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
										END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
										END AS 'Value After Profit/Loss',

							 
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
							END
					END
				ELSE IF((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0))
					BEGIN
						IF(@ConsultantCode <> '')
							BEGIN
								SELECT  MAX(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', SUM(gain_loss) AS  'Gain/Loss',
								''  'Closing Date',
								bse_rate AS 'BSERATE',
								bse_rate * SUM(closing_qty) AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS 'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0 
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', 
								ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', SUM(gain_loss) AS  'Gain/Loss',
								''  'Closing Date',
								ISNULL(bse_rate ,0) AS  'BSERATE',
								ISNULL(bse_rate,0) * SUM(ISNULL(closing_qty,0))  AS  'BSE_Valuation',
								CASE WHEN ISNULL(bse_rate,0) = 0 THEn 0 ELSE ISNULL(bse_rate,0) * SUM(ISNULL(closing_qty,0)) - SUM(ISNULL(closing_value,0)) END  AS  'BSE_UnRealizedGainLoss',
								ISNULL(nse_rate,0) AS  'NSERATE',
								ISNULL(nse_rate,0) * SUM(ISNULL(closing_qty,0)) AS  'NSE_Valuation',
								CASE WHEN ISNULL(nse_rate,0) = 0 THEN 0 ELSE  ISNULL(nse_rate,0) * SUM(ISNULL(closing_qty,0)) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
										END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
										END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT   max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(gain_loss) AS  'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(ISNULL(closing_value,0)),2) AS 'Closing Value',SUM(ISNULL(closing_qty,0)) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								ISNULL(bse_rate ,0) AS  'BSERATE',
								ISNULL(bse_rate,0) * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN ISNULL(bse_rate,0) = 0 THEn 0 ELSE ISNULL(bse_rate,0) * SUM(ISNULL(closing_qty,0))  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								ISNULL(nse_rate,0) AS  'NSERATE',
								ISNULL(nse_rate,0) * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN ISNULL(nse_rate,0) = 0 THEN 0 ELSE  ISNULL(nse_rate,0) * SUM(ISNULL(closing_qty,0)) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					END
			END
		ELSE IF(@RecordOnlyhavingClosingbalanceZero = 1)
			BEGIN
				IF ((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1) OR (@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1))
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(ISNULL(gain_loss,0)),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END AS  'Closing Date',
								ISNULL(bse_rate,0)  AS  'BSERATE',
								ISNULL(bse_rate,0) * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN ISNULL(bse_rate,0) = 0 THEn 0 ELSE ISNULL(bse_rate,0) * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								ISNULL(nse_rate,0) AS  'NSERATE',
								ISNULL(nse_rate,0) * SUM(ISNULL(closing_qty,0)) AS  'NSE_Valuation',
								CASE WHEN ISNULL(nse_rate,0)=0 THEN 0 ELSE  ISNULL(nse_rate,0) * SUM(ISNULL(closing_qty,0)) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(ISNULL(gain_loss,0)),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								ISNULL(bse_rate,0)  AS  'BSERATE',
								ISNULL(bse_rate,0) * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN ISNULL(bse_rate,0) = 0 THEn 0 ELSE ISNULL(bse_rate,0) * SUM(ISNULL(closing_qty,0))  - SUM(ISNULL(closing_value,0)) END  AS  'BSE_UnRealizedGainLoss',
								ISNULL(nse_rate,0) AS  'NSERATE',
								ISNULL(nse_rate,0) * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN ISNULL(nse_rate,0)=0 THEN 0 ELSE  ISNULL(nse_rate,0) * SUM(ISNULL(closing_qty,0)) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss', ''  consultant_name
								 
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
							END
					END
				ELSE IF ((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0))
					BEGIN

						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(ISNULL(gain_loss,0)),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								'' AS  'Closing Date',
								ISNULL(bse_rate,0)  AS  'BSERATE',
								ISNULL(bse_rate,0) * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN ISNULL(bse_rate,0) = 0 THEn 0 ELSE ISNULL(bse_rate,0) * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								ISNULL(nse_rate,0) AS  'NSERATE',
								ISNULL(nse_rate,0) * SUM(ISNULL(closing_qty,0)) AS  'NSE_Valuation',
								CASE WHEN ISNULL(nse_rate,0)=0 THEN 0 ELSE  ISNULL(nse_rate,0) * SUM(ISNULL(closing_qty,0)) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate  
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(ISNULL(gain_loss,0)),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								''  'Closing Date',
								ISNULL(bse_rate,0)  AS  'BSERATE',
								ISNULL(bse_rate,0) * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN ISNULL(bse_rate,0) = 0 THEn 0 ELSE ISNULL(bse_rate,0) * SUM(ISNULL(closing_qty,0))  - SUM(ISNULL(closing_value,0)) END  AS  'BSE_UnRealizedGainLoss',
								ISNULL(nse_rate,0) AS  'NSERATE',
								ISNULL(nse_rate,0) * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN ISNULL(nse_rate,0)=0 THEN 0 ELSE  ISNULL(nse_rate,0) * SUM(ISNULL(closing_qty,0)) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss', ''  consultant_name
								 
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate  
								 
								HAVING SUM(closing_qty) = 0
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(ISNULL(gain_loss,0)),4) as 'Gain/Loss','' AS 'BSE RATE',SUM(ISNULL(gain_loss,0)) AS  'Gain/Loss',
								ISNULL(bse_rate,0)  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								ISNULL(bse_rate,0) * SUM(ISNULL(closing_qty,0))  AS  'BSE_Valuation',
								CASE WHEN ISNULL(bse_rate,0) = 0 THEn 0 ELSE ISNULL(bse_rate,0) * SUM(ISNULL(closing_qty,0))  - SUM(ISNULL(closing_value,0)) END  AS  'BSE_UnRealizedGainLoss',
								ISNULL(nse_rate,0) AS  'NSERATE',
								ISNULL(nse_rate,0) * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN ISNULL(nse_rate,0)=0 THEN 0 ELSE  ISNULL(nse_rate,0) * SUM(ISNULL(closing_qty,0)) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								
								SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name

							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(ISNULL(gain_loss,0)),4) as 'Gain/Loss','' AS 'BSE RATE',SUM(ISNULL(gain_loss,0)) AS  'Gain/Loss',
								ISNULL(bse_rate ,0) AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								ISNULL(bse_rate,0) * SUM(ISNULL(closing_qty,0))  AS  'BSE_Valuation',
								CASE WHEN ISNULL(bse_rate,0) = 0 THEn 0 ELSE ISNULL(bse_rate,0) * SUM(ISNULL(closing_qty,0))  - SUM(ISNULL(closing_value,0)) END  AS  'BSE_UnRealizedGainLoss',
								ISNULL(nse_rate,0) AS  'NSERATE',
								ISNULL(nse_rate,0) * SUM(ISNULL(closing_qty,0)) AS  'NSE_Valuation',
								CASE WHEN ISNULL(nse_rate,0)=0 THEN 0 ELSE  ISNULL(nse_rate,0) * SUM(ISNULL(closing_qty,0)) - SUM(ISNULL(closing_value,0)) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
									0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) +  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
									ELSE
								CASE WHEN 
										SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) -  ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
									0 END 
									END AS 'Value After Profit/Loss',
								0 Other_amt,'' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) = 0
							END
					END
			END
			DROP TABLE #alldata_Summary
			
END
































GO
/****** Object:  StoredProcedure [dbo].[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency] AS' 
END
GO
--[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency]  0,1,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-12-18 03:50:37:50','','','','1', '0' ,'0','AllData' 
ALTER PROCEDURE [dbo].[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency] 
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate VARCHAR(30),@Todate VARCHAR(30), 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,@OUTPUT_Flag VARCHAR(MAX))
AS  
  BEGIN 
  SET NOCOUNT ON;
		CREATE TABLE #MainOutputtable_1
        ( 
		   pkid INT identity(1,1),
		   Dup_pkid int, 
           Trans_No VARCHAR(20),
		   id INT,
		   prioritys INT,
		   Trans_Type  VARCHAR(50), 
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(10),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name  VARCHAR(500),
		   flag_holding_type VARCHAR(200), 
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(10),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount AS( [opening_qty] * [opening_rate] ), 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount AS( purchase_qty * purchase_rate ), 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount AS ( sold_qty * sold_rate ), 
		   gain_loss float,
           
		   closing_qty AS (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0))=0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty] ,0)+ ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0)) END ), 

           closing_rate  AS 
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END),
		   closing_value AS
							(CASE WHEN (ISNULL([opening_qty],0)  > ISNULL([sold_qty],0)) AND  ((ISNULL([opening_qty],0)) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([opening_rate],0) ELSE
							 CASE WHEN (ISNULL([purchase_qty],0) > ISNULL([sold_qty],0)) AND  ((ISNULL([purchase_qty],0)) - (ISNULL([sold_qty],0))) != 0  THEN ISNULL(purchase_rate,0)ELSE
							 CASE WHEN (ISNULL([sold_qty],0)  > ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) AND  ((ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) ) -  (ISNULL([sold_qty],0))) != 0  THEN ISNULL([Sold_rate],0)  
							 ELSE 0 END END END)
							 *
							 (CASE WHEN ISNULL([sold_qty],0) > 0 and (ISNULL([opening_qty],0) + ISNULL([purchase_qty],0)) = 0 THEN (-ISNULL([sold_qty],0)) ELSE ( ISNULL([opening_qty],0) + ISNULL([purchase_qty],0) )-(ISNULL([sold_qty],0))
							  END ),
		   
		   short_term FLOAT DEFAULT 0,
		   long_term  FLOAT DEFAULT 0,
           speculation  FLOAT DEFAULT 0,
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(20) ,
		   ScriptCode VARCHAR(50),
		   Strike_Price float DEFAULT 0,
		   OptionType VARCHAR(100),
		   Last_Date VARCHAR(100) 
        )  

		CREATE TABLE #mainoutputtable_1_Final
        ( 
		   Dup_pkid int,
		   OrderBy varchar(100),
           Trans_No VARCHAR(20),
		   id INT,prioritys INT   ,
		   Split_Type VARCHAR(50), 
		   Flag_Type VARCHAR(10),
		   Flag_Type_Sold VARCHAR(10),
		   flag_script_name  VARCHAR(500),
		   flag_holding_type VARCHAR(200), 
		   script_name  VARCHAR(500),
		   holding_type VARCHAR(200), 
		   opening_bill_no VARCHAR(10),		    
           opening_date DATETIME,
		   opening_qty  FLOAT DEFAULT 0,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date DATETIME,
		   purchase_bill_no VARCHAR(100),
		   purchase_qty FLOAT DEFAULT 0,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date DATETIME,
		   sold_bill_no VARCHAR(100),
		   sold_qty FLOAT DEFAULT 0,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain as CASE WHEN (ISNULL(gain_loss,0)) > 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   loss as CASE WHEN (ISNULL(gain_loss,0)) < 0 THEN ISNULL(gain_loss,0) ELSE 0 END,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   dayscount FLOAT DEFAULT 0,
		   isintradaycol INT,
		   [type] VARCHAR(20),
		   sort   VARCHAR(5),
		   ScriptCode VARCHAR(50) ,
		   Strike_Price float DEFAULT 0,
		   OptionType VARCHAR(100),
		   Last_Date VARCHAR(100) 
        ) 
		DECLARE @StartYearDate varchar(20) = '01/04/'+ (Select SUBSTRING(@yearcode ,3,4))  
		SET @StartYearDate = CONVERT(VARCHAR(10),@StartYearDate,101)
		DECLARE @holding_types VARCHAR(200),@Flagtype VARCHAR(10),@dates VARCHAR(20),@qty INT,@rate FLOAT,@amount FLOAT,@ID INT,@isIntradayCol_Sold INT,@TransType VARCHAR(20)
		DECLARE @showIntraday INT  
		DECLARE @tablerowscount INT
      IF(@status = 0) 
			BEGIN
				DECLARE @holding_type VARCHAR(100),@scriptcd VARCHAR(100),@billno VARCHAR(100),@scriptname VARCHAR(100),
				@openingDate DATETIME,@openingRate FLOAT,@openingQty INT,@openingAmount FLOAT,
				@purchaseDate DATETIME,@PurchaseBillNo  VARCHAR(50),@purchaseRate FLOAT,@purchaseQty INT,@purchaseAmount FLOAT,
				@soldDate DATETIME,@soldBillNo  VARCHAR(50),@soldRate FLOAT,@soldQty INT,@soldAmount FLOAT,
				@purchaseScriptId VARCHAR(50),@Consultant_Name  VARCHAR(100), 
				@SoldScriptId VARCHAR(50),@pendingSoldDate VARCHAR(50),@pendingSoldBillNo VARCHAR(10),@pendingSoldQty FLOAT,@pendingSoldRate FLOAT,@PurchaseIntraFlag VARCHAR(100),@SaleIntraFlag VARCHAR(10) ,
				@Strike_Price FLOAT,@OptionType VARCHAR(50),@Last_Date VARCHAR(50)
				DECLARE @TransTypes VARCHAR(200),@Trans_No VARCHAR(20),@ScriptId VARCHAR(50),@Dup_pkid int, @Pkid int,@idcount int   

				CREATE TABLE #SCriptCodes
				(
					ScriptCode varchar(MAX)
				)

				IF(@ScriptCode != '')
					INSERT INTO #SCriptCodes SELECT value FROM Fn_split(@ScriptCode, ',') 
				ELSE 
					INSERT INTO #SCriptCodes select Script_Code from mst_script 

				CREATE TABLE #ConsultantCodes
				(
					ConsultantCodes varchar(MAX)
				)
				
				IF(@ConsultantCode = '0')
					BEGIN
						SELECT DISTINCT p.member_code,p.year_code,
							STUFF((	SELECT distinct ',' + p1.Consultant_Code
									FROM Mst_Consultant p1
									FOR XML PATH(''), TYPE
									).value('.', 'NVARCHAR(MAX)')
							,1,1,'') ConsultantCode
						into #temoConsultant
						FROM Mst_Consultant p

						SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant)--xWHERE member_code = @memcode AND year_code = @yearcode)
						DROP table #temoConsultant
					END
				 
				IF(@ConsultantCode != '')
					INSERT INTO #ConsultantCodes SELECT value FROM Fn_split(@ConsultantCode, ',') 
				ELSE 
					INSERT INTO #ConsultantCodes select Consultant_Code from Mst_Consultant
				
				SELECT  ROW_NUMBER ( ) OVER (ORDER BY t.script_code, t.trans_dt ) AS NameId,
				t.Trans_No,t.Sr_No,t.Bill_no,t.Trans_Dt,t.TransType,t.Ac_Type,t.Script_Code,t.Last_Date,t.Qty,t.Exp_Rate,
						t.Member_code,t.YearCode,t.Consultant_code,t.isFNOBill,t.Strike_Price,t.OptionType,t.isIntraDay, t.FrmNm,t.ID,
						Ms.bse_code,Ms.nse_code,
		
						CASE WHEN @Investmenttype=2 then  ms.script_name 
							ELSE
							Ms.script_name 
							+ '/' +   CONVERT(VARCHAR(10),t.Last_Date,101) 
							+ CASE WHEN ISNULL(t.Strike_Price,'') != '' THEN  '/' + CONVERT(VARCHAR(10),t.Strike_Price) ELSE '' END
							+ CASE WHEN ISNULL(t.OptionType,'')   != '' THEN  '/' + CONVERT(VARCHAR(10),t.OptionType) ELSE '' 
							END	END script_name,
						'' AS 'Holding Type',
						CASE WHEN t.Bill_no = 'Opening'  AND ISNULL(t.Frmnm,'') != 'BB' THEN 'Opening' 
							 WHEN t.TransType='Bought' AND  t.Bill_no != 'Opening'  THEN 'Bought' 
							 WHEN TransType='Sold' THEN 'Sold' 
						END AS 'Flag_Type',
						cm.Consultant_Name,t.isstock
						INTO #alldata 
				FROM brokerbill_trans t 
				LEFT JOIN mst_script ms ON t.script_code = Ms.script_code 
				LEFT JOIN   Mst_Consultant  cm ON t.Consultant_code = cm.Consultant_code  
				WHERE  isfnobill = @Investmenttype AND trans_dt <= @Todate AND t.member_code = @memcode AND yearcode = @yearcode  
				AND  t.script_code IN (SELECT * FROM #SCriptCodes)
				AND	 t.Consultant_code IN (SELECT * FROM #ConsultantCodes)
				AND  isnull(t.isIntraDay,0) =(CASE WHEN @IsIntraDay=0 THEN  isnull(isIntraDay,0) ELSE ISNULL(@IsIntraDay,0) END) 
				AND t.isstock=(select case when @Is_BFCF = 1 then  '' else  t.isstock end)
				GROUP BY Trans_No,Sr_No,Bill_no,Trans_Dt,TransType,Ac_Type,t.Script_Code,MonthYear,Last_Date,LotSize,Qty,LotQty,Disp_qty,
				Bal_qty,G_Rate,Brok_Amt,ServTax_Amount,Exp_Rate,Amount,Stt_Amount,t.Member_Code,YearCode,t.Consultant_code,
				EntrySource,Ref_TransNo,Ref_SrNo,MergedEntry,isFNOBill,Strike_Price,OptionType,isIntraDay,Brok_PerUnit,lockedbymerger,
				frac_Qty,Org_Trans_No,Org_SrNo,isDeleteMerger,isstock,ScripwiseExpense,isClient_code,isClient_Brokrage,c_Qty,C_Gross_Rate,
				C_Net_Rate,C_Amount,C_STT,C_STax,C_MisChg,TransactionChg,C_StampDuty,Exp_Rate,PerExp_Unit,FrmNm,ID,bse_code,nse_code,script_name ,cm.Consultant_Name,t.isstock
				ORDER  BY NameId 
				 
				DECLARE @isIntradayCol INT 
				DECLARE  @COUNT INT = 0	 

				DECLARE alldatacursor CURSOR READ_ONLY FOR 
				SELECT id,Trans_No,script_name,Script_Code,  [holding type],bill_no,CONVERT(DATETIME,trans_dt,101),qty,Exp_Rate,ISNULL(qty, 0) * ISNULL(Exp_Rate, 0),ISNULL(isintraday, 0),consultant_name ,Strike_Price,OptionType,Last_Date  
				FROM #alldata
				WHERE #alldata.bill_no IN('Split','Opening') OR  CONVERT(date,trans_dt,101)  < CONVERT(date ,@StartYearDate,101)

				OPEN alldatacursor 
			 	FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type, @billno,@dates, @qty, @rate, @amount, @isIntradayCol ,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date
				WHILE(@@FETCH_STATUS = 0)
					BEGIN
						-- Insert All Openings
						SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
						SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
						SET @Dup_pkid = ISNULL(@Dup_pkid,0)
						SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
						SET @Dup_pkid = @Dup_pkid + 1
						DECLARE @IDs INT=0
						INSERT INTO #MainOutputtable_1   (opening_bill_no, id,Dup_pkid,  Trans_No,ScriptCode ,  Flag_Type, script_name,holding_type,opening_date,opening_qty,opening_rate,isintradaycol,consultant_name,Strike_Price,OptionType,Last_Date) 
						SELECT @billno,@ID,@Dup_pkid, @Trans_No,@ScriptId ,'Opening',@scriptname,@holding_type,@dates,@qty,@rate,@isIntradayCol ,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date
						
						IF(@idcount>0)
							BEGIN
								UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
							END
					END 
						FETCH NEXT FROM alldatacursor INTO @ID,@Trans_No, @scriptname,@ScriptId, @holding_type,@billno,@dates,@qty,@rate,@amount,@isIntradayCol, @Consultant_Name,@Strike_Price,@OptionType,@Last_Date

				CLOSE alldatacursor 
				DEALLOCATE alldatacursor 
		
				DECLARE @salecount INT=0,@Boughtcount INT=0,@Flag_Type VARCHAR(20)
				
				DECLARE purchaseANDSaledatacursor CURSOR READ_ONLY FOR 
				SELECT id,Bill_no,Flag_Type,TransType,script_code ,script_name,[holding type],Trans_No,CONVERT(DATETIME, trans_dt,101), qty,Exp_Rate,qty * Exp_Rate,ISNULL(isintraday, 0)isIntraDay,Consultant_Name,Strike_Price,OptionType,Last_Date
				FROM #alldata WHERE   
				(TransType in('Bought','Sold')  AND CONVERT(date,trans_dt,101)  >= CONVERT(date ,@StartYearDate,101)) and  Flag_Type NOT IN('Opening') 
				--#alldata.bill_no NOT IN('Split','Opening') 
				--GROUP BY  id,Bill_no,Flag_Type,TransType,script_name,script_code ,[holding type],Trans_No,  trans_dt , qty,Exp_Rate , isIntraDay,Consultant_Name	
				OPEN purchaseANDSaledatacursor 
			
				FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type , @TransType,@ScriptId, @scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name ,@Strike_Price,@OptionType,@Last_Date
				
				WHILE (@@FETCH_STATUS = 0) 
						BEGIN
							SET @COUNT = 0
							DECLARE @IsOpening INT =0
							DECLARE @prioritysId INT=0
							DECLARE @str VARCHAR(MAX)=''	
							DECLARE @purchase_Op_Qty FLOAT =0
							DECLARE @purchase_Op_Bill VARCHAR(20)=''
							DECLARE @purchase_Op_Date VARCHAR(20)=''
							DECLARE @purchase_Op_Rate FLOAT=0
							DECLARE	@PurQTY FLOAT=0
							DECLARE	@BalPurQTY FLOAT=0
							DECLARE @BalSoldQTY FLOAT=0
							DECLARE @Balpurchase_Op_Qty FLOAT=0
							DECLARE @BalOpeningQTY FLOAT=0
							DECLARE	@Sold_Qty FLOAT=0
							DECLARE @tempID int = 0
							IF(@isIntradayCol=0)
								BEGIN
									IF(@TransType LIKE '%Bought%')
										BEGIN
											/* For Purchase or opening Entry  IS Sold Enry Already Exists with Same Script And Holding Type */
											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type_Sold IN('Sold')  and  Flag_Type ='Sold'  AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0)) AND isintradaycol=0 AND Consultant_Name = (CASE WHEN @ConsultantCode <> '' THEN @Consultant_Name ELSE consultant_name END))
											IF (@COUNT > 0)
												BEGIN
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, holding_type,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* INTO #tempSoldValExists 
													FROM
													#MainOutputtable_1 
													WHERE script_name=@scriptname AND holding_type=@holding_type  AND isintradaycol=0 AND 
													consultant_name = (CASE WHEN @ConsultantCode <> '' THEN @Consultant_Name ELSE consultant_name END)
													AND ISNULL(sold_qty,0)!=0 AND ((ISNULL(purchase_qty,0)=0) OR  (ISNULL(opening_qty,0)=0))
													AND Flag_Type_Sold IN('Sold')  and  Flag_Type ='Sold'  AND isintradaycol=0
													ORDER BY NameId
													
													
													DECLARE @R_Sold_COUNT INT=(SELECT COUNT(*) FROM #tempSoldValExists )
													DECLARE @Temppurchase_Op_Qty INT 
													SET @purchase_Op_Qty=@qty
													WHILE(@R_Sold_COUNT  > 0)
														BEGIN 
															DECLARE @tempSaleID INT = (SELECT TOP(1) id FROM #tempSoldValExists )
															SET @str=@TransType
															SET @Temppurchase_Op_Qty=(SELECT TOP(1) sold_qty  FROM #tempSoldValExists WHERE id  = @tempSaleID  ORDER BY Dup_pkid)
															SET @soldDate=(SELECT TOP (1) sold_date  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @soldRate=(SELECT TOP (1) sold_rate  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @soldBillNo=(SELECT TOP (1) sold_bill_no  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempSoldValExists WHERE id  = @tempSaleID )
															SET @Sold_Qty= @purchase_Op_Qty
															IF(@TransType='Opening')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	
																	opening_date=@dates,
																	opening_rate=@rate,
																	opening_qty= CASE WHEN @Temppurchase_Op_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Temppurchase_Op_Qty END,
																	Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND pkid = @pkid
																END
															ELSE IF(@TransType='Bought')
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET	
																	purchase_date=@dates,
																	purchase_bill_no=@billno,
																	purchase_rate=@rate,
																	purchase_qty= CASE WHEN @Temppurchase_Op_Qty > @purchase_Op_Qty THEN @purchase_Op_Qty ELSE @Temppurchase_Op_Qty END,
																	Flag_Type='Bought'
																	WHERE  id = @tempSaleID  AND pkid = @pkid
																END
															

															IF(@Temppurchase_Op_Qty > @purchase_Op_Qty )
																BEGIN
																	UPDATE #MainOutputtable_1  
																	SET sold_qty=@purchase_Op_Qty 
																	WHERE Flag_Type_Sold='Sold' AND   id = @tempSaleID  AND pkid = @pkid
																END

															DELETE FROM #tempSoldValExists  WHERE id = @tempSaleID  AND pkid = @pkid
															SET @tablerowscount=(SELECT COUNT(*) FROM  #tempSoldValExists )
															DECLARE @Balancedval   FLOAT = ABS(@purchase_Op_Qty) - ABS(@Temppurchase_Op_Qty)

															IF(@Balancedval  < 0)
																BEGIN
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1
																	SET @soldQty=ABS(@Balancedval) 
																	SET @prioritysId  =(SELECT MAX(prioritys) FROM #MainOutputtable_1)-- WHERE id=@tempSaleID )
																	SET @prioritysId = ISNULL(@prioritysId,0)+1
																	INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode, Flag_Type,Flag_Type_Sold, prioritys,script_name,holding_type,sold_bill_no, sold_date,sold_qty,sold_rate,isintradaycol,consultant_name,Strike_Price,OptionType,Last_Date )
																	VALUES(@Dup_pkid,@tempSaleID ,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@soldBillNo,@soldDate,ABS(@Balancedval),@soldRate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date)
																	
																	UPDATE #MainOutputtable_1 SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempSaleID 
																	
																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																		END
																	BREAK;
																END
															ELSE IF(@Balancedval  > 0 AND @tablerowscount = 0)
																BEGIN
																	SET @prioritysId  = (SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																	SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																	SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																	SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																	SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																	SET @Dup_pkid = @Dup_pkid + 1

																	if(@TransType='Opening')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode, Flag_Type,  prioritys,  script_name,holding_type, opening_date,opening_qty,opening_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date,Strike_Price,OptionType,Last_Date)
																			VALUES(@Dup_pkid,@ID,@Trans_No, @ScriptId,'Bought', @prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval),@rate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date,@Strike_Price,@OptionType,@Last_Date)
																		END
																	ELSE if(@TransType='Bought')
																		BEGIN
																			INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No, ScriptCode, Flag_Type, Flag_Type_Sold,prioritys,script_name,holding_type,purchase_bill_no,purchase_date,purchase_qty,purchase_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date )
																			VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Bought','Bought',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balancedval)  ,@rate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date )
																		END

																	IF(@idcount>0)
																		BEGIN
																			UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																		END	
																 ENd
															
															SET @R_Sold_COUNT  = @R_Sold_COUNT  - 1
															SET @qty=@Balancedval
														END
													

													DROP TABLE #tempSoldValExists
												END
											/*To Insert New Purchase or opening Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1)
													INSERT INTO #MainOutputtable_1 (Dup_pkid,id,Trans_No,ScriptCode, prioritys,Flag_Type,script_name, holding_type, purchase_bill_no, purchase_date, purchase_qty, purchase_rate, isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date ) 
													VALUES (@Dup_pkid, @ID,@Trans_No,@ScriptId, @prioritysId,'Bought', @scriptname, @holding_type, @billno, @dates, @qty, @rate, @isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date ) 
												END
										END	
									ELSE IF(@TransType LIKE '%Sold%')
										BEGIN
											/* For Sold Entry  IS Purchase And Opening Enry Already Exists with Same Script And Holding Type */

											SET @COUNT = (SELECT Count(*) FROM #MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening') AND ISNULL(sold_qty,0)=0  AND isintradaycol=0  AND Consultant_Name = (CASE WHEN @ConsultantCode <> '' THEN @Consultant_Name ELSE consultant_name END))
											IF (@COUNT > 0)
									 			BEGIN
													DECLARE @Balanceval FLOAT
													SELECT  ROW_NUMBER ( ) OVER (ORDER BY  scriptcode, holding_type,case when opening_date <> NULL then opening_date else purchase_date end  ) AS NameId,
													* INTO #tempValExists 
													FROM
													#MainOutputtable_1 WHERE holding_type=@holding_type AND script_name=@scriptname AND Flag_Type IN('Bought','Rights','Bonus','Ipo','Opening','Split') 
													AND consultant_name = (CASE WHEN @ConsultantCode <> '' THEN @Consultant_Name ELSE consultant_name END) 
													AND ISNULL(sold_qty,0)=0  AND isintradaycol=0 
													ORDER BY NameId
													
													DECLARE @RCOUNT INT= (SELECT COUNT(*) FROM #tempValExists)
													DECLARE @TempSoldQty int 
													
													
													WHILE(@RCOUNT > 0)
														BEGIN 
															SET @tempID = (Select top(1) id from #tempValExists  ORDER BY Dup_pkid)
															SET @str = (Select top(1) Flag_Type From #tempValExists Where id  = @tempID)
															SET @Sold_Qty= @qty
															IF(@str='Opening')
																BEGIN
																	SET @TempSoldQty=(SELECT TOP(1) opening_qty  FROM #tempValExists WHERE id  = @tempID)
																	SET @openingDate=(SELECT TOP(1) opening_date FROM #tempValExists WHERE id  = @tempID)
																	SET @openingrate=(SELECT TOP(1) opening_rate FROM #tempValExists WHERE id  = @tempID)
																	SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempValExists WHERE id  = @tempID )
																END
															ELSE IF(@str='Bought')
																BEGIN
																	SET @TempSoldQty=(SELECT TOP(1) purchase_qty FROM #tempValExists WHERE id  = @tempID)
																	SET @PurchaseDate=(SELECT TOP(1) purchase_date FROM #tempValExists WHERE id  = @tempID)
																	SET @Purchaserate=(SELECT TOP(1) purchase_rate FROM #tempValExists WHERE id  = @tempID)
																	SET @PurchaseBillNo=(SELECT TOP(1) purchase_bill_no FROM #tempValExists WHERE id  = @tempID)
																	SET @Pkid = (SELECT TOP (1) Pkid  FROM #tempValExists WHERE id  = @tempID )
																END
															    
															IF(@Sold_Qty > 0)
																BEGIN
																	UPDATE #MainOutputtable_1  
																		SET	
																			opening_qty = CASE WHEN @str ='Opening'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																								ELSE 0
																							END,
																			purchase_qty  = CASE WHEN @str ='Bought'
																								THEN 
																									CASE WHEN  @TempSoldQty >= @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END
																							END,
																			sold_date=@dates,
																			sold_bill_no=@billno,
																			sold_rate=@rate,
																			sold_qty= CASE WHEN @TempSoldQty > @Sold_Qty THEN @Sold_Qty ELSE @TempSoldQty END,
																			Flag_Type_Sold='Sold'
																	WHERE  id = @tempID and ISNULL(sold_qty,0)=0 AND pkid = @pkid
																	SET @Balanceval = ABS(@Sold_Qty) - ABS(@TempSoldQty)
																END
															
														DELETE FROM #tempValExists WHERE id = @tempID AND pkid = @pkid
														SET @tablerowscount=(SELECT COUNT(*) FROM  #tempValExists )
														SET @RCOUNT = @RCOUNT - 1
													
														IF(@Balanceval  < 0)
															BEGIN
																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1

																SET @prioritysId  =(SELECT MAX(ISNULL(@prioritysId,0) + 1) FROM #MainOutputtable_1) 
																IF(@str='Opening')
																	BEGIN
																		SET @openingQty=ABS(@Balanceval) 
																		INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Opening_date,Opening_qty,Opening_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date )
																		VALUES(@Dup_pkid,@tempID,@Trans_No,@ScriptId, 'Opening',@prioritysId, @scriptname,@holding_type,@openingdate,ABS(@Balanceval) ,@openingrate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date )
																		UPDATE #MainOutputtable_1 SET prioritys=@prioritysId+1  WHERE prioritys > @prioritysId AND ID<>@tempID
																	END
																ELSE 
																	BEGIN
																		SET @PurchaseQty=ABS(@Sold_Qty) 
																		INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, prioritys,script_name,holding_type,Purchase_date,purchase_bill_no , Purchase_qty,Purchase_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date )
																		VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Bought',@prioritysId, @scriptname,@holding_type,@Purchasedate,@PurchaseBillNo ,ABS(@Balanceval)  ,@Purchaserate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date )
																		UPDATE #MainOutputtable_1 SET prioritys=@prioritysId  WHERE prioritys > @prioritysId AND ID<>@tempID
																	END
																IF(@idcount>0)
																	BEGIN
																		UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																	END
																BREAK;
															END
														ELSE IF(@Balanceval  >  0 AND @tablerowscount = 0)
															BEGIN
																SET @Dup_pkid = (SELECT (MAX(ISNULL(Dup_pkid,0))) FROM #MainOutputtable_1 WHERE script_name = @scriptname)
																SET @Dup_pkid = (SELECT CASE WHEN ISNULL(@Dup_pkid,0) = 0 then (SELECT (MAX(ISNULL(Dup_pkid,1))) FROM #MainOutputtable_1) else @Dup_pkid end)
																SET @Dup_pkid = ISNULL(@Dup_pkid,0)
																SET @idcount = (SELECT COUNT(*) FROM #MainOutputtable_1 WHERE Dup_pkid > @Dup_pkid)
																SET @Dup_pkid = @Dup_pkid + 1

																SET @prioritysId  =(SELECT MAX(prioritys+1) FROM #MainOutputtable_1)
																INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date )
																VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId, 'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,ABS(@Balanceval)  ,@rate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date )
															
																IF(@idcount>0)
																	BEGIN
																		UPDATE #MainOutputtable_1 SET Dup_pkid = Dup_pkid + 1 where Dup_pkid >= @Dup_pkid  and script_name <> @scriptname
																	END
															END
														SET @qty = @Balanceval
													END
													DROP TABLE #tempValExists
											END
											
											/*To Insert New Sold Entry If Sold Does Not Exists In Previous Data*/
											ELSE
												BEGIN
													SET @prioritysId=(SELECT MAX(ISNULL(prioritys,0)+1) FROM #mainoutputtable_1)
													SET @Dup_pkid =(select max(Dup_pkid+1) from #mainoutputtable_1) 
													INSERT INTO #MainOutputtable_1(Dup_pkid,ID,Trans_No,ScriptCode,  Flag_Type, Flag_Type_Sold,prioritys,  script_name,holding_type,Sold_bill_no,Sold_date,Sold_qty,Sold_rate,isintradaycol,consultant_Name,Strike_Price,OptionType,Last_Date )
													VALUES(@Dup_pkid,@ID,@Trans_No,@ScriptId,  'Sold','Sold',@prioritysId, @scriptname,@holding_type,@billno,@dates,@qty,@rate,@isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date )
												END
											SET @purchase_Op_Date=''
											SET @purchase_Op_Rate=''
											SET @purchase_Op_Qty=''
											SET @purchase_Op_Bill=''
										END
								END
							 
							FETCH NEXT FROM purchaseANDSaledatacursor INTO @ID,@billno,@Flag_Type,@TransType,@ScriptId,@scriptname,@holding_type,@Trans_No, @dates,@qty, @rate, @amount, @isIntradayCol,@Consultant_Name,@Strike_Price,@OptionType,@Last_Date 
						END 
						 
				CLOSE purchaseANDSaledatacursor 
				DEALLOCATE purchaseANDSaledatacursor 
		END 
		
		INSERT INTO #mainoutputtable_1_Final (OrderBy, opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name,Holding_Type,flag_script_name,flag_Holding_Type,
				opening_date,opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,gain_loss ,closing_qty ,closing_rate ,closing_value ,
				short_term,long_term,speculation,gain_speculation,loss_speculation,consultant_name,nse_rate,bse_rate, sort,isintradaycol ,Strike_Price,OptionType,Last_Date)

				SELECT ROW_NUMBER ( ) OVER (ORDER BY  ScriptCode,holding_type,Dup_pkid, case when CONVERT(DATE,opening_date,101) <> null then CONVERT(DATE,opening_date,101) else CONVERT(DATE,purchase_date,103) END,prioritys DESC, sold_date DESC ) AS NameId,
				opening_bill_no,id,Trans_No, prioritys,ScriptCode,script_name ,Holding_Type, flag_script_name,flag_Holding_Type,opening_date,
				opening_qty ,opening_Rate,opening_amount,purchase_date,purchase_bill_no,
				purchase_qty ,purchase_rate ,purchase_amount ,sold_date ,sold_bill_no ,sold_qty ,
				sold_rate,sold_amount ,
				 
					    Round(ISNULL(
							CASE	WHEN  opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365   --short term for openings
									THEN  sold_rate * sold_qty - opening_rate*opening_qty
									WHEN  purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365 --short term for purchase
									THEN  sold_rate * sold_qty - purchase_rate*purchase_qty  --long term
									ELSE
										CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
												WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
													THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
												ELSE 0.0
										END
							END,0) ,4)
						as gain_loss,
				
				closing_qty ,closing_rate ,closing_value ,
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) < 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) < 365) --short term for purchase
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
						
				CASE WHEN  (opening_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101)) > 365)   --short term for openings
							OR
							(purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) > 365) --short term for purchase
					THEN  
						CASE	WHEN opening_date IS NOT NULL AND sold_date IS NOT NULL  -- openings
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, opening_rate, sold_rate, CONVERT(DATETIME,opening_date,101), CONVERT(DATETIME,sold_date,101), opening_qty, sold_qty)) 
								WHEN purchase_date IS NOT NULL AND sold_date IS NOT NULL  -- Purchase
									THEN (Select [dbo].[fnGetGainnLoss](@Investmenttype,ScriptCode, @BSE_NSE_Code, purchase_rate, sold_rate, CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101), purchase_qty, sold_qty)) 
								ELSE 0.0
						END
				ELSE 0.0 END,
				CASE WHEN  (purchase_date IS NOT NULL AND sold_date IS NOT NULL AND DATEDIFF(DAY,  CONVERT(DATETIME,purchase_date,101), CONVERT(DATETIME,sold_date,101)) = 0) 
							AND (purchase_bill_no = sold_bill_no) 
				THEN  sold_rate * sold_qty - purchase_rate*purchase_qty ELSE 0.0 END,
				0,
				0,
				consultant_name,nse_rate,bse_rate,1 sort,isintradaycol ,Strike_Price,OptionType,Last_Date
				FROM #MainOutputtable_1 
				order by NameId

		UPDATE #mainoutputtable_1_Final SET prioritys=0
		DECLARE @i INT  = (SELECT ISNULL(MAX(prioritys),0)   FROM #mainoutputtable_1_Final)
		UPDATE #mainoutputtable_1_Final
		SET prioritys  = @i , @i = @i + 1

		IF(@OUTPUT_Flag='Details')
			BEGIN
				IF(@ConsultantCode!='')
					BEGIN
					 
				 SELECT id,prioritys,   ScriptCode,script_name 'Script Name','Empty' Holding_Type,opening_bill_no,
						CONVERT(date, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(date, purchase_date,101) 'Purchase Date',ISNULL(purchase_bill_no,0) 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(date, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss', ISNULL(Gain,0)Gain, ISNULL(Loss,0)Loss,
						ISNULL(Closing_Qty,0) 'Closing Qty',(ISNULL(Closing_Rate,0)) 'Closing Rate',(ISNULL(Closing_Value,0)) 'Closing Value',
						ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,ISNULL(isintradaycol,0)isintradaycol,1 sort 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)
						ORDER By consultant_name,script_name,Holding_Type
					END
				ELSE
					BEGIN
						
						SELECT id,prioritys,   ScriptCode,script_name 'Script Name','Empty' Holding_Type,opening_bill_no,
						CONVERT(date, opening_date,101) 'Opening Date',ISNULL(opening_qty,0) 'Opening Qty',ISNULL(opening_Rate,0) 'Opening Rate',ISNULL(opening_amount,0) 'Opening Amount',
						CONVERT(date, purchase_date,101) 'Purchase Date',purchase_bill_no 'Purchase BillNo',ISNULL(purchase_qty,0) 'Purchase Qty',ISNULL(purchase_rate,0) 'Purchase Rate',ISNULL(purchase_amount,0) 'Purchase Amount',
						CONVERT(date, sold_date,101) 'Sold Date',sold_bill_no 'Sold BillNo',ISNULL(sold_qty,0) 'Sold Qty',ISNULL(sold_rate,0) 'Sold Rate',ISNULL(sold_amount,0) 'Sold Amount',
						ISNULL(gain_loss,0) 'Gain/Loss',ISNULL(Gain,0)Gain,ISNULL(Loss,0)Loss,
						ISNULL(Closing_Qty,0)   'Closing Qty', ISNULL(Closing_Rate,0)  'Closing Rate', ISNULL(Closing_Value,0)  'Closing Value',
						ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(gain,0) != 0 THEN ISNULL(gain,0)  ELSE '' END gain_speculation,
						CASE WHEN isintradaycol=1 AND ISNULL(loss,0) != 0  THEN ISNULL(loss,0)  ELSE '' END loss_speculation,
						consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,ISNULL(isintradaycol,0)isintradaycol,1 sort 
						FROM #mainoutputtable_1_Final
						WHERE (opening_qty != 0  or purchase_qty != 0  or sold_qty != 0)  
						ORDER BY   script_name--,id
					END
			END

		ELSE IF(@OUTPUT_Flag='ScriptWiseTotal')
			 BEGIN
				SELECT  0 id ,  0 prioritys, script_name 'Script Name', 'Empty' Holding_Type,
				NULL 'Opening Date', SUM(ISNULL(opening_qty,0)) 'Opening Qty',  ISNULL((ISNULL(SUM(ISNULL(opening_amount,0)),0)  / NULLIF(SUM(ISNULL(Opening_qty,0)),0)),0)   'Opening Rate', SUM(ISNULL(opening_amount,0)) 'Opening Amount',
				NULL 'Purchase Date',MAX(purchase_bill_no) 'Purchase BillNo', SUM(ISNULL(purchase_qty,0))  'Purchase Qty', ISNULL((ISNULL(SUM(ISNULL(purchase_amount,0)),0)  / SUM(NULLIF(ISNULL(purchase_qty,0),0))),0)  'Purchase Rate', SUM(ISNULL(purchase_amount,0))  'Purchase Amount',
				NULL 'Sold Date', MAX(sold_bill_no) 'Sold BillNo', SUM(ISNULL(sold_qty,0)) 'Sold Qty', ISNULL((ISNULL(SUM(ISNULL(sold_amount,0)),0) / NULLIF (SUM(ISNULL(sold_qty,0)),0)),0) 'Sold Rate', SUM(ISNULL(sold_amount,0)) 'Sold Amount', 
				SUM(ISNULL(gain_loss ,0)) 'Gain/Loss', SUM(ISNULL(gain,0))  'Gain', SUM(ISNULL(loss,0))  'Loss',
				SUM(ISNULL(closing_qty,0))  'Closing Qty', ISNULL((ISNULL(SUM(ISNULL(closing_value,0)),0) / NULLIF(SUM(ISNULL(closing_qty,0)),0)),0)   'Closing Rate', SUM(ISNULL(closing_value,0))  'Closing Value',
				SUM(ISNULL(short_term,0))  short_term, SUM(ISNULL(long_term,0))  long_term,SUM(ISNULL(speculation,0))speculation, 
				SUM(ISNULL(gain_speculation,0))gain_speculation, SUM(ISNULL(loss_speculation,0))loss_speculation,
				'' consultant_name,0 nse_rate,0 bse_rate,1 sort 
				FROM
					(
						SELECT MAX(id+0)id ,MAX (prioritys+0) prioritys, script_name  ,'Empty' Holding_Type,
						NULL 'Opening Date',SUM(opening_qty) 'Opening_Qty',sum(opening_rate) opening_rate ,SUM(opening_amount) 'Opening_Amount',
						NULL 'Purchase Date',purchase_bill_no,SUM(purchase_qty) 'Purchase_Qty', SUM(purchase_rate) purchase_rate,SUM(purchase_amount) 'Purchase_Amount',
						NULL 'Sold Date',sold_bill_no ,SUM(sold_qty) 'Sold_Qty', SUM(sold_rate)sold_rate  , SUM(sold_amount) 'Sold_Amount',SUM(gain_loss) 'Gain_Loss',SUM(gain) 'Gain',SUM(loss) 'Loss',
						SUM(closing_qty) 'Closing_Qty',SUM(closing_rate) 'Closing_Rate',SUM(closing_value) 'Closing_Value',SUM(short_term) short_term,SUM(long_term) long_term,
						SUM(speculation) speculation,SUM(gain_speculation) gain_speculation,SUM(loss_speculation) loss_speculation,'' consultant_name,0 nse_rate,0 bse_rate,1 sort --,dayscount,isintradaycol,type,Split_Type,Flag_Type,Flag_Type_Sold
						FROM #mainoutputtable_1_Final 
						GROUP BY script_name,Holding_Type,purchase_bill_no,sold_bill_no 
					)a
				GROUP BY  script_name  
				ORDER BY  prioritys 
			END

		ELSE IF(@OUTPUT_Flag='AllData')
			BEGIN
			
				SELECT  prioritys ,Trans_No,id , ScriptCode,script_name ,'Empty' Holding_Type, flag_script_name,flag_Holding_Type,
				CONVERT(date, opening_date,101)opening_date,ISNULL(opening_qty,0) opening_qty,ISNULL(opening_Rate,0)opening_Rate,ISNULL(opening_amount,0)opening_amount,
				CONVERT(date, purchase_date,101)purchase_date,purchase_bill_no,ISNULL(purchase_qty ,0)purchase_qty,ISNULL(purchase_rate ,0)purchase_rate ,ISNULL(purchase_amount ,0)purchase_amount ,
				CONVERT(date, sold_date,101) sold_date,sold_bill_no ,ISNULL(sold_qty ,0)sold_qty ,ISNULL(sold_rate,0)sold_rate,ISNULL(sold_amount ,0)sold_amount ,
				ISNULL(gain_loss ,0)gain_loss,ISNULL(gain ,0),ISNULL(loss,0),ISNULL(closing_qty ,0)closing_qty ,ISNULL(closing_rate ,0)closing_rate ,ISNULL(closing_value ,0)closing_value ,
				ISNULL(short_term,0)short_term,ISNULL(long_term,0)long_term,ISNULL(speculation,0)speculation,
				ISNULL(gain_speculation,0)gain_speculation,ISNULL(loss_speculation,0)loss_speculation,
				consultant_name,ISNULL(nse_rate,0)nse_rate,ISNULL(bse_rate,0)bse_rate,0 Other_amt,0 ServTax_Amt ,0 Stt_amt ,1 sort ,isintradaycol,ISNULL(Strike_Price,0)Strike_Price,OptionType,Last_Date
				FROM #mainoutputtable_1_Final
			END

		DROP TABLE #MainOutputtable_1 
		 
		DROP TABLE #alldata 
		 
  END  




































GO
/****** Object:  StoredProcedure [dbo].[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency_Summary]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency_Summary] AS' 
END
GO
 --Execute  proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency_Summary  0,1,'0','A0001','1120172018','2015-02-01 12:00:00:00','2018-02-01 03:50:37:50','','','0','', '0' ,'0',0,1,0
ALTER PROCEDURE [dbo].[proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency_Summary]  --''
(@status INT,@Investmenttype  INT,@Ac_Type NVARCHAR(100),@memcode VARCHAR(100),@yearcode VARCHAR(100),@Fromdate datetime,@Todate datetime, 
@ScriptCode VARCHAR(max),@ConsultantCode  VARCHAR(max),@BSE_NSE_Code VARCHAR(max),@Is_BFCF VARCHAR(max),@IsIntraDay VARCHAR(max),@short_Long_Term INT,
@RecordOnlyhavingClosingbalanceZero as bit,@WithActualAvgRate as bit, @DateWiseClosinStock as bit)
AS
BEGIN
SET NOCOUNT ON;
		CREATE TABLE #mainoutputtable_1_Final_Summary 
        ( 
          prioritys INT,Trans_No VARCHAR(50), id INT, script_Code VARCHAR(50),script_name  VARCHAR(500),holding_type VARCHAR(200),flag_script_name  VARCHAR(500),flag_holding_type VARCHAR(200),
           opening_date VARCHAR(50),opening_qty  FLOAT DEFAULT 0,opening_rate  FLOAT DEFAULT 0,opening_amount FLOAT DEFAULT 0, 
           purchase_date VARCHAR(50),purchase_bill_no VARCHAR(100),purchase_qty FLOAT DEFAULT 0,purchase_rate FLOAT DEFAULT 0,purchase_amount FLOAT DEFAULT 0 , 
           sold_date VARCHAR(50),sold_bill_no VARCHAR(100),sold_qty FLOAT DEFAULT 0,sold_rate FLOAT DEFAULT 0,sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,gain FLOAT DEFAULT 0,loss FLOAT DEFAULT 0,
		   closing_qty FLOAT DEFAULT 0, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   Other_amt FLOAT DEFAULT 0,
		   ServTax_Amt FLOAT DEFAULT 0,
		   Stt_amt FLOAT DEFAULT 0,
		   sort   VARCHAR(5),
		   isintradaycol  INT,
		   Strike_Price float,
		   OptionType varchar(max),
		   Last_Date dateTime
		 
        ) 

		
		IF(@ConsultantCode = '0')	
			BEGIN
						
				SELECT DISTINCT p.member_code,p.year_code,
					STUFF((	SELECT distinct ',' + p1.Consultant_Code
							FROM Mst_Consultant p1
							FOR XML PATH(''), TYPE
							).value('.', 'NVARCHAR(MAX)')
					,1,1,'') ConsultantCode
				into #temoConsultant
				FROM Mst_Consultant p

				SET @ConsultantCode = (Select Top(1) ConsultantCode From  #temoConsultant WHERE member_code = @memcode AND year_code = @yearcode)
				DROP table #temoConsultant
			END

		Insert into #mainoutputtable_1_Final_Summary
		EXEC proc_WithTaxStockholding_F_And_O_AND_MCX_And_Currency   @status,@Investmenttype,@Ac_Type,@memcode,@yearcode,@Fromdate,@Todate,@ScriptCode,@ConsultantCode,@BSE_NSE_Code,@Is_BFCF,@IsIntraDay,@short_Long_Term,'ALLData'
	 
		SELECT T1.id,T1.Trans_No,T1.prioritys,T1.script_name,T1.holding_type,T1.flag_script_name,T1.flag_holding_type,
		T1.opening_date,T1.opening_qty,T1.opening_rate,T1.opening_amount,
		T1.purchase_date,T1.purchase_bill_no,T1.purchase_qty,T1.purchase_rate,T1.purchase_amount,
		T1.sold_date,T1.sold_bill_no,T1.sold_qty,T1.sold_rate,T1.sold_amount,T1.gain_loss,T1.gain,T1.loss,
		T1.closing_qty,T1.closing_rate,T1.closing_value,T1.short_term,T1.long_term,T1.speculation,T1.gain_speculation,T1.loss_speculation,
		T1.consultant_name,T1.sort,T1.isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt ,
		Isnull(Dr.Bse_FO_Rate,0) AS 'bse_rate', /**/
		Isnull(Dr.Nse_FO_Rate,0) AS 'nse_rate' /**/
		INTO #alldata_Summary 
		FROM #mainoutputtable_1_Final_Summary  T1
		LEFT JOIN BrokerBill T2 ON T1.Trans_No=T2.Trans_no
		LEFT JOIN DailyRate  DR  
		ON 
			DR.InvestmentType != 0 and Dr.InvestmentType != 2 AND
			DR.Script_Code = T1.script_Code and  Convert(varchar,dr.Trans_Dt,101) =  Convert(varchar,@Todate,101) AND 
			Convert(varchar,DR.Expir_Date ,101) =  Convert(varchar,T1.Last_Date,101) AND
			ISNULL(Substring(RTRIM(LTRIM(T1.OptionType)),0,3),'') = ISNULL( DR.OptionType,'') AND
			ISNULL(DR.Strike_Price,0) = ISNULL(T1.Strike_Price,'')
		
		TRUNCATE TABLE #mainoutputtable_1_Final_Summary
		INSERT INTO #mainoutputtable_1_Final_Summary (id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,nse_rate,bse_rate,sort,isintradaycol,T2.Other_amt,T2.ServTax_Amt,T2.Stt_amt) 

		SELECT id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,
		Max(ISNULL(nse_rate,0)),Max(ISNULL(bse_rate,0)),
		sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt FROM #alldata_Summary  

		GROUP BY id,Trans_No,prioritys,script_name,holding_type,flag_script_name,flag_holding_type,
		opening_date,opening_qty,opening_rate,opening_amount,
		purchase_date,purchase_bill_no,purchase_qty,purchase_rate,purchase_amount,
		sold_date,sold_bill_no,sold_qty,sold_rate,sold_amount,gain_loss,gain,loss,
		closing_qty,closing_rate,closing_value,short_term,long_term,speculation,gain_speculation,loss_speculation,
		consultant_name,nse_rate,bse_rate,sort,isintradaycol,Other_amt,ServTax_Amt,Stt_amt 

		--select * from #mainoutputtable_1_Final_Summary

		IF(@RecordOnlyhavingClosingbalanceZero = 0)
			BEGIn
				IF((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1) OR (@WithActualAvgRate = 0 AND @DateWiseClosinStock = 1))
					BEGIN
						if(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
									END AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								--SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END,bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
									END AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								--SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,''  consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) != 0
							END
					END
				ELSE IF((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0))
					BEGIN
						if(@ConsultantCode<>'')
							BEGIN
								SELECT  max(id+1)id,holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
									END AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								--SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name, 
								 bse_rate,nse_rate,consultant_name
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name AS 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate', '' 'Gain/Loss',
								''  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) 
										ELSE
								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) ELSE
										0 END 
									END AS 'Avg. Rate',

								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) < 0  THEN (SUM(ISNULL(closing_value,0)) + ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) 
										ELSE
								CASE WHEN 
									SUM(ISNULL(gain_loss,0)) > 0  THEN (SUM(ISNULL(closing_value,0)) - ABS(SUM(ISNULL(gain_loss,0)))) / (NULLIF(SUM(closing_qty),0)) * (SUM( ISNULL(closing_qty,0))) ELSE
										0 END 
									END AS 'Value After Profit/Loss',
								--SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								--SUM(closing_value)-SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,''  consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						if(@ConsultantCode<>'')
							BEGIN
								SELECT   max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date','' 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(closing_value),2) AS 'Closing Value',SUM(closing_qty) AS 'Closing Qty', ISNULL(ROUND( ABS(SUM(IsNULl(closing_value,0))/SUM(NULLIF(closing_qty,0))),4),0)  AS 'Closing Rate','' 'Closing Date',SUM(Gain_Loss) 'Gain/Loss',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) / SUM(closing_qty) as 'Avg. Rate',
								0 Other_amt, '' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) != 0
							END
					END
			END
		ELSE IF(@RecordOnlyhavingClosingbalanceZero = 1)
			BEGIN
				IF ((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 1) or (@WithActualAvgRate = 0 OR @DateWiseClosinStock = 1))
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END  AS  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)   - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate'
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate ,
								CASE
									WHEN closing_qty < 0 THEN sold_date
									WHEN ISNULL(opening_date,'') != '' THEN opening_date
									WHEN ISNULL(purchase_date,'') != '' THEN purchase_date
								END
								HAVING SUM(closing_qty) = 0
							END
					END
				ELSE IF ((@WithActualAvgRate = 1 AND @DateWiseClosinStock = 0) )
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN 
								SELECT  max(id+1)id, holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								''  'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate',
								SUM(ISNULL(Other_amt,0))Other_amt,  consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate 
								HAVING SUM(closing_qty) = 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss',0 'Closing Qty',0 'Closing Rate',0 'Closing Value',
								'' 'Closing Date',
								bse_rate  AS  'BSERATE',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)   - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) / nullif(SUM(closing_qty),0) as 'Avg. Rate'
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate  
								HAVING SUM(closing_qty) = 0
							END
					END
				ELSE IF(@WithActualAvgRate = 0)
					BEGIN
						IF(@ConsultantCode<>'')
							BEGIN
								SELECT max(id+1)id,holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)   - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(ISNULL(gain_loss,0)) AS 'Profit/Loss',
								SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) AS 'Value After Profit/Loss',
								SUM(ISNULL(closing_value,0)) - SUM(ISNULL(gain_loss,0)) / NULLIF(SUM(ISNULL(closing_qty,0)),0) AS 'Avg. Rate',
								SUM(ISNULL(Other_amt,0)) Other_amt, consultant_name,'a' sort
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY consultant_name,holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) != 0
								ORDER BY consultant_name
							END
						ELSE
							BEGIN
								SELECT holding_type,script_name 'Script Name', ROUND(SUM(gain_loss),4) as 'Gain/Loss','' AS 'BSE RATE','' 'Gain/Loss',
								bse_rate  AS  'BSERATE','' 'Closing Qty','' 'Closing Rate','' 'Closing Value','' 'Closing Date',
								bse_rate * SUM(closing_qty)  AS  'BSE_Valuation',
								CASE WHEN bse_rate = 0 THEn 0 ELSE bse_rate * SUM(closing_qty)  - SUM(closing_value) END  AS  'BSE_UnRealizedGainLoss',
								nse_rate AS  'NSERATE',
								nse_rate * SUM(closing_qty) AS  'NSE_Valuation',
								CASE WHEN nse_rate=0 THEN 0 ELSE  nse_rate * SUM(closing_qty) - SUM(closing_value) END AS  'NSE_UnRealizedGainLoss',
								SUM(gain_loss) AS 'Profit/Loss',
								SUM(closing_value) - SUM(gain_loss) AS 'Value After Profit/Loss',
								SUM(closing_value)-SUM(gain_loss) / nullif(SUM(closing_qty),0) AS 'Avg. Rate',
								0 Other_amt,'' consultant_name
								FROM #mainoutputtable_1_Final_Summary
								GROUP BY holding_type,script_name,bse_rate,nse_rate
								HAVING SUM(closing_qty) = 0
							END
					END
			END
			DROP TABLE #alldata_Summary
			--drop table #mainoutputtable_1_Final_Summary
END






























GO
/****** Object:  StoredProcedure [dbo].[Purchar_Sale_MonthWise_Report]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Purchar_Sale_MonthWise_Report]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Purchar_Sale_MonthWise_Report] AS' 
END
GO


-- exec Purchar_Sale_MonthWise_Report '30001','1120182019','04/01/2018','03/31/2019','','','0','200001','','0','20 MICRONS LTD.'

ALTER PROCEDURE [dbo].[Purchar_Sale_MonthWise_Report] (@Membercode     VARCHAR(max), 
                                                       @Yearcode       VARCHAR(10), 
                                                       @FromDate       VARCHAR(50), 
                                                       @ToDate         VARCHAR(50), 
                                                       @BrokerCode     VARCHAR(max), 
                                                       @HoldingType    VARCHAR(500), 
                                                       @InvestmentType VARCHAR(6), 
                                                       @Scriptcode     VARCHAR(max),
													   @isSLBS         VARCHAR(2),
													   @isBfcf  VARCHAR(10),
													   @Script_Name varchar(max) = '')
AS 
  BEGIN 
  SET NOCOUNT ON;
      DECLARE @sqlstr AS NVARCHAR(max) 
			  
      IF( @InvestmentType = 0 OR @InvestmentType = 2 ) 
        BEGIN 
            SET @sqlstr = 'Select BT.script_code	as ''Script_Code'', ' 
			SET @sqlstr = @sqlstr + 'MS.Script_Name			as ''Script_Name'',' 
		END	
      ELSE 
        BEGIN 
           -- SET @sqlstr  = 'Select MS.script_code as ''Script_Code'', ' 
			--SET @sqlstr = @sqlstr + '(MS.Script_Name  + Convert(Varchar,Last_Date,103) + (case WHEN Strike_Price != 0 THEN  ''/'' + Convert(Varchar(20),Strike_Price) ELSE '''' END) +(case WHEN OptionType != '''' THEN  ''/'' + Convert(Varchar(20),OptionType) ELSE '''' END)) as ''Script_Name'','
		DECLARE @ScriptName varchar(500)  = 'MS.Script_Name 
						 + ''/'' +  CONVERT(VARCHAR(10),Last_Date,103) 
						 +	CASE WHEN ISNULL(Strike_Price,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),Strike_Price) ELSE '''' END
						 +  CASE WHEN ISNULL(OptionType,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),OptionType) ELSE '''' 
							END As Script_Name'
																
					SET @sqlstr = 'Select BT.script_code,' + @ScriptName + ','	
		END 

	SET  @sqlstr = @sqlstr  + 'MS.Script_Name	as ''Script_Name_Original'',' 
	SET  @sqlstr = @sqlstr  + 'BB.Broker_Code	as ''Broker_Code'',' 
	SET  @sqlstr = @sqlstr  + 'MA.AC_Name		as ''Broker_Name'',' 
	SET  @sqlstr = @sqlstr  + 'BT.TransType		as ''TransType'',' 

    IF( @InvestmentType = 0) 
      BEGIN 
		  SET @sqlstr = @sqlstr  + '''''		 as ''Last_Date'',' 
          SET @sqlstr = @sqlstr  + 'MAA.Ac_code  as ''HoldingTypeCode'',' 
		  SET @sqlstr = @sqlstr  + 'MAA.Ac_Name  as ''HoldingType'',' 
      END 
    ELSE 
      BEGIN 
		  SET @sqlstr = @sqlstr  + 'BT.Last_Date			as ''Last_Date'',' 
          SET @sqlstr = @sqlstr + ' NULL				as ''HoldingTypeCode'','
		  SET @sqlstr = @sqlstr + ' NULL				as ''HoldingType'',' 
      END 
    
    SET @sqlstr=@sqlstr + ' SUM(BT.Qty)									as ''Quantity'',' 
    SET @sqlstr=@sqlstr + ' Sum(BT.G_Rate * BT.Qty) / Sum(BT.Qty)		as ''GrossRate'',' 
    SET @sqlstr=@sqlstr + ' Sum(BT.G_Rate * BT.Qty)					    as ''GrossAmount'','
    SET @sqlstr=@sqlstr + ' Sum(BT.Amount) / Sum(BT.Qty)				as ''NetRate'','
    SET @sqlstr=@sqlstr + ' Sum(BT.Amount)								as ''NetAmount'',' 
    SET @sqlstr=@sqlstr + ' SUM(BT.Brok_Amt)							as ''BrokerAmount'','  
    SET @sqlstr=@sqlstr + ' BT.isFNOBill								as ''IsFNOBill'',' 
	--SET @sqlstr=@sqlstr + ' BT.IsSLBS								    as ''IsSLBS'''   
	SET @sqlstr = @sqlstr + ' CASE  WHEN IsSLBS is Null   THEN  0 ELSE IsSLBS  END  ''IsSLBS''' 

    SET @sqlstr=@sqlstr + ' INTO #Temp from BrokerBill_Trans BT ' 
    SET @sqlstr=@sqlstr + ' Inner Join BrokerBill BB on BB.Trans_no=BT.Trans_No ' 
    SET @sqlstr=@sqlstr + ' Inner Join Mst_Script MS On MS.Script_Code=BT.Script_Code ' 
    SET @sqlstr=@sqlstr + ' Inner Join Mst_Member MM On MM.Member_Code=BT.Member_code ' 
    SET @sqlstr=@sqlstr + ' Inner Join Mst_Account MA On MA.AC_Code=BB.Broker_Code And MA.Member_Code= ' 
            + Char(39) + @Membercode + Char(39) 
            + 'AND MA.Year_Code = ' + Char(39) + @Yearcode 
            + Char(39) + '' 

    IF( @InvestmentType = 0 ) 
      BEGIN 
          SET @sqlstr=@sqlstr + 'Inner join Mst_Account MAA on MAA.AC_Code=BT.Ac_Type  AND MAA.Member_Code=' 
                + Char(39) + @Membercode + Char(39) 
                + 'AND MAA.Year_Code = ' + Char(39) + @Yearcode 
                + Char(39) + '' 
    END 

    SET @sqlstr = @sqlstr   + ' where BT.isFNOBill = ' + Char(39) + @InvestmentType + Char(39) 
    SET @sqlstr = @sqlstr + ' and BT.Member_code =' + Char(39) + @Membercode + Char(39)    
    SET @sqlstr = @sqlstr + ' and BT.YearCode=' + Char(39) + @Yearcode + Char(39) 
	SET @sqlstr = @sqlstr + ' and BT.MergedEntry !=''1'''
    SET @sqlstr = @sqlstr + ' and (BT.Trans_Dt between ' + Char(39) + @FromDate + Char(39) + ' and ' + Char(39) + @ToDate + Char(39) + ')' 		
    SET @sqlstr = @sqlstr + ' and BT.Ac_Type =  (select case  when ' + Char(39) + @HoldingType + Char(39) + ' = 0 then BT.Ac_Type  else ''' + @HoldingType + ''' end)' 

    IF( @BrokerCode <> '' ) 
      BEGIN 
          SET @sqlstr =@sqlstr + ' and BB.Broker_Code in (SELECT Value FROM membercodestable(' 
                       + Char(39) + @BrokerCode + Char(39) + ',' + Char(39) 
                       + ',' + Char(39) + '))  ' 
      END 

    --IF( @Scriptcode <> '' ) 
    --  BEGIN 
    --      SET @sqlstr = @sqlstr + ' and BT.Script_Code in (SELECT Value FROM membercodestable(' 
    --                    + Char(39) + @Scriptcode + Char(39) + ',' + Char(39) 
    --                    + ',' + Char(39) + '))  ' 
    --  END 

	
	IF(@Investmenttype='0'or @Investmenttype='2')
		BEGIN
			IF ( @Scriptcode <> '' ) 
				BEGIN 
				  SET @sqlstr = @sqlstr + ' and BT.Script_Code in (SELECT Value FROM membercodestable(' + Char(39) +  @Scriptcode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
				END 
		END
	ELSE
		BEGIN
			IF ( @Script_Name <> '' ) 
				BEGIN 
					DECLARE @ScriptNametemp varchar(500)  = 'MS.Script_Name 
				 + ''/'' +  CONVERT(VARCHAR(10),Last_Date,103) 
				 +	CASE WHEN ISNULL(Strike_Price,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),Strike_Price) ELSE '''' END
				 +  CASE WHEN ISNULL(OptionType,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),OptionType) ELSE '''' 
					END'
				  SET @sqlstr = @sqlstr + ' and ' + @ScriptNametemp + ' in (SELECT Value FROM membercodestable(' + Char(39) + @Script_Name + Char(39) + ',' + Char(39) + ',' + Char(39) + ')) ' 
				END 
	END 


    IF(@InvestmentType!=0 AND @InvestmentType!=2)
	 BEGIN 
	      IF(@isBfcf='1')
		   BEGIN
			SET @sqlstr = @sqlstr + ' and BT.isstock not in(''BF'',''CF'') '
		   END
	 END

    IF( @BrokerCode <> '' AND @Scriptcode <> '' ) 
      BEGIN 
          SET @sqlstr =@sqlstr + ' and BB.Broker_Code in (SELECT Value FROM membercodestable(' 
                       + Char(39) + @BrokerCode + Char(39) + ',' + Char(39) 
                       + ',' + Char(39) + '))  ' 
      END 
    IF( @InvestmentType = 0) 
      BEGIN 
          SET @sqlstr =@sqlstr + ' Group by BT.script_code,MS.Script_Name,BT.Member_Code,MM.Member_Name, BB.Broker_Code,MA.AC_Name,BT.TransType,MAA.Ac_code,MAA.AC_Name,Last_Date,Strike_Price,OptionType,BT.isFNOBill,BT.IsSLBS,Last_Date
		 order by 5,1,2'
	 END 
	ELSE
     BEGIN 
          SET @sqlstr =@sqlstr + ' Group by BT.script_code,MS.Script_Name,BT.Member_Code,MM.Member_Name, BB.Broker_Code,MA.AC_Name,BT.TransType,Last_Date,Strike_Price,OptionType,BT.isFNOBill,BT.IsSLBS,BT.Last_Date
			 order by 5,1,2'
	 END 
	
    SET @sqlstr = @sqlstr + ' Select Script_Code,Script_Name,Script_Name_Original,Broker_Code,Broker_Name, HoldingTypeCode, HoldingType,Last_Date,' 
    SET @sqlstr = @sqlstr + ' CASE  WHEN TransType = ''Bought'' THEN SUM(t1.Quantity)					ELSE 0  END  ''PurchaseQTY'',' 
    SET @sqlstr = @sqlstr + ' CASE  WHEN TransType = ''SOLD''   THEN SUM(t1.Quantity)					ELSE 0  END  ''SoldQTY'',' 
    SET @sqlstr = @sqlstr + ' case  WHEN TransType = ''Bought'' THEN SUM(t1.[GrossRate])				ELSE 0  END  ''PurchaseGrossRate'',' 
    SET @sqlstr = @sqlstr + ' CASE  WHEN TransType = ''SOLD''   THEN SUM(t1.[GrossRate])				ELSE 0  END  ''SoldGrossRate'',' 
    SET @sqlstr = @sqlstr + ' CASE  WHEN TransType = ''Bought'' THEN SUM(t1.[GrossAmount])				ELSE 0  END  ''PurchaseGrossAmount'',' 
    SET @sqlstr = @sqlstr + ' CASE  WHEN TransType = ''SOLD''   THEN SUM(t1.[GrossAmount])				ELSE 0  END  ''SoldGrossAmount'',' 
    SET @sqlstr = @sqlstr + ' CASE  WHEN TransType = ''Bought'' THEN SUM(t1.[NetRate])					ELSE 0  END  ''PurchaseNetRate'',' 
    SET @sqlstr = @sqlstr + ' CASE  WHEN TransType = ''SOLD''   THEN SUM(t1.[NetRate])					ELSE 0  END  ''SoldNetRate'',' 
    SET @sqlstr = @sqlstr + ' CASE  WHEN TransType = ''Bought'' THEN SUM(t1.[NetAmount])				ELSE 0  END  ''PurchaseNetAmount'',' 
    SET @sqlstr = @sqlstr + ' CASE  WHEN TransType = ''SOLD''   THEN SUM(t1.[NetAmount])				ELSE 0  END  ''SoldNetAmount'',' 
    SET @sqlstr = @sqlstr + ' CASE  WHEN TransType = ''Bought'' THEN SUM(t1.[BrokerAmount])				ELSE 0  END  ''PurchaseBrokerageAmount'',' 
    SET @sqlstr = @sqlstr + ' CASE  WHEN TransType = ''SOLD''   THEN SUM(t1.[BrokerAmount])				ELSE 0  END  ''SoldBrokerageAmount'','
	SET @sqlstr = @sqlstr + ' CASE  WHEN IsSLBS is Null   THEN  0 ELSE IsSLBS  END  ''IsSLBS'''
	SET @sqlstr = @sqlstr + ' into #Temp_1 FROM #Temp t1  ' 
    SET @sqlstr = @sqlstr + ' Group By Script_Code,Script_Name,Broker_Code,Broker_Name, HoldingType,TransType,HoldingTypeCode,IsSLBS,Last_Date,Script_Name_Original' 
    SET @sqlstr = @sqlstr + ' order by Script_code,Broker_code ' 
	  
    SET @sqlstr = @sqlstr + ' Select Script_Code,Script_Name,Broker_Code,Broker_Name,HoldingTypeCode, HoldingType,' 
    SET @sqlstr = @sqlstr + ' SUM(PurchaseQTY)									as ''PurchaseQTY'' ,' 
    SET @sqlstr = @sqlstr + ' SUM(SoldQTY)										as ''SoldQTY'' ,' 
    SET @sqlstr = @sqlstr + ' SUM(PurchaseGrossRate)							as ''PurchaseGrossRate'',' 
    SET @sqlstr = @sqlstr + ' SUM(SoldGrossRate)								as ''SoldGrossRate'',' 
    SET @sqlstr = @sqlstr + ' SUM(PurchaseGrossAmount)							as ''PurchaseGrossAmount'',' 
    SET @sqlstr = @sqlstr + ' SUM(SoldGrossAmount)								as ''SoldGrossAmount'',' 
    SET @sqlstr = @sqlstr + ' SUM(PurchaseNetRate)								as ''PurchaseNetRate'',' 
    SET @sqlstr = @sqlstr + ' SUM(SoldNetRate)									as ''SoldNetRate'',' 
    SET @sqlstr = @sqlstr + ' SUM(PurchaseNetAmount)							as ''PurchaseNetAmount'',' 
    SET @sqlstr = @sqlstr + ' SUM(SoldNetAmount)								as ''SoldNetAmount'',' 
    SET @sqlstr = @sqlstr + ' SUM(PurchaseBrokerageAmount)						as ''PurchaseBrokerageAmount'',' 
    SET @sqlstr = @sqlstr + ' SUM(SoldBrokerageAmount)							as ''SoldBrokerageAmount'',' 
    SET @sqlstr = @sqlstr + ' SUM(PurchaseQTY) - SUM(SoldQTY)		            as ''NetQty'',' 
	SET @sqlstr = @sqlstr + ' SUM(SoldNetAmount) - SUM(PurchaseNetAmount)		as ''DiffernceAmount'',' 
	SET @sqlstr = @sqlstr + ' IsSLBS											as ''IsSLBS'''
    SET @sqlstr = @sqlstr + ' FROM #Temp_1  ' 
	SET @sqlstr = @sqlstr + ' Where  IsSLBS =  '+ Char(39) + @isSLBS + Char(39) +''
    SET @sqlstr = @sqlstr + ' Group By  Script_Code,Script_Name,Broker_Code,Broker_Name, HoldingType,HoldingTypeCode,IsSLBS,Last_Date,Script_Name_Original' 
    SET @sqlstr = @sqlstr + ' order by Script_Name_Original,Last_Date'
    SET @sqlstr = @sqlstr + ' Drop  Table #temp DROP TABLE #Temp_1' 

    PRINT @sqlstr 

    EXECUTE (@sqlstr) 
END 



GO
/****** Object:  StoredProcedure [dbo].[r_bankreco]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[r_bankreco]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[r_bankreco] AS' 
END
GO
ALTER procedure [dbo].[r_bankreco]
(
 @memcode varchar(Max),
 @yearcode varchar(100),
 @Fromdate varchar(30) ,
 @Todate   varchar(30),
 @bankc   varchar(1000)
)
 
As
Begin
 SET NOCOUNT ON;
 CREATE TABLE #tmptable3
( 
 dt varchar(100),chqno varchar(100),particulars varchar(100),Narration varchar(200),Recdt varchar(100),debit varchar(100),credit varchar(100) 
)

/*print 'SELECT a.Trans_No,a.Sr_No,a.Trans_Dt,a.Chq_No,b.AC_Name,c.AC_Name,a.Dr_Code,a.Cr_Code,a.Reco_Date,a.Reco,a.Amount from Ac_Trans a join Mst_Account b on a.Dr_Code=b.AC_Code join Mst_Account c on a.Cr_Code=c.AC_Code where a.Member_Code='" + Form1.memcode + "' and a.Year_Code='" + Form1.yearcode + "' and Book_Type1='BK'  and (Dr_Code='" + bankc + "' or Cr_Code='" + bankc + "') and a.Trans_Dt>='" + globalno.getstartdate().ToString("yyyy-MM-dd") + "' and a.Trans_Dt<='"+dateTimePicker1.Value.ToString("yyyy-MM-dd")+"'"*/
declare @dt varchar(50),@chqno varchar(100),@acnm varchar(2000),@drnmae varchar(2000),@crname varchar(2000),@drcode varchar(2000),@crcode varchar(2000),@recodt varchar(100),@dbamt varchar(100),@cramt varchar(100),@recostats varchar(100),@tamt varchar(100),@narr varchar(100)


DECLARE bankdetscursor CURSOR READ_ONLY FOR
SELECT a.Trans_Dt,a.Chq_No,b.AC_Name,c.AC_Name,a.Dr_Code,a.Cr_Code,a.Reco_Date,a.Reco,a.Amount,a.Narr1 from Ac_Trans a join Mst_Account b on a.Dr_Code=b.AC_Code join Mst_Account c on a.Cr_Code=c.AC_Code where a.Member_Code=@memcode and a.Year_Code=@yearcode and Book_Type1='BK'  and (Dr_Code=@bankc or Cr_Code=@bankc) and a.Trans_Dt>=@Fromdate and a.Trans_Dt<=@Todate and a.Reco=1

       OPEN bankdetscursor
        FETCH NEXT FROM bankdetscursor INTO  @dt ,@chqno ,@drnmae ,@crname ,@drcode,@crcode,@recodt,@recostats,@tamt,@narr
        while @@FETCH_STATUS=0
        begin 
        
		if(@drcode=@bankc)
		begin


		    set @cramt = @tamt;
               set @acnm =@crname;
			   set @dbamt = '0';

		end

		if(@crcode=@bankc)
		begin


		    set @dbamt = @tamt;
               set @acnm =@drnmae;
			   set @cramt='0';

			   end

			   declare @recdt varchar(100);
			   set @recdt='';
			   if(@recostats='1')
			   begin
			   
                   set @recdt=@recodt;
			   end

			    

			   insert into #tmptable3(dt,chqno,particulars,Recdt,debit,credit,Narration)values(@dt,@chqno,@acnm,@recdt,@dbamt,@cramt,@narr)
		

		FETCH NEXT FROM bankdetscursor INTO  @dt ,@chqno ,@drnmae ,@crname ,@drcode,@crcode,@recodt,@recostats,@tamt,@narr
 		end

		close bankdetscursor
		deallocate bankdetscursor

		select * from #tmptable3
	end
























GO
/****** Object:  StoredProcedure [dbo].[R_JournalVoucher]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[R_JournalVoucher]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[R_JournalVoucher] AS' 
END
GO


ALTER Procedure [dbo].[R_JournalVoucher]
(
  @Fromdate varchar(100),
  @Todate   varchar(100),
  @yearcode varchar(100),
  @membercode varchar(Max),
  @Accountcode varchar(Max)
 -- @drcode varchar(100),
--  @crcode varchar(100)

)

As
if(@Accountcode=''   )
Begin
SET NOCOUNT ON;
select  Distinct (AC_Trans.Vouch_No) As[BillVouch_no],
     --  AC_Trans.Trans_Dt As[Date],
	   AC_Trans.Trans_Dt As[Date],
	   madr.AC_Name As[Debit],
	   macr.AC_Name As[Credit],
	   ISNULL(cast(AC_Trans.Amount as decimal(10,2)),0) As[Amount],
	  -- Round(ISNULL(AC_Trans.Amount,0),2) As[Amount],
	   CONCAT(AC_Trans.Narr1,'',AC_Trans.Narr2,'',AC_Trans.Narr3) As[Narration]
	   --AC_Trans.Narr1 As[Narration]
 From AC_Trans 
 Join Mst_Account madr
 on
 madr.AC_Code =AC_Trans.Dr_Code and madr.Member_Code=@membercode and madr.Year_Code=@yearcode
 Join Mst_Account macr
 on
 macr.AC_Code=AC_Trans.Cr_Code and macr.Member_Code=@membercode and macr.Year_Code=@yearcode

 where Book_Type1='JV' and AC_Trans.Member_Code= @membercode and AC_Trans .Year_Code=@yearcode and Trans_Dt>=@Fromdate and Trans_Dt<=@Todate
End

else if (@Accountcode !='')
Begin
select distinct (AC_Trans.Vouch_No) As[Bill/Vouch_no],
       AC_Trans.Trans_Dt As[Date],
	   madr.AC_Name As[Debit],
	   macr.AC_Name As[Credit],
	    ISNULL(cast(AC_Trans.Amount as decimal(10,2)),0) As[Amount],
	  -- ISNULL(AC_Trans.Amount,0) As[Amount],
	   CONCAT(AC_Trans.Narr1,'',AC_Trans.Narr2,'',AC_Trans.Narr3) As[Narration]
	 --  AC_Trans.Narr1 As[Narration]
 From AC_Trans 
 Join Mst_Account madr
 on
 madr.AC_Code =AC_Trans.Dr_Code and  madr.Member_Code=@membercode and madr.Year_Code=@yearcode
 Join Mst_Account macr
 on
 macr.AC_Code=AC_Trans.Cr_Code and macr.Member_Code=@membercode and macr.Year_Code=@yearcode
 where
 Book_Type1='JV' and
   AC_Trans.Member_Code=@membercode and AC_Trans .Year_Code=@yearcode and
  Trans_Dt>=@Fromdate and Trans_Dt<=@Todate and 
 (AC_Trans.Cr_Code   in (SELECT Value FROM membercodestable(@Accountcode ,',')) or  AC_Trans.Dr_Code   in (SELECT Value FROM membercodestable(@Accountcode ,',')) )
End
 
























GO
/****** Object:  StoredProcedure [dbo].[Report_Bank_Reconsilation]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Report_Bank_Reconsilation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Report_Bank_Reconsilation] AS' 
END
GO

 -- EXECUTE  Report_Bank_Reconsilation 'S0027','D0002','1120172018','2017-04-01','2018-03-31',0
ALTER procedure [dbo].[Report_Bank_Reconsilation] 


(
  @BankCode VARCHAR(Max) null,
  @MemberCode VARCHAR(Max) null,
  @YearCode VARCHAR(20) null,
  @FromDate DateTime null,
  @ToDate   Datetime null,
  @IsReconcile int
)
AS
BEGIN
	SET NOCOUNT ON;

	
			--select NULL 'Date', '' 'Cheque No' ,AC_Name  'Particular', NULL  'RecoDate',0 'Debit', 0 'Credit','' 'Narration',  1 sort 
			--from Mst_Account 
			--where AC_Code = @BankCode
			--UNION
			--SELECT NULL 'Date','' 'Cheque No' , 'Add: Cheque issued but not cleared' Particular, NULL 'RecoDate',NULL 'Debit',NULL 'Credit','' 'Narration',2 sort   
			--from AC_Trans T1

			--UNION

			SELECT	T1.Trans_No,
                    T1.Sr_No,
			        convert (Varchar,T1.Trans_Dt,103) 'Trans_Dt',
					t1.Chq_No 'Cheque No',
					T2.AC_Name,
				    convert (Varchar,Reco_Date,103)'RecoDate',
					Amount 'Debit',
					0 'Credit',
					Concat("Narr1","Narr2","Narr3") as 'Narration',
					1 sort   
					from AC_Trans T1
					INNER JOIN Mst_Account T2 ON T2.AC_Code=t1.Dr_Code  AND T1.Member_Code=@MemberCode
					WHERE  T1.Book_Type1 IN('BK','RC') and T2.Member_Code= @MemberCode and T2.Year_Code=@YearCode and  
					T1.Trans_Dt BETWEEN @FromDate AND @ToDate  AND
					(T1.Dr_Code= @BankCode OR T1.Cr_Code= @BankCode) 
					AND T1.Reco = @IsReconcile
			
			--UNION

			--SELECT NULL 'Date','' 'Cheque No' , 'Less: Cheque Deposited but not cleared' Particular, NULL 'RecoDate',NULL 'Debit',NULL 'Credit','' 'Narration',4 sort   from AC_Trans T1

			UNION

			SELECT  T1.Trans_No,
                    T1.Sr_No,
			        convert (Varchar,T1.Trans_Dt,103) 'Trans_Dt',
				    t1.Chq_No  'Cheque No' ,
					T3.AC_Name,
					convert (Varchar,Reco_Date,103) 'RecoDate', 
					0 'Debit',
					Amount 'Credit',
					Concat("Narr1","Narr2","Narr3") as 'Narration',
					2 sort  from 
					AC_Trans T1
					INNER JOIN Mst_Account T3 ON T3.AC_Code=t1.Cr_Code  AND T1.Member_Code=@MemberCode
					where  T1.Book_Type1 IN('BK','RC') and T3.Member_Code=@MemberCode and T3.Year_Code=@YearCode and 
					T1.Trans_Dt BETWEEN @FromDate AND @ToDate  AND
					(T1.Cr_Code=@BankCode or T1.Dr_Code=@BankCode)
					AND T1.Reco = @IsReconcile
					order by sort
		
END























GO
/****** Object:  StoredProcedure [dbo].[ReTransfer_Account_Master]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ReTransfer_Account_Master]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[ReTransfer_Account_Master] AS' 
END
GO



--Execute ReTransfer_Account_Master '1120172018','1220182019','C0001','04/01/2017','03/31/2018'

ALTER  Procedure [dbo].[ReTransfer_Account_Master]
(
	@PreviousYearcode varchar(10),
	@NextYearcode varchar(10),
	@Membercode varchar(10),
	@FromDate Datetime,
	@ToDate Datetime
)
AS
 BEGIN
	
	
	Create Table #tempBalance
	(
		Trans_No varchar(500),
		Entry_Type varchar(20),
		[Bill_No] varchar(500),
		[Date] DateTime,
		[Check_Number] varchar(1000),
		Ac_Code varchar(10),
		Ac_Name varchar(500),
		Sub_Ac_Code varchar(10),
		Sub_Ac_Name varchar(500),
		Debit_Amount float,
		Credit_Amount float,
		Balance float,  
		Group_id int,
		Groupname Varchar(500),
		Narration Varchar(500),
		BookType varchar(10),
		InvestementTypeCode int,
		Effect varchar(1),
		Effect1 varchar(1),
		EntryType Varchar(10),
		SrNo Varchar(Max)
	)

	Insert into #tempBalance
	Execute [dbo].[rpt_Account_Ledger_Report] @Membercode,@PreviousYearcode,'','',@FromDate,@ToDate,1

	--Select * from #tempBalance

	---------------- Matched Accounts ------------------------- 
		SELECT MAPrev.*, 'Account matched' as 'Remark', NULL as 'DebitCreditIndication'  
	INTO #TempMatchAccount
	FROM MSt_Account MAPrev
	LEFT Join (
				SELECT * 
				FROM MSt_Account 
				WHERE Member_Code = @Membercode and year_Code = @NextYearcode
				)  MANext 
		ON  MAPrev.Ac_Name = MANext.Ac_Name AND MAPRev.Grp_Name = MANext.Grp_Name 
	WHERE MAPrev.Member_Code = @Membercode and MAPrev.year_Code = @PreviousYearcode  
	
	------ Update balances	
	Update MA
	SET MA.Op_Bal = abs(ISNULL(TB.Balance,0)),	
		MA.OP_Cal = CASE WHen TB.Balance > 0 THEN 1 WHEN  TB.Balance < 0 THEN -1 ELSE 0 END
	From MST_Account MA
	LEFT JOIN 
			(
				Select  Ac_Code,
						Ac_Name,
						Sum(Debit_Amount) as debit,
						Sum(Credit_Amount) as credit,
						(Sum(Debit_Amount) - Sum(Credit_Amount)) as 'Balance',
						Group_id,
						Groupname,
						Effect,
						Effect1 
				From #tempBalance 
				Where Effect in ('A','L','D','C') 
				Group By Ac_Code,Ac_Name,Group_id,Groupname,Effect,Effect1	
				Having (Sum(Debit_Amount) - Sum(Credit_Amount)) != 0
				--Order by Ac_Name

			) TB
	ON MA.Ac_Name = TB.Ac_Name AND MA.Grp_Name  = TB.Groupname 
	Where MA.Member_Code = @Membercode AND MA.Year_Code = @NextYearcode
	
	

----------------- UnMatched Account -----------------------
		SELECT MAPrev.*, 'Account name : ' + MAPrev.Ac_Name + ' and Account Code : ' + MaPrev.Ac_Code + ' not matched in F.Y. - ' + @NextYearcode   as 'Remark', '  ' as 'DebitCreditIndication' 
	INTO #TempUnMatchAccount
	FROM MSt_Account MAPrev
	LEFT JOIN (
					SELECT * 
					FROM MSt_Account 
					WHERE Member_Code = @Membercode and year_Code = @NextYearcode
				)  MANext 
		ON  MAPrev.Ac_Name = MANext.Ac_Name AND MAPRev.Grp_Name = MANext.Grp_Name 
	WHERE MAPrev.Member_Code = @Membercode and MAPrev.year_Code = @PreviousYearcode  AND MANext.Member_Code IS NULL


	--Brokerage Master Transfer Start--
	  
      DELETE FROM Brokerage_Master WHERE AC_code IN(Select Ac_code from Mst_Account Where Member_code=@Membercode AND Year_Code=@PreviousYearcode AND Grp_Name='BROKER')
      AND Member_Code=@Membercode and Year_Code=@NextYearcode
	 
	  INSERT INTO Brokerage_Master(AC_code,Investment_Type,Buy_Brokrage,Sell_Brokerage,Per_Order,Max_Brokrage,Min_Brokrge,Member_Code)
      SELECT AC_code,Investment_Type,Buy_Brokrage,Sell_Brokerage,Per_Order,Max_Brokrage,Min_Brokrge,Member_Code 
      from Brokerage_Master Where Member_Code=@Membercode and Year_Code=@PreviousYearcode

	  Update Brokerage_Master Set Year_Code=@NextYearcode where Member_Code=@Membercode and Year_Code Is Null
	
	--Brokerage Master Transfer END--

	-- Expense Master Mapping Transfer

	  DELETE FROM BrokerBill_Format_Expense  
      WHERE Tax_Name IN (SELECT Tax_Name FROM BrokerBill_Format_Expense WHERE Member_code=@Membercode AND Year_Code=@PreviousYearcode)
      AND BrokerBill_Format_No IN(SELECT BrokerBill_Format_No FROM BrokerBill_Format_Expense 
      WHERE Member_code=@Membercode AND Year_Code=@PreviousYearcode)  
      AND Member_code=@Membercode AND year_code=@NextYearcode

	  INSERT INTO BrokerBill_Format_Expense(Member_code,Tax_code,year_code,InvestmentType,Tax_Name,BrokerBill_Format_No)
	  SELECT Member_code,Tax_code,@NextYearcode,InvestmentType,Tax_Name,BrokerBill_Format_No
	  FROM BrokerBill_Format_Expense WHERE Member_Code=@Membercode and year_code=@PreviousYearcode

	---- Expense Master Mapping Transfer END--

	--Select * from #TempUnMatchAccount

	Update TA
	SET TA.Op_Bal = ISNULL(TB.Balance,0),	
		TA.DebitCreditIndication = CASE WHen TB.Balance > 0 THEN 'DR' WHEN  TB.Balance < 0 THEN 'CR' ELSE '  ' END,
		TA.OP_Cal = CASE WHen TB.Balance > 0 THEN 1 WHEN  TB.Balance < 0 THEN -1 ELSE 0 END
	From #TempUnMatchAccount TA
	LEFT JOIN 
			(
				Select  Ac_Code,
						Ac_Name,
						Sum(Debit_Amount) as debit,
						Sum(Credit_Amount) as credit,
						Sum(Debit_Amount) - Sum(Credit_Amount) as 'Balance',
						Group_id,
						Groupname,
						Effect,
						Effect1 
				From #tempBalance 
				Where Effect in ('A','L','D','C') 
				Group By Ac_Code,Ac_Name,Group_id,Groupname,Effect,Effect1	
				Having (Sum(Debit_Amount) - Sum(Credit_Amount)) != 0
				--Order by Ac_Name

			) TB
	ON TA.Ac_Name = TB.Ac_Name AND TA.Grp_Name  = TB.Groupname --AND MA.Member_Code = @Membercode AND MA.Year_Code = @NextYearcode
	
	SELECT Grp_Name,
		   Ac_Name,
		   Ac_Code,
		   ABS(Op_Bal) as Op_Bal,
		   DebitCreditIndication,
		   Remark
	FROM #TempUnMatchAccount 
	Order by Ac_Name

	

----------------------------------------------------------------- Balance Transfer ------------------------------------------------------------



--Execute [dbo].[rpt_Account_Ledger_Report] 'T0009','1120172018','','','04/01/2017','03/31/2018',1
--Select * from mst_Account Where Ac_Code = 'S0001'
--Select * from mst_AcGroup



--Drop table #tempBalance

END
 



GO
/****** Object:  StoredProcedure [dbo].[rpt_Account_Ledger_Report]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_Account_Ledger_Report]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[rpt_Account_Ledger_Report] AS' 
END
GO




-- execute [dbo].[rpt_Account_Ledger_Report] 'T0009','1120172018','','','04/01/2017','03/31/2018',0
ALTER Procedure [dbo].[rpt_Account_Ledger_Report]
(
 @Membercode Varchar(Max),
 @Yearcode Varchar(500),
 @Accountcode Varchar(Max),
 @Groupid Varchar(Max),
 @FromDate Varchar(50),
 @ToDate varchar(50),
 @TransFar bit=0
)
AS 
  BEGIN
  SET NOCOUNT ON;
Create Table #temp
(
	Trans_No varchar(500),
	Entry_Type varchar(20),
	[Bill_No] varchar(500),
	[Date] DateTime,
	[Check_Number] varchar(1000),
	Ac_Code varchar(10),
	Ac_Name varchar(500),
	Sub_Ac_Code varchar(10),
	Sub_Ac_Name varchar(500),
	Debit_Amount float,
	Credit_Amount float,
	Balance as 
	CAST((Credit_Amount - Debit_Amount) AS DECIMAL(16,4)),  
	Group_id int,
	Groupname Varchar(500),
	Narration Varchar(500),
	BookType varchar(10),
	InvestementTypeCode int, 
	Effect varchar(1),
    Effect1 varchar(1),
    EntryType Varchar(10),
	SrNo Varchar(Max)
	)

Create Table #Openings
(
	Trans_No varchar(500),
	Entry_Type varchar(20),
	[Bill_No] varchar(500),
	[Date] DateTime,
	[Check_Number] varchar(1000),
	Ac_Code varchar(10),
	Ac_Name varchar(500),
	Sub_Ac_Code varchar(10),
	Sub_Ac_Name varchar(500),
	Debit_Amount float,
	Credit_Amount float,
	Balance as 
	CAST((Credit_Amount - Debit_Amount) AS DECIMAL(16,4)),  
	Group_id int,
	Groupname Varchar(500),
	Narration Varchar(500),
	BookType varchar(10),
	InvestementTypeCode int,
	Effect varchar(1),
    Effect1 varchar(1),
    EntryType Varchar(10),
	SrNo Varchar(Max)
	)

	DECLARE @StartYearDate varchar(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
	
	-- Acount code Find
	create table #Account (	Ac_Code varchar(max))
	DECLARE @TempAccountCode varchar(1000)
			IF(@Accountcode = '')
				BEGIN 
					INSERT INTO #Account  Select Ac_Code FROM Mst_Account  Where Year_Code = @Yearcode And Member_Code =@Membercode						
				END
			ELSE 
					INSERT INTO #Account SELECT value FROM Fn_split(@Accountcode, ',') 

--- Group Name find
    create table #Group (Group_id varchar(max))
	DECLARE @TempGroupid varchar(1000)
			IF(@Groupid = '')
				BEGIN 
					INSERT INTO #Group  Select Grp_id FROM Mst_AcGroup					
				END
			ELSE 
					INSERT INTO #Group SELECT value FROM Fn_split(@Groupid, ',') 

--Insert only Dr Amount
Insert into #temp ( Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,
					Narration,BookType,InvestementTypeCode,Effect,Effect1,EntryType,SrNo )
select	AT.Trans_No,
		Case 
			When Book_Type1 = 'BK'  THEN  
				CASE  WHEN AT.Sub_Type1 = 'C' THEN 'CASH' ELSE  'BANK' 
			END
			WHEN Book_Type1 = 'JV' THEN  'Journal Entry'
			WHEN Book_Type1 = 'RC' THEN  'Bank Reconcilation' 
			WHEN Book_Type1 = 'IN' THEN  'Income Expense'
			WHEN Book_Type1 = 'IPO' THEN  'IPO'
			ELSE I.Entry_Type
		END as 'Entry_Type', 
		At.Vouch_No,
		Trans_Dt,
		Chq_No,
		ma.AC_Code,
		ma.AC_Name,
		AT.Cr_Code,
		(Select Top(1) Ac_Name From Mst_Account Where AC_Code = AT.Cr_Code and Mst_Account.Member_Code=@Membercode and Mst_Account.Year_Code=@Yearcode),
		Cast(SUM(Amount)AS DECIMAL(16,4)),
		0.0,
		ma.Grp_id,
		ma.Grp_Name,
		AT.Narr1 +AT.Narr2+AT.Narr3,
		At.Book_Type1,
		Case When Book_Type1 = 'BB'  THEN  I.SR_NO  ELSE -1 END ,
		ma.Effect,
		ma.Effect1,
		AT.EntryType,
		AT.Sr_No  

from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Dr_Code And ma.Member_Code = @Membercode AND ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.Grp_Id = ma.Grp_id
Where At.Book_Type1 != 'BB' and (AT.Trans_Dt  <= @ToDate AND AT.Trans_Dt>=@StartYearDate) AND (Select Count(*) From Mst_Account Where AC_Code = AT.CR_Code AND Year_Code = @Yearcode And Member_Code =@Membercode)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode and ma.AC_Code in (select AC_Code from #Account) and MAG.Grp_Id in (Select Group_id from #Group)

Group By AT.Trans_No,I.Entry_Type,At.Vouch_No,Trans_Dt,Chq_No,ma.AC_Code,ma.AC_Name,AT.Cr_Code,Amount,AT.Member_Code,MM.Member_Name,ma.Grp_id,ma.Grp_Name,
		 AT.Narr1 +AT.Narr2+AT.Narr3,Book_Type1,AT.Sub_Type1,I.SR_NO,ma.Effect,ma.Effect1,AT.EntryType,AT.Sr_No    

--Insert Into Cr Amount
Insert into #temp (	Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,
					Narration,BookType,InvestementTypeCode,Effect,Effect1,EntryType,SrNo )
select	AT.Trans_No,
		Case 
			When Book_Type1 = 'BK'  THEN  
				CASE  WHEN AT.Sub_Type1 = 'C' THEN 'CASH' ELSE  'BANK' 
			END
			WHEN Book_Type1 = 'JV'  THEN  'Journal Entry'
			WHEN Book_Type1 = 'RC'  THEN  'Bank Reconcilation' 
			WHEN Book_Type1 = 'IN'  THEN  'Income Expense'
			WHEN Book_Type1 = 'IPO' THEN  'IPO'
			ELSE I.Entry_Type
		END as 'Entry_Type', 
		At.Vouch_No,
		Trans_Dt,
		Chq_No,
		ma.AC_Code,
		ma.AC_Name,
		AT.Dr_Code,
		(Select Top(1) Ac_Name From Mst_Account Where AC_Code = AT.Dr_Code and Mst_Account.Member_Code=@Membercode and Mst_Account.Year_Code=@Yearcode),
		0.0,
		Cast(SUM(Amount)AS DECIMAL(16,4)),
		ma.Grp_id,
		ma.Grp_Name,
	    AT.Narr1 +AT.Narr2+AT.Narr3,
		At.Book_Type1,
		Case When Book_Type1 = 'BB'  THEN  I.SR_NO  ELSE -1 END,
		ma.Effect,
		ma.Effect1,
		AT.EntryType,
		AT.Sr_No       

from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Cr_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.Grp_Id = ma.Grp_id

Where At.Book_Type1 != 'BB' and (AT.Trans_Dt  <= @ToDate AND AT.Trans_Dt>=@StartYearDate) AND (Select Count(*) From Mst_Account Where AC_Code = AT.Dr_Code ANd Year_Code = @Yearcode And Member_Code =@Membercode)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode and ma.AC_Code in (select AC_Code from #Account) and  MAG.Grp_Id in(Select Group_id from #Group) 

Group By AT.Trans_No,I.Entry_Type,At.Vouch_No,Trans_Dt,Chq_No,ma.AC_Code,ma.AC_Name,AT.Dr_Code,Amount,AT.Member_Code,MM.Member_Name,ma.Grp_id,
ma.Grp_Name,AT.Narr1 +AT.Narr2+AT.Narr3,Book_Type1,AT.Sub_Type1,I.SR_NO,ma.Effect,ma.Effect1,AT.EntryType,AT.Sr_No  

-- Insert SHAREINVESTMENT /SHARE TRADING DR AMOUNT
Insert into #temp (	Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,
					Narration,BookType,InvestementTypeCode,Effect,Effect1,EntryType,SrNo)
select	AT.Trans_No,
		Case 
			When Book_Type1 = 'BK'  THEN  
				CASE  WHEN AT.Sub_Type1 = 'C' THEN 'CASH' ELSE  'BANK' 
			END
			WHEN Book_Type1 = 'JV' THEN  'Journal Entry'
			WHEN Book_Type1 = 'RC' THEN  'Bank Reconcilation' 
			WHEN Book_Type1 = 'IN' THEN  'Income Expense'
			WHEN Book_Type1 = 'IPO' THEN  'IPO'
			ELSE I.Entry_Type
		END as 'Entry_Type', 
		At.Vouch_No,
		AT.Trans_Dt,
		Chq_No,
		ma.AC_Code,
		ma.AC_Name,
		AT.Dr_Code,
		(Select Top(1) Ac_Name From Mst_Account Where AC_Code = AT.Dr_Code and Mst_Account.Member_Code=@Membercode and Mst_Account.Year_Code=@Yearcode),
		0.0,
		CASE WHEN (MAG.GRP_NAME = 'BROKER' OR REPLACE(MAG.GRP_NAME, ' ', '') = 'BROKER(C.A)') THEN (BB.Net_amt)
			 ELSE AT.Amount
		END as 'Amount',			
		ma.Grp_id,
		ma.Grp_Name,
		AT.Narr1 +AT.Narr2+AT.Narr3,
		AT.Book_Type1,
		Case When Book_Type1 = 'BB'  THEN  I.SR_NO  ELSE -1 END,
		ma.Effect,
		ma.Effect1,
		AT.EntryType,
		AT.Sr_No   
		  
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Cr_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.Grp_Id = ma.Grp_id
Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no And BB.Member_Code=@Membercode and BB.YearCode=@Yearcode

Where At.Book_Type1 = 'BB' and (AT.Trans_Dt  <= @ToDate AND AT.Trans_Dt>=@StartYearDate) AND (Select Count(*) From Mst_Account Where AC_Code = AT.Dr_Code and Year_Code = @Yearcode And Member_Code =@Membercode)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode AND ma.AC_Code in (select AC_Code from #Account) and  MAG.Grp_Id in(Select Group_id from #Group)
AND AT.EntryType != 10  and  (ma.Grp_Name!='BROKER' and  REPLACE(MAG.GRP_NAME, ' ', '') != 'BROKER(C.A)')and At.Amount!=0  
Group By AT.Trans_No,I.Entry_Type,At.Vouch_No,At.Trans_Dt,Chq_No,ma.AC_Code,ma.AC_Name,AT.Dr_Code,AT.Amount,AT.Member_Code,MM.Member_Name,MAG.GRP_NAME,BB.Net_amt,
		 ma.Grp_id,ma.Grp_Name,AT.Narr1 +AT.Narr2+AT.Narr3,Book_Type1,AT.Sub_Type1,I.SR_NO,ma.Effect,ma.Effect1,AT.EntryType,BB.Member_Code,BB.YearCode,AT.Sr_No      

-- Insert SHAREINVESTMENT /SHARE TRADING CR AMOUNT
Insert into #temp (	Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,
					Narration,BookType,InvestementTypeCode,Effect,Effect1,EntryType,SrNo )
select	AT.Trans_No,
		Case 
			When Book_Type1 = 'BK'  THEN  
				CASE  WHEN AT.Sub_Type1 = 'C' THEN 'CASH' ELSE  'BANK' 
			END
			WHEN Book_Type1 = 'JV' THEN  'Journal Entry'
			WHEN Book_Type1 = 'RC' THEN  'Bank Reconcilation' 
			WHEN Book_Type1 = 'IN' THEN  'Income Expense'
			WHEN Book_Type1 = 'IPO' THEN  'IPO'
			ELSE I.Entry_Type
		END as 'Entry_Type', 
		At.Vouch_No,
		AT.Trans_Dt,
		Chq_No,
		ma.AC_Code,
		ma.AC_Name,
		AT.Dr_Code,
		(Select Top(1) Ac_Name From Mst_Account Where AC_Code = AT.Cr_Code and Mst_Account.Member_Code=@Membercode and Mst_Account.Year_Code=@Yearcode),		
		CASE WHEN (MAG.GRP_NAME = 'BROKER' OR REPLACE(MAG.GRP_NAME, ' ', '') = 'BROKER(C.A)' ) THEN BB.Net_amt
			 ELSE AT.Amount
		END as 'Amount',
		0.0,
		ma.Grp_id,
		ma.Grp_Name,
		AT.Narr1 +AT.Narr2+AT.Narr3,
		At.Book_Type1,
		Case When Book_Type1 = 'BB'  THEN  I.SR_NO  ELSE -1 END,
		ma.Effect,
		ma.Effect1,
		AT.EntryType,
		AT.Sr_No       

from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Dr_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.Grp_Id = ma.Grp_id
Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no  And BB.Member_Code=@Membercode and BB.YearCode=@Yearcode

Where At.Book_Type1 = 'BB' and (AT.Trans_Dt  <= @ToDate AND AT.Trans_Dt>=@StartYearDate) AND (Select Count(*) From Mst_Account Where AC_Code = AT.Cr_Code AND Year_Code = @Yearcode And Member_Code =@Membercode)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode AND ma.AC_Code in (select AC_Code from #Account) and  MAG.Grp_Id in(Select Group_id from #Group)
AND AT.EntryType != 10 and (ma.Grp_Name!='BROKER' and REPLACE(MAG.GRP_NAME, ' ', '') != 'BROKER(C.A)')and  At.Amount!=0
Group By AT.Trans_No,I.Entry_Type,At.Vouch_No,At.Trans_Dt,Chq_No,ma.AC_Code,ma.AC_Name,AT.Dr_Code,At.Cr_Code,
AT.Amount,AT.Member_Code,MM.Member_Name,MAG.GRP_NAME,BB.Net_amt,ma.Grp_id,ma.Grp_Name,AT.Narr1 +AT.Narr2+AT.Narr3 ,
Book_Type1,AT.Sub_Type1,I.SR_NO,ma.Effect,ma.Effect1,AT.EntryType,BB.Member_Code,BB.YearCode,AT.Sr_No   

-- Broker Account Entry
Insert into #temp ( Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,
					Narration,BookType,InvestementTypeCode,Effect,Effect1,EntryType,SrNo )
select	AT.Trans_No,
		Case 
			When Book_Type1 = 'BK'  THEN  
				CASE  WHEN BB.Sub_Type1 = 'C' THEN 'CASH' ELSE  'BANK' 
			END
			WHEN Book_Type1 = 'JV' THEN  'Journal Entry'
			WHEN Book_Type1 = 'RC' THEN  'Bank Reconcilation' 
			WHEN Book_Type1 = 'IN' THEN  'Income Expense'
			WHEN Book_Type1 = 'IPO' THEN  'IPO'
			ELSE I.Entry_Type
		END as 'Entry_Type', 
		At.Bill_no,
		AT.Trans_Dt,
	    '',	
		ma.AC_Code,
		ma.AC_Name,	
		'',		
		CASE WHEN  I.SR_NO='0' THEN 'SHARE TRANSACTION A/C'
		     WHEN  I.SR_NO='1' THEN 'F & O SHARE TRADING A/C'
		     WHEN  I.SR_NO='2' THEN 'MUTUAL FUND INVESTMENT A/C' 
		     WHEN  I.SR_NO='3' THEN 'COMMODITY SHARE TRADING A/C' 
		     WHEN  I.SR_NO='4' THEN 'CURRENCY SHARE TRADING A/C'
		     WHEN  I.SR_NO='5' THEN 'NCDEX SHARE TRADING A/C'
	     	 ELSE 'SHARE TRANSACTION A/C' 
			 END As'Sub_Ac_Name',

		CASE WHEN At.Ac_Type = 'D' THEN At.Net_amt ELSE 0.0 END,
		CASE WHEN At.Ac_Type = 'C' THEN At.Net_amt ELSE 0.0 END,
		ma.Grp_id,
		ma.Grp_Name,
		'',
		Book_Type1,
		Case When Book_Type1 = 'BB'  THEN  I.SR_NO  ELSE -1 END,
		ma.Effect,
		ma.Effect1,
		BB.EntryType,
		'' 
		   
from BrokerBill AT
Join Ent_EntryTypes I On I.SR_NO = AT.isFNOBill
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Broker_Code And ma.Member_Code = @Membercode and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.Grp_Id = ma.Grp_id
Inner Join AC_Trans BB ON  At.Trans_No = BB.Trans_no  AND BB.Member_Code=@Membercode AND BB.Year_Code=@Yearcode

Where At.Book_Type = 'BB' and (AT.Trans_Dt  <= @ToDate AND AT.Trans_Dt>=@StartYearDate ) --AND (Select Count(*) From Mst_Account Where AC_Code = AT.Cr_Code)  > 0 
AND AT.Member_Code =  @Membercode AND At.YearCode = @Yearcode and ma.AC_Code in (select AC_Code from #Account) and  MAG.Grp_Id in(Select Group_id from #Group)
AND BB.EntryType != 10  
Group By AT.Trans_No,I.Entry_Type,At.Bill_no,At.Trans_Dt,ma.AC_Code,ma.AC_Name,AT.Broker_Code,
AT.Member_Code,MM.Member_Name, At.isFNOBill,ma.Grp_id,ma.Grp_Name,AT.Ac_Type,AT.Net_amt,Book_Type1,BB.Sub_Type1,I.SR_NO,
ma.Effect,ma.Effect1,BB.EntryType,BB.Member_Code,BB.Year_Code
Order by At.Trans_Dt

-- Insert  Expense Dr Amount
Insert into #temp (	Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,
					Narration,BookType,InvestementTypeCode,Effect,Effect1,EntryType,SrNo)
select	AT.Trans_No,
		Case 
			When Book_Type1 = 'BK'  THEN  
				CASE  WHEN AT.Sub_Type1 = 'C' THEN 'CASH' ELSE  'BANK' 
			END
			WHEN Book_Type1 = 'JV' THEN  'Journal Entry'
			WHEN Book_Type1 = 'RC' THEN  'Bank Reconcilation' 
			WHEN Book_Type1 = 'IN' THEN  'Income Expense'
			WHEN Book_Type1 = 'IPO' THEN  'IPO'
			ELSE I.Entry_Type
		END as 'Entry_Type', 
		At.Vouch_No,
		AT.Trans_Dt,
		Chq_No,
		ma.AC_Code,
		ma.AC_Name,
		AT.Cr_code,
		(Select Top(1) Ac_Name From Mst_Account Where AC_Code = AT.Cr_code and Mst_Account.Member_Code=@Membercode and Mst_Account.Year_Code=@Yearcode),
		CASE WHEN At.ExpenseType = 'A' THEN At.Amount ELSE 0.0 END,
		0.0,--CASE WHEN At.ExpenseType = 'L' THEN At.Amount ELSE 0.0 END,
		ma.Grp_id,
		ma.Grp_Name,
		AT.Narr1 +AT.Narr2+AT.Narr3,
		AT.Book_Type1 ,
		Case When Book_Type1 = 'BB'  THEN  I.SR_NO  ELSE -1 END,
		ma.Effect,
		ma.Effect1,
		AT.EntryType,
		AT.Sr_No     
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Dr_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.Grp_Id = ma.Grp_id
Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no  AND BB.Member_Code=@Membercode And BB.YearCode=@Yearcode

Where At.Book_Type1 = 'BB' and (AT.Trans_Dt  <= @ToDate AND AT.Trans_Dt>=@StartYearDate) AND (Select Count(*) From Mst_Account Where AC_Code = AT.Dr_Code AND Year_Code = @Yearcode And Member_Code =@Membercode)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode and ma.AC_Code in (select AC_Code from #Account) and  MAG.Grp_Id in(Select Group_id from #Group)
AND AT.EntryType = 10  

Group By AT.Trans_No,I.Entry_Type,At.Vouch_No,At.Trans_Dt,Chq_No,ma.AC_Code,ma.AC_Name,AT.Dr_Code, AT.Cr_Code,AT.Amount,AT.Member_Code,MM.Member_Name,
 At.ExpenseType,ma.Grp_id,ma.Grp_Name,AT.Narr1 +AT.Narr2+AT.Narr3 ,Book_Type1,Sub_Type1,I.SR_NO,ma.Effect,ma.Effect1,AT.EntryType,BB.Member_Code,BB.YearCode,AT.Sr_No    

-- Insert Expense Cr Amount 
Insert into #temp (	Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,
				Narration,BookType,InvestementTypeCode,Effect,Effect1,EntryType,SrNo)
select	AT.Trans_No,
	Case 
		When Book_Type1 = 'BK'  THEN  
				CASE  WHEN AT.Sub_Type1 = 'C' THEN 'CASH' ELSE  'BANK' 
			END
		WHEN Book_Type1 = 'JV' THEN  'Journal Entry'
		WHEN Book_Type1 = 'RC' THEN  'Bank Reconcilation' 
		WHEN Book_Type1 = 'IN' THEN  'Income Expense'
		WHEN Book_Type1 = 'IPO' THEN  'IPO'
		ELSE I.Entry_Type
	END as 'Entry_Type', 
	At.Vouch_No,
	AT.Trans_Dt,
	Chq_No,
	ma.AC_Code,
	ma.AC_Name,
	AT.Dr_code,
	(Select Top(1) Ac_Name From Mst_Account Where AC_Code = AT.Dr_code and Mst_Account.Member_Code=@Membercode and Mst_Account.Year_Code=@Yearcode),
	0.0,--CASE WHEN At.ExpenseType = 'A' THEN At.Amount ELSE 0.0 END,
	CASE WHEN At.ExpenseType = 'L' THEN At.Amount ELSE 0.0 END,
	ma.Grp_id,
	ma.Grp_Name,
	AT.Narr1 +AT.Narr2+AT.Narr3,
	AT.Book_Type1 ,
	Case When Book_Type1 = 'BB'  THEN  I.SR_NO  ELSE -1 END,
	ma.Effect,
    ma.Effect1,
	AT.EntryType,
	AT.Sr_No     

from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Cr_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.Grp_Id = ma.Grp_id
Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no  AND BB.Member_Code=@Membercode And BB.YearCode=@Yearcode

Where At.Book_Type1 = 'BB' and (AT.Trans_Dt  <= @ToDate AND AT.Trans_Dt>=@StartYearDate) AND (Select Count(*) From Mst_Account Where AC_Code = AT.Cr_Code and Year_Code = @Yearcode And Member_Code =@Membercode)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode and ma.AC_Code in (select AC_Code from #Account) and  MAG.Grp_Id in(Select Group_id from #Group)
AND AT.EntryType = 10  

Group By AT.Trans_No,I.Entry_Type,At.Vouch_No,At.Trans_Dt,Chq_No,ma.AC_Code,ma.AC_Name,AT.Dr_Code, AT.Cr_Code,AT.Amount,AT.Member_Code,MM.Member_Name,
At.ExpenseType,ma.Grp_id,ma.Grp_Name,AT.Narr1 +AT.Narr2+AT.Narr3 ,Book_Type1,Sub_Type1,I.SR_NO,ma.Effect,ma.Effect1,AT.EntryType,BB.Member_Code,BB.YearCode,AT.Sr_No   

Insert into #Openings (	Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,
						Narration,BookType,InvestementTypeCode,Effect,Effect1,EntryType,SrNo)
 select		'',
			'Opening' as 'Entry_Type', 
			'',
			@fromdate,
			'',
			ma.AC_Code,
			ma.AC_Name,
			'',
			'',
			CASE
				WHEN  ma.Op_Cal = 1 Then  ma.Op_Bal ELSE 0.0
			END,
			CASE
				WHEN  ma.Op_Cal = -1 Then  ma.Op_Bal ELSE 0.0
			END,
			ma.Grp_id,
			ma.Grp_Name,
			'',
			'',
			0,
			ma.Effect,
            ma.Effect1, 
			'',
			'' 
	from Mst_Account ma
	Join Mst_Member MM On MM.Member_Code=MA.Member_Code 
	Join Mst_AcGroup MAG On MAG.Grp_Id=ma.Grp_id
	where ma.Op_Bal != 0 And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
	and ma.AC_Code in (select AC_Code from #Account) and MAG.Grp_Id in(Select Group_id from #Group)
	UNION All 
	Select  '',
			'Opening' as 'Entry_Type', 
			'',
			@fromdate,
			'',
			t.AC_Code,
			t.AC_Name,
			'',
			'',
			t.Debit_Amount,
			t.Credit_Amount,
			t.Group_id,
			t.Groupname,
			'',
			'',
			0,
			t.Effect,
            t.Effect1,
			'',
			''  
	From #temp t
	where Balance !=0 and t.Date < @FromDate  --and t.Date!=@FromDate
	--Select * from  #Openings 
	--Select * from #temp
		
	Insert into #temp (	Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,
						Narration,BookType,InvestementTypeCode,Effect,Effect1,EntryType,SrNo)
	Select  Trans_No,
			Entry_Type,
			[Bill_No],
			[Date],
			[Check_Number],
			Ac_Code,
			Ac_Name,
			Sub_Ac_Code,
			Sub_Ac_Name,
			CASE 
				WHEN (Sum(Debit_Amount) - Sum(Credit_Amount)) > 0  THEN ABS((Sum(Debit_Amount) - Sum(Credit_Amount))) ELSE 0 
			END,
			CASE 
				WHEN (Sum(Debit_Amount) - Sum(Credit_Amount)) < 0  THEN ABS((Sum(Debit_Amount) - Sum(Credit_Amount))) ELSE 0 
			END,
			max(Group_id),
			Groupname,
			Narration,
			BookType,
			InvestementTypeCode,
			Effect,
            Effect1,
			EntryType ,
			''  
	from #Openings	

	Group By Trans_No,Entry_Type,[Bill_No],[Check_Number],[Date],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Groupname,
	Narration,BookType,InvestementTypeCode,Effect,Effect1,EntryType  	
	Select 
			Trans_No,
			Entry_Type,
			[Bill_No],
			[Date],
			[Check_Number],
			Ac_Code,
			LTRIM(RTRIM(Ac_Name)) AS 'Ac_Name',
			Sub_Ac_Code,
			Sub_Ac_Name,
			Debit_Amount,
			Credit_Amount,
			Balance,  
			Group_id,
			Groupname,
			Narration,
			BookType,
			InvestementTypeCode,
			Effect,
            Effect1,
			EntryType,
			SrNo      
	from #temp  t
	where Balance !=0 and t.Date >= @FromDate    --and t.Date!=@FromDate
	Order by Ac_Name,Date,Trans_No,Ac_Code,Groupname,SrNo

if @TransFar=0
BEGIN
Select AT.ExpenseType, At.Trans_No,Round(At.Amount,4) as 'Amount',Ma.AC_Name,Bt.Bill_no 
FROM  AC_Trans AT
JOIN Mst_Account MA ON Ma.AC_Code = (CASE WHEN AT.ExpenseType = 'A' THEN AT.Dr_Code WHEN AT.ExpenseType = 'L' THEN At.Cr_Code END) 
AND MA.Member_Code = @Membercode AND MA.Year_Code = @Yearcode
JOIN BrokerBill_Trans BT on At.Trans_No = Bt.Trans_No AND  BT.Member_code = @Membercode  and BT.YearCode = @Yearcode
WHERE AT.EntryType = 10
AND AT.Year_Code = @yearcode
AND bt.TransType != 'Opening'
AND AT.Member_Code = @Membercode
Group by Bt.Bill_no, ma.AC_Name, At.Trans_No,AT.ExpenseType,At.Amount Having At.Amount > 0 order by 5,1,2
END
Drop Table #temp
Drop Table #Account
end




























GO
/****** Object:  StoredProcedure [dbo].[rpt_Account_Master]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_Account_Master]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[rpt_Account_Master] AS' 
END
GO
--exec rpt_Account_Master '','1','A0001','1120182019','BANK,BROKER'


ALTER PROCEDURE [dbo].[rpt_Account_Master]
(
@Ac_code Varchar(max),
@WithDeatils int,
@Membercode Varchar(max),
@Yearcode Varchar(max),
@Groupwise Varchar(max)
)
As
 BEGIN
 SET NOCOUNT ON;
			DECLARE @sqlstr AS NVARCHAR(max)
			DECLARE @sqlstr1 AS NVARCHAR(max)
			DECLARE @sqlstr2 AS NVARCHAR(max)
			

			IF(@Groupwise <> '')
				BEGIN
					SET @sqlstr2 = 'Select '''' as ''Ac_code'',''Group Name'' as ''Account Header'',Grp_Name as ''A/c Name'', '''' as ''Opening Balance'','''' as ''Op. Balance'','''' as ''Debit/Credit'',1 ''sort'' ,Grp_Name as ''Group_Name'''
					SET @sqlstr2 = @sqlstr2 + '  from Mst_Account' 
					SET @sqlstr2 = @sqlstr2 + ' WHERE Mst_Account.Grp_Name IN(SELECT value FROM membercodestable ( '+ Char(39) + @Groupwise + Char(39) + ',' + Char(39) + ',' + Char(39) + ')) '
					SET @sqlstr2  = @sqlstr2 + ' and Member_Code= ''' + @Membercode + ''''
					SET @sqlstr2  = @sqlstr2 + ' and Year_Code='''+@Yearcode+''''				
					SET @sqlstr2 = @sqlstr2 + ' and Mst_Account.InternalEntry=0 group by Grp_Name' 			
					 
				 END

			 	      
		    IF(@Ac_code <> '')
			BEGIN  
				if(@Groupwise = '')	
					BEGIN
						SET @sqlstr = 'Select AC_Code,''A/c Name'' as ''Account Header'',AC_Name ,''Opening Balance'' as ''Opening Balance'' '
						SET @sqlstr =  @sqlstr + ' ,Op_Bal, Case when Op_Cal = -1 Then ''C'' ELSE ''D'' END as ''Debit/Credit'', 2 ''sort'' ,Grp_Name as ''Group_Name'''
						SET @sqlstr =  @sqlstr + '    from Mst_Account'
				
						SET @sqlstr1  =  ' where Mst_Account.AC_Code in (SELECT value FROM membercodestable ( '+ Char(39) + @Ac_code + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  '
						SET @sqlstr1  =	@sqlstr1 + ' and Mst_Account.InternalEntry=0 '
					--	SET @sqlstr1  =	@sqlstr1 + ' and Op_Bal !=0 '
						SET @sqlstr1  = @sqlstr1 + ' and Member_Code= ''' + @Membercode + ''''
						SET @sqlstr1  = @sqlstr1 + ' and Year_Code='''+@Yearcode+''''
						SET @sqlstr =@sqlstr   + @sqlstr1				
		         	END
				ELSE
					BEGIN
						SET @sqlstr = @sqlstr2 + ' UNION Select AC_Code,''A/c Name'' as ''Account Header'',AC_Name ,''Opening Balance'' as ''Opening Balance'' '
						SET @sqlstr =  @sqlstr + ' ,Op_Bal, Case when Op_Cal = -1 Then ''C'' ELSE ''D'' END as ''Debit/Credit'', 2 ''sort'' ,Grp_Name as ''Group_Name'''
						SET @sqlstr =  @sqlstr + '    from Mst_Account'
				
						SET @sqlstr1  =  ' where Mst_Account.AC_Code in (SELECT value FROM membercodestable ( '+ Char(39) + @Ac_code + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  '
						SET @sqlstr1  =	@sqlstr1 + ' and Mst_Account.InternalEntry=0 '
					--	SET @sqlstr1  =	@sqlstr1 + ' and Op_Bal !=0 '
						SET @sqlstr1  = @sqlstr1 + ' and Member_Code= ''' + @Membercode + ''''
						SET @sqlstr1  = @sqlstr1 + ' and Year_Code='''+@Yearcode+''''
						SET @sqlstr = @sqlstr   + @sqlstr1
					END		
				 END
		    IF(@Ac_code ='')
			BEGIN	
			    if(@Groupwise = '')	
					BEGIN
						SET @sqlstr= 'Select AC_Code,''A/c Name'' as ''Account Header'',AC_Name ,''Opening Balance'' as ''Opening Balance'' '
						SET @sqlstr= @sqlstr + ' ,Op_Bal, Case when Op_Cal = -1 Then ''C'' ELSE ''D'' END as ''Debit/Credit'', 2 ''sort'',Grp_Name as ''Group_Name'' '
						SET @sqlstr = @sqlstr + '   from Mst_Account '
						SET @sqlstr1 =   ' Where Mst_Account.InternalEntry=0'
						--SET @sqlstr1 = @sqlstr1 + ' and Op_Bal !=0 ' 
						SET @sqlstr1  = @sqlstr1 + ' and Member_Code= ''' + @Membercode + ''''
						SET @sqlstr1  = @sqlstr1 + ' and Year_Code='''+@Yearcode+''''
						SET @sqlstr = @sqlstr   + @sqlstr1
					END
				ELSE     
					BEGIN 
						SET @sqlstr = @sqlstr2 + ' UNION  Select AC_Code,''A/c Name'' as ''Account Header'',AC_Name ,''Opening Balance'' as ''Opening Balance''  '
						SET @sqlstr= @sqlstr + ' ,Op_Bal, Case when Op_Cal = -1 Then ''C'' ELSE ''D'' END as ''Debit/Credit'', 2 ''sort'', Grp_Name as ''A/c Name'' '
						SET @sqlstr = @sqlstr + '   from Mst_Account '
						SET @sqlstr1 =   ' Where Mst_Account.Grp_Name IN(SELECT value FROM membercodestable ( '+ Char(39) + @Groupwise + Char(39) + ',' + Char(39) + ',' + Char(39) + ')) AND Mst_Account.InternalEntry=0'
					--	SET @sqlstr1 = @sqlstr1 + ' and Op_Bal !=0 ' 
						SET @sqlstr1  = @sqlstr1 + ' and Member_Code= ''' + @Membercode + ''''
						SET @sqlstr1  = @sqlstr1 + ' and Year_Code='''+@Yearcode+''''

						SET @sqlstr = @sqlstr   + @sqlstr1
					     						 
					END 
			
		END

		IF(@WithDeatils=1)
			BEGIN
				SET @sqlstr = @sqlstr + ' UNION  select AC_Code,''Contact Person'',Contact_Person,'''','''','''',3 sort,Grp_Name as ''Group_Name''   from Mst_Account '
					SET @sqlstr = @sqlstr + @sqlstr1
				SET @sqlstr = @sqlstr + ' UNION  select AC_Code,''Address'',Add1,'''','''','''',4 sort, Grp_Name as ''Group_Name''   from Mst_Account '
					SET @sqlstr = @sqlstr + @sqlstr1
				SET @sqlstr = @sqlstr + ' UNION  select AC_Code,''Tel No'',Tel_No,'''','''','''',5 sort, Grp_Name as ''Group_Name''   from Mst_Account '
					SET @sqlstr = @sqlstr + @sqlstr1
				SET @sqlstr = @sqlstr + ' UNION  select AC_Code,''Mobiler No'',Mobile_No,'''','''','''',6 sort, Grp_Name as ''Group_Name''   from Mst_Account '
					SET @sqlstr = @sqlstr + @sqlstr1
				SET @sqlstr = @sqlstr + ' UNION  select AC_Code,''Fax No'',Fax_No,'''','''','''',7 sort,Grp_Name as ''Group_Name''   from Mst_Account '
					SET @sqlstr = @sqlstr + @sqlstr1					
				SET @sqlstr = @sqlstr + ' UNION  select AC_Code,''Email Id'',email,'''','''','''',8 sort, Grp_Name as ''Group_Name''   from Mst_Account '
					SET @sqlstr =@sqlstr + @sqlstr1
					 	 
			 END
	   	if(@Groupwise <> '' AND @WithDeatils = 0)	
			SET @sqlstr = @sqlstr +  ' Order BY  Group_Name, AC_Code '
		ELSE if(@Groupwise <> '' AND @WithDeatils = 1)	
			SET @sqlstr = @sqlstr +  ' Order BY  Group_Name, AC_Code,sort '
		ELSE IF(@WithDeatils = 0)
			SET @sqlstr = @sqlstr +  ' Order BY  AC_Name '
		ELSE IF(@WithDeatils = 1)
			SET @sqlstr = @sqlstr +  ' Order BY  AC_Code,sort '

			Print @sqlstr
			EXECUTE (@sqlstr)


  end
   

























GO
/****** Object:  StoredProcedure [dbo].[rpt_BrokerBill_Register]    Script Date: 27/04/2020 7:24:06 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_BrokerBill_Register]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[rpt_BrokerBill_Register] AS' 
END
GO

--exec rpt_BrokerBill_Register 'A0001','1120192020','0','','','','04/01/2019','03/31/2020','0', '','','All','','','',''
 
ALTER PROCEDURE [dbo].[rpt_BrokerBill_Register]
(
  @Membercode Varchar(Max),
  @Yearcode varchar(1000),
  @InvestmentType Nvarchar(Max),
  @ConsultantCode Varchar(Max),
  @BrokerCode Varchar(Max),
  @ScriptCode Varchar(Max),
  @FromDate Varchar(50),
  @ToDate varchar(50),
  @HoldingType Varchar(500),
  @Billno Varchar(Max),
  @Familycode Varchar(Max),
  @TransType Varchar(50),
  @IsIntraDay Varchar(10) ,
  @flag varchar(20),
  @BSEISINNO Bit =0,
  @Script_Name varchar(max) = '',
   @BFCF Bit =0
)
AS
	BEGIN
	SET NOCOUNT ON;
        DECLARE @sqlstr AS NVARCHAR(max) 

		CREATE TABLE #Temp
		   (
		    Member_Name VARCHAR(1000),Member_code VARCHAR(1000),script_code VARCHAR(150),script_name VARCHAR(150),Qty VARCHAR(150),Bill_no VARCHAR(100),
			TransType VARCHAR(50),BillDate VARCHAR(150),Ac_Type VARCHAR(50),G_Rate VARCHAR(50) ,GrossAmount VARCHAR(1000),BrokrageAmount VARCHAR(100),
			NetRate VARCHAR(50),NetAmount VARCHAR(1000),Consultant_Name VARCHAR(1000),Consultant_code VARCHAR(500),BrokerCode VARCHAR(1000),
			Broker_Name VARCHAR(1000),Family_Code VARCHAR(1000),Family_Name VARCHAR(100),Trans_no Varchar(1000)
		   )

		DECLARE @TempMemberCode varchar(1000)
			IF(@membercode = '' AND @familycode != '')
				BEGIN 
					Select Member_Code 
					INTO #Members 
					FROM Mst_Member Where Family_Code IN (SELECT Value FROM membercodestable(@familycode,','))
			
					declare @tmp varchar(250)
					SET @tmp = ''
					select @tmp = @tmp + Member_Code + ',' from #Members
					SET @TempMemberCode = 	IsNULL((select SUBSTRING(@tmp, 0, LEN(@tmp))),'')
				END
			ELSE 
					SET @TempMemberCode = 	@membercode
			 
		IF(@InvestmentType=0 OR @InvestmentType=2)
			BEGIN
			     IF(@BSEISINNO=0 AND (@InvestmentType=0  OR @InvestmentType=2))
				 BEGIN
				 SET @sqlstr='Select MST_Script.script_code, Mst_Script.Script_Name as Script_Name'
				 END
				 ELSE IF(@BSEISINNO=1 AND @InvestmentType=0)
				 BEGIN
				         SET @sqlstr='Select MST_Script.script_code, (Mst_Script.Script_Name +''['' + Mst_Script.BSE_Code +'']''+''['' + Mst_Script.ISIN_No +'']'') as Script_Name'
				 END
			END
		ELSE
			--BEGIN
			--	SET @sqlstr = 'Select MST_Script.script_code, (Mst_Script.Script_Name + Convert(Varchar,Last_Date,103) + (case WHEN Strike_Price != 0 THEN  ''/'' + Convert(Varchar(20),Strike_Price) ELSE '''' END) + (case WHEN OptionType != '''' THEN  ''/'' + Convert(Varchar(20),OptionType) ELSE '''' END) ) As Script_Name'
			--END
			BEGIN			
					DECLARE @ScriptName varchar(500)  = 'Mst_Script.Script_Name 
						 + ''/'' +  CONVERT(VARCHAR(10),Last_Date,103) 
						 +	CASE WHEN ISNULL(Strike_Price,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),Strike_Price) ELSE '''' END
						 +  CASE WHEN ISNULL(OptionType,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),OptionType) ELSE '''' 
							END As Script_Name'
																
					SET @sqlstr = 'Select BrokerBill_Trans.script_code,' + @ScriptName + ',Last_Date as Last_Date'				
				END
		
		IF(@Familycode <> '')
			BEGIN
				SET @sqlstr= @sqlstr +', Mst_Family.Family_Name,Mst_Family.Family_Code'
			END
		ELSE
		   BEGIN
		        SET @sqlstr= @sqlstr +', Mst_Family.Family_Name,Mst_Family.Family_Code'
		   END

		IF(@ConsultantCode <> '')
			BEGIN
				SET @sqlstr = @sqlstr + ',Mst_Consultant.Consultant_code, Mst_Consultant.Consultant_Name as Consultant_Name '
			END
		ELSE
			BEGIN
				SET @sqlstr = @sqlstr + ',  Mst_Consultant.Consultant_code, Mst_Consultant.Consultant_Name'
			END

		IF(@Membercode <> '')
			BEGIN
				SET @sqlstr= @sqlstr +', Mst_Member.Member_code,Mst_Member.Member_Name'
			END 
		ELSE
		   BEGIN
		        SET @sqlstr= @sqlstr +', Mst_Member.Member_code,Mst_Member.Member_Name'
           END 

		IF(@BrokerCode<>'')
			BEGIN
				SET @sqlstr =@sqlstr + ',BrokerBill.Broker_Code, Mst_Account.AC_Name as Broker_Name'
			END
		ELSE
			BEGIN
				SET @sqlstr=@sqlstr + ', BrokerBill.Broker_Code,Mst_Account.AC_Name  as Broker_Name'
			END

		IF(@Billno <> '')
			BEGIN
				SET @sqlstr=@sqlstr + ',BrokerBill_Trans.Bill_no'
			END
		ELSE
			BEGIN
				SET @sqlstr=@sqlstr + ',BrokerBill_Trans.Bill_no'
			END
				SET @sqlstr=@sqlstr + ',(BrokerBill.Valan_code) As Settelment_No'	       
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.TransType) As Type'
				SET @sqlstr=@sqlstr + ', CONVERT(DateTime, BrokerBill_Trans.Trans_Dt,103) As ''Bill_Date'''	
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.Ac_Type) As Holding_Type'
				SET @sqlstr=@sqlstr + ',BrokerBill_Trans.Trans_No'
		
		IF(@InvestmentType = '0')
			BEGIN
				SET @sqlstr=@sqlstr + ',(MA.Ac_Name) As HoldingType '	
			END
		ELSE
			BEGIN
				SET @sqlstr=@sqlstr + ', '''' As HoldingType '	
			END
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.Qty) As Qty'
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.G_Rate) AS Gross_Rate'
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.G_Rate * BrokerBill_Trans.Qty) As Gross_Amount'
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.Brok_Amt) As Brokerage_Amount'
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.Rate) As Net_Rate'
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.Rate*BrokerBill_Trans.Qty) As Net_Amount '	
				SET @sqlstr=@sqlstr + ',ISNULL(BrokerBill_Trans.isIntraDay,0) isIntraDay '	
						
				SET @sqlstr =@sqlstr + 'inTo #temp from BrokerBill_Trans '
				SET @sqlstr=@sqlstr + ' Inner Join BrokerBill On BrokerBill.Trans_no = BrokerBill_Trans.Trans_No AND BrokerBill.Member_Code = ' +  Char(39) + @Membercode + Char(39) + 'AND BrokerBill.YearCode = '  + Char(39) + @Yearcode + Char(39) + ''
				SET @sqlstr=@sqlstr + ' Inner Join Mst_Account On Mst_Account.AC_Code = BRokerBill.Broker_Code AND Mst_Account.Member_Code = ' +  Char(39) + @Membercode + Char(39) + 'AND Mst_Account.Year_Code = '  + Char(39) + @Yearcode + Char(39) + ''
			 
		IF(ISNULL(@InvestmentType,'0')='0')
			BEGIN
				SET @sqlstr=@sqlstr + ' Inner Join Mst_Account MA On MA.AC_Code = BrokerBill_Trans.Ac_Type AND MA.Member_Code = ' +  Char(39) + @Membercode + Char(39) + 'AND MA.Year_Code = '  + Char(39) + @Yearcode + Char(39) + ''
			END
				SET @sqlstr=@sqlstr + ' Inner Join Mst_Consultant  On Mst_Consultant.Consultant_Code = BrokerBill_Trans.Consultant_code'
				SET @sqlstr=@sqlstr + ' Inner join Mst_Script On Mst_Script.Script_Code = BrokerBill_Trans.Script_Code'
				SET @sqlstr=@sqlstr + ' Inner join Mst_Member on Mst_Member.Member_Code=BrokerBill_Trans.Member_code'
				SET @sqlstr=@sqlstr + ' Inner join Mst_Family  On Mst_Family.Family_Code=Mst_Member.Family_Code'
				SET @sqlstr  = @sqlstr + ' where BrokerBill_Trans.isFNOBill = ' + Char(39) + @InvestmentType + Char(39)
				SET @sqlstr  = @sqlstr + ' and (BrokerBill_Trans.Trans_Dt between '  + Char(39) + @FromDate  + Char(39) +   ' and ' + Char(39) + @ToDate + Char(39) +')'
				SET @sqlstr  = @sqlstr + ' and BrokerBill_Trans.Ac_Type =  (select case  when ' + Char(39) +  @HoldingType + Char(39) + ' = 0 then BrokerBill_Trans.Ac_Type  else '+ @HoldingType +' end)' 
				SET @sqlstr  = @sqlstr + ' and BrokerBill_Trans.TransType = (case when ' + Char(39) +  ISNULL(@TransType,'All') + Char(39) +   '=''All'' OR  ' + Char(39) +  ISNULL(@TransType,' ') + Char(39) +   '='' ''
				THEN BrokerBill_Trans.TransType else' + Char(39) +  @TransType + Char(39) + 'end )'
							
				--SET @sqlstr = @sqlstr + ' AND ISNULL(BrokerBill_Trans.isIntraDay,0) =   (CASE WHEN ' + Char(39) +  ISNULL(@IsIntraDay,0) + Char(39) +   '= 0   THEN   ISNULL(isIntraDay,0) ELSE '  + Char(39) +   ISNULL(@IsIntraDay,0)  + Char(39) +   'END) '
				IF(@IsIntraDay != 2)
					BEGIN 
						If(@IsIntraDay = 0)
							SET @sqlstr = @sqlstr + ' AND (BrokerBill_Trans.isIntraDay IS NULL OR BrokerBill_Trans.isIntraDay = 0)'
						ELSE
							SET @sqlstr = @sqlstr + ' AND (BrokerBill_Trans.isIntraDay IS NOT NULL AND BrokerBill_Trans.isIntraDay = 1)'
					END
	
			IF(@Membercode <> '')
				 SET @sqlstr  = @sqlstr + ' and BrokerBill_Trans.Member_code in (SELECT Value FROM membercodestable(' + Char(39) + @TempMemberCode + Char(39) + ',' + Char(39) + ',' + Char(39) + ')) '
				 SET @sqlstr  = @sqlstr + ' and BrokerBill_Trans.YearCode = ''' + @Yearcode + ''''
				 SET @sqlstr  = @sqlstr + ' and BrokerBill_Trans.Bill_no != ''Opening'''

           IF(@Investmenttype='0'or @Investmenttype='2')
	           BEGIN
		           IF(@ScriptCode <> '' ) 
			          BEGIN 
				          SET @sqlstr = @sqlstr + ' and BrokerBill_Trans.Script_Code in (SELECT Value FROM membercodestable(' + Char(39) + @ScriptCode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
			         END 
	          END
		   ELSE
			   BEGIN
					IF (@Script_Name <> '' ) 
						BEGIN 
							DECLARE @ScriptNametempBroker varchar(500)  = 'Mst_Script.Script_Name 
						 + ''/'' +  CONVERT(VARCHAR(10),Last_Date,103) 
						 +	CASE WHEN ISNULL(Strike_Price,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),Strike_Price) ELSE '''' END
						 +  CASE WHEN ISNULL(OptionType,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),OptionType) ELSE '''' 
							END'
						  SET @sqlstr = @sqlstr + ' and ' + @ScriptNametempBroker + ' in (SELECT Value FROM membercodestable(' + Char(39) + @Script_Name + Char(39) + ',' + Char(39) + ',' + Char(39) + ')) ' 
						END 
		   END 
        IF(@Billno<> '')
			 BEGIN
			    SET @sqlstr= @sqlstr +' and BrokerBill_Trans.Bill_no in (SELECT Value FROM membercodestable(' + Char(39) + @Billno + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
			 END

		IF ((@Membercode <> '')  AND @ConsultantCode <> '' ) 
			BEGIN 
				SET @sqlstr = @sqlstr + ' and Mst_Consultant.Consultant_code in (SELECT Value FROM membercodestable('+ Char(39) + @consultantcode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
			END

		IF (@consultantcode <> '' ) 
			BEGIN 
				SET @sqlstr = @sqlstr +  'and Mst_Consultant.Consultant_code in (SELECT value FROM membercodestable('+ Char(39) + @consultantcode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  '
			END 

		IF(@BrokerCode <> '')
			BEGIN
				SET @sqlstr =@sqlstr + 'and BrokerBill.Broker_Code in (SELECT Value FROM membercodestable('+ Char(39) + @BrokerCode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
			END		

		IF((@BrokerCode <> '')  AND @ConsultantCode <> '')
			BEGIN
				SET @sqlstr =@sqlstr + 'and BrokerBill.Broker_Code in (SELECT Value FROM membercodestable('+ Char(39) + @BrokerCode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
			END		
		IF((@Billno<>'') AND (@ConsultantCode<>'')and @BrokerCode <> '')
			BEGIN
				SET @sqlstr =@sqlstr + '	and BrokerBill_Trans.Bill_no in (SELECT Value FROM membercodestable('+ Char(39) + @Billno + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
			END		

		IF((@Billno<>'') AND (@ConsultantCode <> '')and @BrokerCode <> '' and (@ScriptCode <> ''))
			BEGIN
				SET @sqlstr =@sqlstr + '	and BrokerBill_Trans.Bill_no in (SELECT Value FROM membercodestable('+ CHAR(39) + @Billno + CHAR(39) + ',' + CHAR(39) + ',' + CHAR(39) + '))  ' 
			END	

       IF(@Investmenttype='0'or @Investmenttype='2')
	       BEGIN
		         IF((@BrokerCode <> '') and @ScriptCode <>'')
			         BEGIN
				          SET @sqlstr =@sqlstr + 'and BrokerBill_Trans.Script_Code in (SELECT Value FROM membercodestable('+ CHAR(39) + @ScriptCode + CHAR(39) + ',' + CHAR(39) + ',' + CHAR(39) + '))  ' 
			         END	
	       END
	   ELSE
		    BEGIN
		      IF ((@Script_Name) <> '' and @BrokerCode <> '') 
						BEGIN 
							DECLARE @ScriptNametemp varchar(500)  = 'Mst_Script.Script_Name 
						 + ''/'' +  CONVERT(VARCHAR(10),Last_Date,103) 
						 +	CASE WHEN ISNULL(Strike_Price,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),Strike_Price) ELSE '''' END
						 +  CASE WHEN ISNULL(OptionType,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),OptionType) ELSE '''' 
							END'
						  SET @sqlstr = @sqlstr + ' and ' + @ScriptNametemp + ' in (SELECT Value FROM membercodestable(' + Char(39) + @Script_Name + Char(39) + ',' + Char(39) + ',' + Char(39) + ')) ' 
						END 
		    END
       IF(@BFCF='1')
	      BEGIN
	       SET @sqlstr = @sqlstr + ' AND (BrokerBill_Trans.isstock NOT IN (''BF'',''CF''))'
	      END
       IF(@Investmenttype='0'or @Investmenttype='2')
	      BEGIN
		        IF((@BrokerCode <> '') and (@ConsultantCode <>''and (@ScriptCode <> '') ))
		        	BEGIN
				          SET @sqlstr =@sqlstr + ' and BrokerBill_Trans.Script_Code in (SELECT Value FROM membercodestable('+ CHAR(39) + @ScriptCode + CHAR(39) + ',' + CHAR(39) + ',' + CHAR(39) + '))  ' 
		        	END	
		  END
	   ELSE	
		  BEGIN
		       IF((@BrokerCode <> '') and (@ConsultantCode <>''and (@Script_Name <>'')))
			       BEGIN
				      DECLARE @ScriptNameConsultnattemp varchar(500)  = 'Mst_Script.Script_Name 
						 + ''/'' +  CONVERT(VARCHAR(10),Last_Date,103) 
						 +	CASE WHEN ISNULL(Strike_Price,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),Strike_Price) ELSE '''' END
						 +  CASE WHEN ISNULL(OptionType,'''') != '''' THEN ''/'' + CONVERT(VARCHAR(10),OptionType) ELSE '''' 
							END'
						  SET @sqlstr = @sqlstr + ' and ' + @ScriptNameConsultnattemp + ' in (SELECT Value FROM membercodestable(' + Char(39) + @Script_Name + Char(39) + ',' + Char(39) + ',' + Char(39) + ')) '
			       END
		   END	

		IF((@Familycode <> ''))
			BEGIN
				SET @sqlstr =@sqlstr + ' and Mst_Family.Family_Code in (SELECT Value FROM membercodestable('+ CHAR(39) + @Familycode + CHAR(39) + ',' + CHAR(39) + ',' + CHAR(39) + '))  ' 
			END	
		 IF(@Membercode <> '')
			 BEGIN
			    SET @sqlstr = @sqlstr +  ' and Mst_Member.Member_Code in(SELECT value FROM membercodestable('+ CHAR(39) + @Membercode + CHAR(39) + ',' + CHAR(39) + ',' + CHAR(39) + '))  '		 
			 END
	
			 SET @sqlstr  = @sqlstr +' Group by '
				IF(@flag='Familywise')
					BEGIN
						SET @sqlstr  = @sqlstr + ' Mst_Family.Family_Code,Mst_Family.Family_Name, Mst_Member.Member_Code,Mst_Member.Member_Name, '
						SET @sqlstr  = @sqlstr + ' Mst_Account.AC_Name, BrokerBill.Broker_Code, BrokerBill_Trans.Bill_no,'
						SET @sqlstr  = @sqlstr + ' Mst_Script.Script_Name, Mst_Script.Script_Code, Mst_Consultant.Consultant_Name,'
						SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Consultant_code, BrokerBill_Trans.TransType,'
						SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Trans_Dt, BrokerBill_Trans.Ac_Type,BrokerBill_Trans.Qty,'
						SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.G_Rate,BrokerBill_Trans.Brok_Amt,BrokerBill_Trans.Rate,'
						SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Amount,Mst_Consultant.Consultant_code,BrokerBill.Valan_code,'
						SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Last_Date,BrokerBill_Trans.Strike_Price,BrokerBill_Trans.OptionType,'
						SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Sr_No,'
						SET @sqlstr  = @sqlstr + ' Mst_Script.BSE_Code,'
						SET @sqlstr  = @sqlstr + ' Mst_Script.ISIN_No,'
					    SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.isstock,'
						SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Trans_No,'
						SET @sqlstr  = @sqlstr + ' MST_Script.script_code ,BrokerBill_Trans.isIntraDay,BrokerBill_Trans.script_code  '
					END
				ELSE
					BEGIN
						 SET @sqlstr  = @sqlstr + ' Mst_Consultant.Consultant_Name,BrokerBill_Trans.Consultant_code,Mst_Account.AC_Name,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill.Broker_Code,BrokerBill_Trans.Bill_no,Mst_Script.Script_Name,'
						 SET @sqlstr  = @sqlstr + ' Mst_Script.Script_Code,BrokerBill_Trans.TransType,BrokerBill_Trans.Trans_Dt,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Ac_Type,BrokerBill_Trans.Qty,BrokerBill_Trans.G_Rate,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Brok_Amt, BrokerBill_Trans.Rate,BrokerBill_Trans.Amount,'
						 SET @sqlstr  = @sqlstr + ' Mst_Consultant.Consultant_code,Mst_Member.Member_Code,Mst_Member.Member_Name,'
						 SET @sqlstr  = @sqlstr + ' Mst_Family.Family_Code,Mst_Family.Family_Name,BrokerBill.Valan_code,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Last_Date,BrokerBill_Trans.Strike_Price,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Sr_No,'
						 SET @sqlstr  = @sqlstr + ' Mst_Script.BSE_Code,'
						 SET @sqlstr  = @sqlstr + ' Mst_Script.ISIN_No,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Trans_No,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.isstock,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.OptionType,MST_Script.script_code ,BrokerBill_Trans.isIntraDay,BrokerBill_Trans.script_code  '
					END

			IF(ISNULL(@InvestmentType,'0')='0')
			BEGIN
				SET @sqlstr  = @sqlstr + ',MA.AC_Name   '
			END
			
			IF(@flag='Familywise')
				SET @sqlstr=@sqlstr +    'SELECT * FROM   #temp t order by 3,10,14,2,11 '  
			ELSE
				SET @sqlstr=@sqlstr +    'SELECT * FROM   #temp t order by 10,14,2,11 '  
			
			 	
			SET @sqlstr=@sqlstr +    ' DROP TABLE #temp'	
			PRINT @sqlstr

			EXECUTE (@sqlstr)
		
			Set @sqlstr = ''
		
			SET @sqlstr = '	Select AT.ExpenseType, At.Trans_No,Round(At.Amount,4) as ''Amount'',Ma.AC_Name,Bt.Bill_no 
							FROM  AC_Trans AT
							JOIN Mst_Account MA ON Ma.AC_Code = (CASE WHEN AT.ExpenseType = ''A'' THEN AT.Dr_Code WHEN AT.ExpenseType = ''L'' THEN At.Cr_Code END) AND  MA.Member_Code = ' +  Char(39) + @Membercode + Char(39) + 'AND MA.Year_Code = '  + Char(39) + @Yearcode + Char(39) + '
							JOIN BrokerBill_Trans BT on At.Trans_No = Bt.Trans_No
							WHERE AT.ExpenseType IN (''A'',''L'')  
							AND AT.Year_Code = ''' + @yearcode + ''' 
							AND Bt.isFNOBill  =''' + @InvestmentType + '''  
							AND bt.TransType != ''Opening''
																				
							'			
			 IF(@Membercode <> '')
			 BEGIN
			    SET @sqlstr = @sqlstr +  ' and AT.Member_Code in(SELECT value FROM membercodestable('+ CHAR(39) + @Membercode + CHAR(39) + ',' + CHAR(39) + ',' + CHAR(39) + '))  '
			 END

			 SET @sqlstr = @sqlstr +  ' Group by Bt.Bill_no, ma.AC_Name, At.Trans_No,AT.ExpenseType,At.Amount Having At.Amount > 0 order by 1,2'

			 print @sqlstr

			 EXECUTE (@sqlstr)
			
END























GO
/****** Object:  StoredProcedure [dbo].[rpt_BrokerBill_Register_Scriptwise]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_BrokerBill_Register_Scriptwise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[rpt_BrokerBill_Register_Scriptwise] AS' 
END
GO

--exec rpt_BrokerBill_Register 'A0001','1120172018','0','','','','04/01/2017','03/31/2018','0', '','','All','1',''
 
ALTER PROCEDURE [dbo].[rpt_BrokerBill_Register_Scriptwise]
(
  @Membercode Varchar(Max),
  @Yearcode varchar(1000),
  @InvestmentType Nvarchar(250),
  @ConsultantCode Varchar(Max),
  @BrokerCode Varchar(Max),
  @ScriptCode Varchar(Max),
  @FromDate Varchar(50),
  @ToDate varchar(50),
  @HoldingType Varchar(500),
  @Billno Varchar(Max),
  @Familycode Varchar(Max),
  @TransType Varchar(50),
  @IsIntraDay Varchar(10) ,
  @flag varchar(20)
)
AS
	BEGIN
	SET NOCOUNT ON;
        DECLARE @sqlstr AS NVARCHAR(max) 

		CREATE TABLE #Temp
		   (
		    Member_Name VARCHAR(1000),Member_code VARCHAR(1000),script_code VARCHAR(150),script_name VARCHAR(150),Qty VARCHAR(150),Bill_no VARCHAR(100),
			TransType VARCHAR(50),BillDate VARCHAR(150),Ac_Type VARCHAR(50),G_Rate VARCHAR(50) ,GrossAmount VARCHAR(1000),BrokrageAmount VARCHAR(100),
			NetRate VARCHAR(50),NetAmount VARCHAR(1000),Consultant_Name VARCHAR(1000),Consultant_code VARCHAR(500),BrokerCode VARCHAR(1000),
			Broker_Name VARCHAR(1000),Family_Code VARCHAR(1000),Family_Name VARCHAR(100)
		   )

		DECLARE @TempMemberCode varchar(1000)
			IF(@membercode = '' AND @familycode != '')
				BEGIN 
					Select Member_Code 
					INTO #Members 
					FROM Mst_Member Where Family_Code IN (SELECT Value FROM membercodestable(@familycode,','))
			
					declare @tmp varchar(250)
					SET @tmp = ''
					select @tmp = @tmp + Member_Code + ',' from #Members
					SET @TempMemberCode = 	IsNULL((select SUBSTRING(@tmp, 0, LEN(@tmp))),'')
				END
			ELSE 
					SET @TempMemberCode = 	@membercode
			 
		IF(@InvestmentType=0 OR @InvestmentType=2)
			BEGIN
				SET @sqlstr='Select MST_Script.script_code, Mst_Script.Script_Name as Script_Name'
			END
		ELSE
			BEGIN
				SET @sqlstr = 'Select MST_Script.script_code, (Mst_Script.Script_Name + Convert(Varchar,Last_Date,103) + (case WHEN Strike_Price != 0 THEN  ''/'' + Convert(Varchar(20),Strike_Price) ELSE '''' END) +''/'' + OptionType) As Script_Name'
			END
		
		IF(@Familycode <> '')
			BEGIN
				SET @sqlstr= @sqlstr +', Mst_Family.Family_Name,Mst_Family.Family_Code'
			END
		ELSE
		   BEGIN
		        SET @sqlstr= @sqlstr +', Mst_Family.Family_Name,Mst_Family.Family_Code'
		   END


		IF(@ConsultantCode <> '')
			BEGIN
				SET @sqlstr = @sqlstr + ',Mst_Consultant.Consultant_code, Mst_Consultant.Consultant_Name as Consultant_Name '
			END
		ELSE
			BEGIN
				SET @sqlstr = @sqlstr + ',  Mst_Consultant.Consultant_code, Mst_Consultant.Consultant_Name'
			END

		IF(@Membercode <> '')
			BEGIN
				SET @sqlstr= @sqlstr +', Mst_Member.Member_code,Mst_Member.Member_Name'
			END 
		ELSE
		   BEGIN
		        SET @sqlstr= @sqlstr +', Mst_Member.Member_code,Mst_Member.Member_Name'
           END 

		IF(@BrokerCode<>'')
			BEGIN
				SET @sqlstr =@sqlstr + ',BrokerBill.Broker_Code, Mst_Account.AC_Name as Broker_Name'
			END
		ELSE
			BEGIN
				SET @sqlstr=@sqlstr + ', BrokerBill.Broker_Code,Mst_Account.AC_Name  as Broker_Name'
			END

		IF(@Billno <> '')
			BEGIN
				SET @sqlstr=@sqlstr + ',BrokerBill_Trans.Bill_no'
			END
		ELSE
			BEGIN
				SET @sqlstr=@sqlstr + ',BrokerBill_Trans.Bill_no'
			END
				SET @sqlstr=@sqlstr + ',(BrokerBill.Valan_code) As Settelment_No'	       
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.TransType) As Type'
				SET @sqlstr=@sqlstr + ',Convert(varchar, BrokerBill_Trans.Trans_Dt,103) As Bill_Date'	
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.Ac_Type) As Holding_Type'
		
		IF(@InvestmentType = '0')
			BEGIN
				SET @sqlstr=@sqlstr + ',(MA.Ac_Name) As HoldingType '	
			END
		ELSE
			BEGIN
				SET @sqlstr=@sqlstr + ', '''' As HoldingType '	
			END
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.Qty) As Qty'
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.G_Rate) AS Gross_Rate'
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.G_Rate * BrokerBill_Trans.Qty) As Gross_Amount'
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.Brok_Amt) As Brokerage_Amount'
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.Rate) As Net_Rate'
				SET @sqlstr=@sqlstr + ',(BrokerBill_Trans.Rate*BrokerBill_Trans.Qty) As Net_Amount '	
				SET @sqlstr=@sqlstr + ',ISNULL(BrokerBill_Trans.isIntraDay,0) isIntraDay '	
						
				SET @sqlstr =@sqlstr + 'inTo #temp from BrokerBill_Trans '
				SET @sqlstr=@sqlstr + ' Inner Join BrokerBill On BrokerBill.Trans_no = BrokerBill_Trans.Trans_No AND BrokerBill.Member_Code = ' +  Char(39) + @Membercode + Char(39) + 'AND BrokerBill.YearCode = '  + Char(39) + @Yearcode + Char(39) + ''
				SET @sqlstr=@sqlstr + ' Inner Join Mst_Account On Mst_Account.AC_Code = BRokerBill.Broker_Code AND Mst_Account.Member_Code = ' +  Char(39) + @Membercode + Char(39) + 'AND Mst_Account.Year_Code = '  + Char(39) + @Yearcode + Char(39) + ''
			 
		IF(ISNULL(@InvestmentType,'0')='0')
			BEGIN
				SET @sqlstr=@sqlstr + ' Inner Join Mst_Account MA On MA.AC_Code = BrokerBill_Trans.Ac_Type AND MA.Member_Code = ' +  Char(39) + @Membercode + Char(39) + 'AND MA.Year_Code = '  + Char(39) + @Yearcode + Char(39) + ''
			END
				SET @sqlstr=@sqlstr + ' Inner Join Mst_Consultant  On Mst_Consultant.Consultant_Code = BrokerBill_Trans.Consultant_code'
				SET @sqlstr=@sqlstr + ' Inner join Mst_Script On Mst_Script.Script_Code = BrokerBill_Trans.Script_Code'
				SET @sqlstr=@sqlstr + ' Inner join Mst_Member on Mst_Member.Member_Code=BrokerBill_Trans.Member_code'
				SET @sqlstr=@sqlstr + ' Inner join Mst_Family  On Mst_Family.Family_Code=Mst_Member.Family_Code'
				SET @sqlstr  = @sqlstr + ' where BrokerBill_Trans.isFNOBill = ' + Char(39) + @InvestmentType + Char(39)
				SET @sqlstr  = @sqlstr + ' and (BrokerBill_Trans.Trans_Dt between '  + Char(39) + @FromDate  + Char(39) +   ' and ' + Char(39) + @ToDate + Char(39) +')'
				SET @sqlstr  = @sqlstr + ' and BrokerBill_Trans.Ac_Type =  (select case  when ' + Char(39) +  @HoldingType + Char(39) + ' = 0 then BrokerBill_Trans.Ac_Type  else '+ @HoldingType +' end)' 
				SET @sqlstr = @sqlstr + ' and BrokerBill_Trans.TransType = (case when ' + Char(39) +  ISNULL(@TransType,'All') + Char(39) +   '=''All'' OR  ' + Char(39) +  ISNULL(@TransType,' ') + Char(39) +   '='' ''
				THEN BrokerBill_Trans.TransType else' + Char(39) +  @TransType + Char(39) + 'end )'
				
				
				--SET @sqlstr = @sqlstr + ' AND ISNULL(BrokerBill_Trans.isIntraDay,0) =   (CASE WHEN ' + Char(39) +  ISNULL(@IsIntraDay,0) + Char(39) +   '= 0   THEN   ISNULL(isIntraDay,0) ELSE '  + Char(39) +   ISNULL(@IsIntraDay,0)  + Char(39) +   'END) '
				IF(@IsIntraDay != 2)
					BEGIN 
						If(@IsIntraDay = 0)
							SET @sqlstr = @sqlstr + ' AND (BrokerBill_Trans.isIntraDay IS NULL OR BrokerBill_Trans.isIntraDay = 0)'
						ELSE
							SET @sqlstr = @sqlstr + ' AND (BrokerBill_Trans.isIntraDay IS NOT NULL AND BrokerBill_Trans.isIntraDay = 1)'
					END


			
			IF(@Membercode <> '')
				 SET @sqlstr  = @sqlstr + ' and BrokerBill_Trans.Member_code in (SELECT Value FROM membercodestable(' + Char(39) + @TempMemberCode + Char(39) + ',' + Char(39) + ',' + Char(39) + ')) '
				 SET @sqlstr  = @sqlstr + ' and BrokerBill_Trans.YearCode = ''' + @Yearcode + ''''
				 SET @sqlstr  = @sqlstr + ' and BrokerBill_Trans.Bill_no != ''Opening'''

		IF(@ScriptCode <> '' ) 
			BEGIN 
				SET @sqlstr = @sqlstr + ' and BrokerBill_Trans.Script_Code in (SELECT Value FROM membercodestable(' + Char(39) + @ScriptCode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
			END 
        IF(@Billno<> '')
			 BEGIN
			    SET @sqlstr= @sqlstr +' and BrokerBill_Trans.Bill_no in (SELECT Value FROM membercodestable(' + Char(39) + @Billno + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
			 END

		IF ((@Membercode <> '')  AND @ConsultantCode <> '' ) 
			BEGIN 
				SET @sqlstr = @sqlstr + ' and Mst_Consultant.Consultant_code in (SELECT Value FROM membercodestable('+ Char(39) + @consultantcode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
			END

		IF (@consultantcode <> '' ) 
			BEGIN 
				SET @sqlstr = @sqlstr +  'and Mst_Consultant.Consultant_code in (SELECT value FROM membercodestable('+ Char(39) + @consultantcode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  '
			END 

		IF(@BrokerCode <> '')
			BEGIN
				SET @sqlstr =@sqlstr + 'and BrokerBill.Broker_Code in (SELECT Value FROM membercodestable('+ Char(39) + @BrokerCode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
			END		

		IF((@BrokerCode <> '')  AND @ConsultantCode <> '')
			BEGIN
				SET @sqlstr =@sqlstr + 'and BrokerBill.Broker_Code in (SELECT Value FROM membercodestable('+ Char(39) + @BrokerCode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
			END		
		IF((@Billno<>'') AND (@ConsultantCode<>'')and @BrokerCode <> '')
			BEGIN
				SET @sqlstr =@sqlstr + '	and BrokerBill_Trans.Bill_no in (SELECT Value FROM membercodestable('+ Char(39) + @Billno + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
			END		

		IF((@Billno<>'') AND (@ConsultantCode <> '')and @BrokerCode <> '' and (@ScriptCode <> ''))
			BEGIN
				SET @sqlstr =@sqlstr + '	and BrokerBill_Trans.Bill_no in (SELECT Value FROM membercodestable('+ CHAR(39) + @Billno + CHAR(39) + ',' + CHAR(39) + ',' + CHAR(39) + '))  ' 
			END	

		IF((@BrokerCode <> '') and @ScriptCode <>'')
			BEGIN
				SET @sqlstr =@sqlstr + 'and BrokerBill_Trans.Script_Code in (SELECT Value FROM membercodestable('+ CHAR(39) + @ScriptCode + CHAR(39) + ',' + CHAR(39) + ',' + CHAR(39) + '))  ' 
			END	
		IF((@BrokerCode <> '') and (@ConsultantCode <>''and (@ScriptCode <> '') ))
			BEGIN
				SET @sqlstr =@sqlstr + ' and BrokerBill_Trans.Script_Code in (SELECT Value FROM membercodestable('+ CHAR(39) + @ScriptCode + CHAR(39) + ',' + CHAR(39) + ',' + CHAR(39) + '))  ' 
			END			

		IF((@Familycode <> ''))
			BEGIN
				SET @sqlstr =@sqlstr + ' and Mst_Family.Family_Code in (SELECT Value FROM membercodestable('+ CHAR(39) + @Familycode + CHAR(39) + ',' + CHAR(39) + ',' + CHAR(39) + '))  ' 
			END	
		 IF(@Membercode <> '')
			 BEGIN
			    SET @sqlstr = @sqlstr +  ' and Mst_Member.Member_Code in(SELECT value FROM membercodestable('+ CHAR(39) + @Membercode + CHAR(39) + ',' + CHAR(39) + ',' + CHAR(39) + '))  '		 
			 END
	

				 SET @sqlstr  = @sqlstr +' Group by '
				IF(@flag='Familywise')
					BEGIN
						SET @sqlstr  = @sqlstr + ' Mst_Family.Family_Code,Mst_Family.Family_Name, Mst_Member.Member_Code,Mst_Member.Member_Name, '
						SET @sqlstr  = @sqlstr + ' Mst_Account.AC_Name, BrokerBill.Broker_Code, BrokerBill_Trans.Bill_no,'
						SET @sqlstr  = @sqlstr + ' Mst_Script.Script_Name, Mst_Script.Script_Code, Mst_Consultant.Consultant_Name,'
						SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Consultant_code, BrokerBill_Trans.TransType,'
						SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Trans_Dt, BrokerBill_Trans.Ac_Type,BrokerBill_Trans.Qty,'
						SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.G_Rate,BrokerBill_Trans.Brok_Amt,BrokerBill_Trans.Rate,'
						SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Amount,Mst_Consultant.Consultant_code,BrokerBill.Valan_code,'
						SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Last_Date,BrokerBill_Trans.Strike_Price,BrokerBill_Trans.OptionType,'
						SET @sqlstr  = @sqlstr + ' MST_Script.script_code ,BrokerBill_Trans.isIntraDay  '
					END
				ELSE
					BEGIN
						 SET @sqlstr  = @sqlstr + ' Mst_Consultant.Consultant_Name,BrokerBill_Trans.Consultant_code,Mst_Account.AC_Name,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill.Broker_Code,BrokerBill_Trans.Bill_no,Mst_Script.Script_Name,'
						 SET @sqlstr  = @sqlstr + ' Mst_Script.Script_Code,BrokerBill_Trans.TransType,BrokerBill_Trans.Trans_Dt,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Ac_Type,BrokerBill_Trans.Qty,BrokerBill_Trans.G_Rate,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Brok_Amt, BrokerBill_Trans.Rate,BrokerBill_Trans.Amount,'
						 SET @sqlstr  = @sqlstr + ' Mst_Consultant.Consultant_code,Mst_Member.Member_Code,Mst_Member.Member_Name,'
						 SET @sqlstr  = @sqlstr + ' Mst_Family.Family_Code,Mst_Family.Family_Name,BrokerBill.Valan_code,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Last_Date,BrokerBill_Trans.Strike_Price,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.OptionType,MST_Script.script_code ,BrokerBill_Trans.isIntraDay  '
					END

			IF(ISNULL(@InvestmentType,'0')='0')
			BEGIN
				SET @sqlstr  = @sqlstr + ',MA.AC_Name   '
			END
			
			SET @sqlstr=@sqlstr +    'SELECT * FROM   #temp t order by Bill_no '   	
			SET @sqlstr=@sqlstr +    ' DROP TABLE #temp'	
			PRINT @sqlstr

			EXECUTE (@sqlstr)

			
			Set @sqlstr = ''

			SET @sqlstr = '	Select AT.ExpenseType, At.Trans_No,Round(At.Amount,4) as ''Amount'',Ma.AC_Name,Bt.Bill_no 
							FROM  AC_Trans AT
							JOIN Mst_Account MA ON Ma.AC_Code = (CASE WHEN AT.ExpenseType = ''A'' THEN AT.Dr_Code WHEN AT.ExpenseType = ''L'' THEN At.Cr_Code END)
							JOIN BrokerBill_Trans BT on At.Trans_No = Bt.Trans_No
							WHERE AT.ExpenseType IN (''A'',''L'')  
							AND AT.Year_Code = ''' + @yearcode + ''' 
							AND Bt.isFNOBill  =''' + @InvestmentType + '''  
							AND bt.TransType != ''Opening''								
							'
			
			 IF(@Membercode <> '')
			 BEGIN
			    SET @sqlstr = @sqlstr +  ' and AT.Member_Code in(SELECT value FROM membercodestable('+ CHAR(39) + @Membercode + CHAR(39) + ',' + CHAR(39) + ',' + CHAR(39) + '))  '
			 END

			 SET @sqlstr = @sqlstr +  ' Group by Bt.Bill_no, ma.AC_Name, At.Trans_No,AT.ExpenseType,At.Amount Having At.Amount > 0 order by 5,1,2'

			 print @sqlstr

			 EXECUTE (@sqlstr)


			 


END
























GO
/****** Object:  StoredProcedure [dbo].[rpt_Consaltant_Transfer]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_Consaltant_Transfer]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[rpt_Consaltant_Transfer] AS' 
END
GO

ALTER Procedure [dbo].[rpt_Consaltant_Transfer]
(

@TillDate DateTime Null,
@YearCode Varchar(100),
@MemberCode Varchar(Max),
@ConsulatantCode Varchar(Max),
@ScriptCode Varchar(Max),
@Investmenttype int
)
AS
BEGIN
	SET NOCOUNT ON;
	
Select BrokerBill_Trans.Trans_No As 'Trans No',BrokerBill_Trans.Sr_No As 'Sr No',Convert(Varchar,BrokerBill_Trans.Trans_Dt,103)As 'Bill Date',
BrokerBill_Trans.Bill_no As 'Bill NO',BrokerBill_Trans.YearCode AS'Year Code',
MS.Script_Name As 'Script Name',MS.Script_Code As'ScriptCode',TransType,BrokerBill_Trans.Qty
from BrokerBill_Trans 

 Inner Join Mst_Script MS On
 MS.Script_Code=BrokerBill_Trans.Script_Code
 Inner join BrokerBill BB On
 BB.Trans_no=BrokerBill_Trans.Trans_No

 Inner join BrokerBill_DmatInfo BBD On
 BBD.Trans_No=BrokerBill_Trans.Trans_No

 Inner Join AC_Trans AC On
 AC.Trans_No=BrokerBill_Trans.Trans_No

  Where BrokerBill_Trans.Member_code=@MemberCode and BrokerBill_Trans.isFNOBill=@Investmenttype 
  and BrokerBill_Trans.YearCode=@YearCode and BrokerBill_Trans.Trans_Dt<=@TillDate 
  and BrokerBill_Trans.Consultant_code=@ConsulatantCode and BrokerBill_Trans.Script_Code=@ScriptCode

  Group By BrokerBill_Trans.Trans_No,BrokerBill_Trans.Trans_Dt,BrokerBill_Trans.Bill_no,BrokerBill_Trans.YearCode,
  MS.Script_Name,MS.Script_Code ,TransType,BrokerBill_Trans.Qty,BrokerBill_Trans.Sr_No
 END
























GO
/****** Object:  StoredProcedure [dbo].[rpt_Family_Memberwise_Account_Ledger_Report]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_Family_Memberwise_Account_Ledger_Report]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[rpt_Family_Memberwise_Account_Ledger_Report] AS' 
END
GO

--execute [dbo].[rpt_Family_Memberwise_Account_Ledger_Report] 'Y0001','','1120182019','','04/01/2018','03/31/2019'

ALTER Procedure [dbo].[rpt_Family_Memberwise_Account_Ledger_Report]
(
 @Membercode Varchar(Max),
 @Familycode Varchar(Max),
 @Yearcode Varchar(500),
 @Accountcode Varchar(Max),
 @FromDate Varchar(50),
 @ToDate varchar(50)
)
AS 
  BEGIN
  SET NOCOUNT ON;
	Create Table #temp
	(
		Trans_No varchar(20),
		Entry_Type varchar(20),
		[Bill_No] varchar(50),
		[Date] datetime,
		[Check_Number] varchar(50),
		Ac_Code varchar(10),
		Ac_Name varchar(500),
		Sub_Ac_Code varchar(10),
		Sub_Ac_Name varchar(500),
		Debit_Amount float,
		Credit_Amount float,
		Balance as Credit_Amount - Debit_Amount ,  
		Member_code Varchar(50),
		MemberName Varchar(200),
		Family_code Varchar(100),
		FamilyName Varchar(200),
		Narration Varchar(max)	
	)

	Create Table #Openings
	(
		Trans_No varchar(20),
		Entry_Type varchar(20),
		[Bill_No] varchar(50),
		[Date] datetime,
		[Check_Number] varchar(50),
		Ac_Code varchar(10),
		Ac_Name varchar(500),
		Sub_Ac_Code varchar(10),
		Sub_Ac_Name varchar(500),
		Debit_Amount float,
		Credit_Amount float,
		Balance as Credit_Amount - Debit_Amount ,  
		Member_code Varchar(50),
		MemberName Varchar(200),
		Family_code Varchar(100),
		FamilyName Varchar(200),
		Narration Varchar(max)	
	)

	DECLARE @StartYearDate varchar(20) = '04/01/'+ (Select SUBSTRING(@yearcode ,3,4))  
	-- Acount code Find
	create table #Account (Ac_Code varchar(max))
	
	IF(@Accountcode = '')
		BEGIN 
			INSERT INTO #Account  Select Ac_Code FROM Mst_Account Where Year_Code = @Yearcode And Member_Code IN (SELECT Value FROM membercodestable(@Membercode,','))					
		END
	ELSE 
			INSERT INTO #Account SELECT value FROM Fn_split(@Accountcode, ',') 

-- Famliy Code find 

	create table #FamilyAccount (Family_code varchar(max))
	IF(@Familycode = '')
				BEGIN 
					INSERT INTO #FamilyAccount  Select Family_Code FROM Mst_Family 
				END
			ELSE 
					INSERT INTO #FamilyAccount SELECT value FROM Fn_split(@Familycode, ',') 

 --Member code Find
	create table #Membercode (Member_code varchar(max))
	--DECLARE @TempMembercode varchar(1000)
	IF(@Membercode = '' and @Familycode = '')
		BEGIN 
			INSERT INTO #Membercode  Select Member_Code FROM Mst_Member 
		END

	IF(@Familycode <> '')
		BEGIN 
			INSERT INTO #Membercode  Select Member_Code FROM Mst_Member Where Family_Code IN (SELECT Value FROM membercodestable(@Familycode,','))							
		END
	ELSE 
		BEGIN	
			
			INSERT INTO #Membercode SELECT value FROM Fn_split(@Membercode, ',') 
		END



 -- Insert Only Dr Amount
Insert into #temp (Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Member_code,MemberName,Family_code,FamilyName,Narration)
select	AT.Trans_No,
			Case 
			When Book_Type1 = 'BK'  THEN  
				CASE  WHEN Sub_Type1 = 'C' THEN 'CASH' ELSE  'BANK' 
			END
			WHEN Book_Type1 = 'JV' THEN  'Journal Entry'
			WHEN Book_Type1 = 'RC' THEN  'Bank Reconcilation' 
			WHEN Book_Type1 = 'IN' THEN  'Income Expense'
			WHEN Book_Type1 = 'IPO' THEN  'IPO'
			ELSE I.Entry_Type
		END as 'Entry_Type',
		At.Vouch_No,
		Trans_Dt,
		Chq_No,
		ma.AC_Code,
		ma.AC_Name,
		AT.Cr_Code,
		(Select Top(1) Ac_Name From Mst_Account Where AC_Code = AT.Cr_Code),
		Amount,
		0.0,
		AT.Member_Code,
		MM.Member_Name,
		MF.Family_Code,
		MF.Family_Name,
		AT.Narr1 +AT.Narr2+AT.Narr3
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
join Mst_Family MF on MF.Family_Code=MM.Family_Code
Join Mst_Account ma ON ma.AC_Code  = At.Dr_Code And ma.Member_Code = AT.Member_Code AND ma.Year_Code = @Yearcode
Where At.Book_Type1 != 'BB' AND
At.Year_Code = @Yearcode  and (AT.Trans_Dt  <= @ToDate AND AT.Trans_Dt>=@StartYearDate) AND  (Select Count(*) From Mst_Account Where AC_Code = AT.Dr_Code AND Year_Code = @Yearcode And Member_Code IN (Select Member_Code From #Membercode) )> 0 
and At.Amount!=0
and ma.AC_Code in (select AC_Code from #Account)
and MF.Family_Code in(Select Family_Code from #FamilyAccount) 
and  MM.Member_Code in(Select Member_Code from #Membercode)
Group By AT.Trans_No,I.Entry_Type,At.Vouch_No,Trans_Dt,Chq_No,ma.AC_Code,ma.AC_Name,AT.Cr_Code,Amount,AT.Member_Code,MM.Member_Name,MF.Family_Code,MF.Family_Name,AT.Narr1 +AT.Narr2+AT.Narr3,Book_Type1,Sub_Type1

-- Insert Into Cr Amount
Insert into #temp (Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Member_code,MemberName,Family_code,FamilyName,Narration)
select	AT.Trans_No,
		Case 
			When Book_Type1 = 'BK'  THEN  
				CASE  WHEN AT.Sub_Type1 = 'C' THEN 'CASH' ELSE  'BANK' 
			END
			WHEN Book_Type1 = 'JV' THEN  'Journal Entry'
			WHEN Book_Type1 = 'RC' THEN  'Bank Reconcilation' 
			WHEN Book_Type1 = 'IN' THEN  'Income Expense'
			WHEN Book_Type1 = 'IPO' THEN  'IPO'
			ELSE I.Entry_Type
		END as 'Entry_Type',
		At.Vouch_No,
		Trans_Dt,
		Chq_No,
		ma.AC_Code,
		ma.AC_Name,
		AT.Dr_Code,
		(Select Top(1) Ac_Name From Mst_Account Where AC_Code = AT.Dr_Code),
		0.0,
		Amount,
		AT.Member_Code,
		MM.Member_Name,
		MF.Family_Code,
		MF.Family_Name,
		AT.Narr1 +AT.Narr2+AT.Narr3
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
join Mst_Family MF on MF.Family_Code=MM.Family_Code
Join Mst_Account ma ON ma.AC_Code  = At.Cr_Code And ma.Member_Code = AT.Member_Code  AND ma.Year_Code = @Yearcode
Where At.Book_Type1 != 'BB' and At.Amount!=0
AND At.Year_Code = @Yearcode  and (AT.Trans_Dt  <= @ToDate AND AT.Trans_Dt>=@StartYearDate) AND  (Select Count(*) From Mst_Account Where AC_Code = AT.Cr_Code AND Year_Code = @Yearcode And Member_Code IN (Select Member_Code From #Membercode))>0 
and ma.AC_Code in (select AC_Code from #Account)
and  MF.Family_Code in(Select Family_Code from #FamilyAccount) 
and MM.Member_Code in(Select Member_Code from #Membercode)
Group By AT.Trans_No,I.Entry_Type,At.Vouch_No,Trans_Dt,Chq_No,ma.AC_Code,ma.AC_Name,AT.Dr_Code,Amount,AT.Member_Code,
MM.Member_Name,MF.Family_Code,MF.Family_Name,AT.Narr1 +AT.Narr2+AT.Narr3,Book_Type1,Sub_Type1

---- Insert SHAREINVESTMENT /SHARE TRADING DR AMOUNT
Insert into #temp (Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Member_code,MemberName,Family_code,FamilyName,Narration)
select	AT.Trans_No,
			Case 
			When Book_Type1 = 'BK'  THEN  
				CASE  WHEN AT.Sub_Type1 = 'C' THEN 'CASH' ELSE  'BANK' 
			END
			WHEN Book_Type1 = 'JV' THEN  'Journal Entry'
			WHEN Book_Type1 = 'RC' THEN  'Bank Reconcilation' 
			WHEN Book_Type1 = 'IN' THEN  'Income Expense'
			WHEN Book_Type1 = 'IPO' THEN  'IPO'
			ELSE I.Entry_Type
		END as 'Entry_Type',
		At.Vouch_No,
		AT.Trans_Dt,
		Chq_No,
		ma.AC_Code,
		ma.AC_Name,
		AT.Dr_Code,
		(Select Top(1) Ac_Name From Mst_Account Where AC_Code = AT.Dr_Code),
		0.0,
		CASE WHEN (MAG.GRP_NAME = 'BROKER' OR MAG.GRP_NAME='BROKER (C.A)') THEN (BB.Net_amt)
	   ELSE AT.Amount
		END as 'Amount',
		
		AT.Member_Code,
		MM.Member_Name,
		MF.Family_Code,
		MF.Family_Name,
		AT.Narr1 + ' ' + AT.Narr2 +  ' ' + AT.Narr3
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
join Mst_Family MF on MF.Family_Code=MM.Family_Code
Join Mst_Account ma ON ma.AC_Code  = At.Cr_Code And ma.Member_Code = AT.Member_Code and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.Grp_Id = ma.Grp_id
Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no 
Where At.Book_Type1 = 'BB' and (AT.Trans_Dt  <= @ToDate AND AT.Trans_Dt>=@StartYearDate) AND (Select Count(*) From Mst_Account Where AC_Code = AT.Dr_Code AND Year_Code = @Yearcode And Member_Code IN (Select Member_Code From #Membercode))  > 0 
AND At.Year_Code = @Yearcode 
and ma.AC_Code in (select AC_Code from #Account)
and MM.Member_Code in(Select Member_Code from #Membercode)
and MF.Family_Code in(Select Family_Code from #FamilyAccount) 
AND AT.EntryType != 10  and ma.Grp_Name!='BROKER'and At.Amount!=0
Group By AT.Trans_No,I.Entry_Type,At.Vouch_No,At.Trans_Dt,Chq_No,ma.AC_Code,ma.AC_Name,AT.Dr_Code,AT.Amount,AT.Member_Code,MM.Member_Name,MF.Family_Code,MF.Family_Name,MAG.GRP_NAME,BB.Net_amt,AT.Narr1 + ' ' + AT.Narr2 +  ' ' + AT.Narr3 ,Book_Type1,Sub_Type1

-- Insert SHAREINVESTMENT /SHARE TRADING CR AMOUNT
Insert into #temp (Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Member_code,MemberName,Family_code,FamilyName,Narration)
select	AT.Trans_No,
			Case 
			When Book_Type1 = 'BK'  THEN  
				CASE  WHEN AT.Sub_Type1 = 'C' THEN 'CASH' ELSE  'BANK' 
			END
			WHEN Book_Type1 = 'JV' THEN  'Journal Entry'
			WHEN Book_Type1 = 'RC' THEN  'Bank Reconcilation' 
			WHEN Book_Type1 = 'IN' THEN  'Income Expense'
			WHEN Book_Type1 = 'IPO' THEN  'IPO'
			ELSE I.Entry_Type
		END as 'Entry_Type',
		At.Vouch_No,
		AT.Trans_Dt,
		Chq_No,
		ma.AC_Code,
		ma.AC_Name,
		AT.Dr_Code,
		(Select Top(1) Ac_Name From Mst_Account Where AC_Code = AT.Cr_Code),
		
		--CASE WHEN MAG.GRP_NAME = 'BROKER' THEN BB.Net_amt
		--	 ELSE AT.Amount
		CASE WHEN (MAG.GRP_NAME = 'BROKER' OR MAG.GRP_NAME='BROKER (C.A)' ) THEN BB.Net_amt
			 ELSE AT.Amount
		END as 'Amount',
		0.0,
		AT.Member_Code,
		MM.Member_Name,
		MF.Family_Code,
		MF.Family_Name,
		AT.Narr1 + ' ' + AT.Narr2 +  ' ' + AT.Narr3
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
join Mst_Family MF on MF.Family_Code=MM.Family_Code
Join Mst_Account ma ON ma.AC_Code  = At.Dr_Code And ma.Member_Code = At.Member_Code  and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.Grp_Id = ma.Grp_id
Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no 
Where At.Book_Type1 = 'BB' and (AT.Trans_Dt  <= @ToDate AND AT.Trans_Dt>=@StartYearDate) AND (Select Count(*) From Mst_Account Where AC_Code = AT.Cr_Code AND Year_Code = @Yearcode And Member_Code IN (Select Member_Code From #Membercode))  > 0 
AND At.Year_Code = @Yearcode 
and ma.AC_Code in (select AC_Code from #Account)
and MM.Member_Code in(Select Member_Code from #Membercode)
and MF.Family_Code in(Select Family_Code from #FamilyAccount) 
AND AT.EntryType != 10 and ma.Grp_Name!='BROKER' and At.Amount!=0
Group By AT.Trans_No,I.Entry_Type,At.Vouch_No,At.Trans_Dt,Chq_No,ma.AC_Code,ma.AC_Name,AT.Dr_Code,At.Cr_Code,AT.Amount,AT.Member_Code,
MM.Member_Name,MF.Family_Code,MF.Family_Name,MAG.GRP_NAME,BB.Net_amt,AT.Narr1 + ' ' + AT.Narr2 +  ' ' + AT.Narr3,Book_Type1,Sub_Type1

--Broker Account Entry
Insert into #temp (Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Member_code,MemberName,Family_code,FamilyName,Narration)
 select	AT.Trans_No,
			Case 
			When Book_Type1 = 'BK'  THEN  
				CASE  WHEN Sub_Type1 = 'C' THEN 'CASH' ELSE  'BANK' 
			END 
			WHEN Book_Type1 = 'JV' THEN  'Journal Entry'
			WHEN Book_Type1 = 'RC' THEN  'Bank Reconcilation' 
			WHEN Book_Type1 = 'IN' THEN  'Income Expense'
			WHEN Book_Type1 = 'IPO' THEN  'IPO'
			ELSE I.Entry_Type
		END as 'Entry_Type',
		At.Bill_no,
		AT.Trans_Dt,
	    '',
		--Chq_No,
		ma.AC_Code,
		ma.AC_Name,	
		'',
		--(Select Top(1) Ac_Name From Mst_Account Where AC_Code = AT.Cr_Code),
		'SHARE TRANSACTION A/C',
		CASE WHEN At.Ac_Type = 'D' THEN At.Net_amt ELSE 0.0 END,
		CASE WHEN At.Ac_Type = 'C' THEN At.Net_amt ELSE 0.0 END,
		AT.Member_Code,
		MM.Member_Name,
		MF.Family_Code,
		MF.Family_Name,
		''
from BrokerBill AT
Join Ent_EntryTypes I On I.SR_NO = AT.isFNOBill
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
join Mst_Family MF on MF.Family_Code=MM.Family_Code
Join Mst_Account ma ON ma.AC_Code  = At.Broker_Code And ma.Member_Code   = AT.Member_Code and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.Grp_Id = ma.Grp_id
Inner Join AC_Trans BB ON  At.Trans_No = BB.Trans_no 
Where At.Book_Type = 'BB' and (AT.Trans_Dt  <= @ToDate AND AT.Trans_Dt>=@StartYearDate)
AND At.YearCode = @Yearcode 
and ma.AC_Code in (select AC_Code from #Account) 
and MM.Member_Code in(Select Member_Code from #Membercode)
and MF.Family_Code in(Select Family_Code from #FamilyAccount) 
AND BB.EntryType != 10   AND At.Amount!=0
Group By AT.Trans_No,I.Entry_Type,At.Bill_no,At.Trans_Dt,ma.AC_Code,ma.AC_Name,AT.Broker_Code,
AT.Amount,AT.Member_Code,MM.Member_Name, At.isFNOBill,ma.Grp_id,AT.Ac_Type,AT.Net_amt,MF.Family_Code,MF.Family_Name,Book_Type1,Sub_Type1
Order by At.Trans_Dt

-- Insert Expense DR Account
Insert into #temp (Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Member_code,MemberName,Family_code,FamilyName,Narration)
select	AT.Trans_No,
		Case 
			When Book_Type1 = 'BK'  THEN  
				CASE  WHEN Sub_Type1 = 'C' THEN 'CASH' ELSE  'BANK' 
			END
			WHEN Book_Type1 = 'JV' THEN  'Journal Entry'
			WHEN Book_Type1 = 'RC' THEN  'Bank Reconcilation' 
			WHEN Book_Type1 = 'IN' THEN  'Income Expense'
			WHEN Book_Type1 = 'IPO' THEN  'IPO'
			ELSE I.Entry_Type
		END as 'Entry_Type',
		At.Vouch_No,
		AT.Trans_Dt,
		Chq_No,
		ma.AC_Code,
		ma.AC_Name,
		AT.Cr_Code,
		(Select Top(1) Ac_Name From Mst_Account Where AC_Code = AT.Cr_Code),
		CASE WHEN At.ExpenseType = 'A' THEN At.Amount ELSE 0.0 END,
		 0.0,--CASE WHEN At.ExpenseType = 'L' THEN At.Amount ELSE 0.0 END,
		AT.Member_Code,
		MM.Member_Name,
		MF.Family_Code,
		MF.Family_Name,
		''
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
join Mst_Family MF on MF.Family_Code=MM.Family_Code
Join Mst_Account ma ON ma.AC_Code  = At.Dr_Code And ma.Member_Code   = AT.Member_Code  and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.Grp_Id = ma.Grp_id
Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no AND BB.Member_Code = @Membercode and BB.YearCode = @Yearcode
Where At.Book_Type1 = 'BB' and (AT.Trans_Dt  <= @ToDate AND AT.Trans_Dt>=@StartYearDate) AND (Select Count(*) From Mst_Account Where AC_Code = AT.Dr_Code AND Year_Code = @Yearcode And Member_Code IN (Select Member_Code From #Membercode))  > 0 
AND At.Year_Code = @Yearcode 
AND ma.AC_Code in (select AC_Code from #Account)
AND MM.Member_Code in(Select Member_Code from #Membercode)
AND MF.Family_Code in(Select Family_Code from #FamilyAccount) 
AND AT.EntryType = 10 
Group By AT.Trans_No,I.Entry_Type,At.Vouch_No,At.Trans_Dt,Chq_No,ma.AC_Code,ma.AC_Name,AT.Dr_Code, AT.Cr_Code,AT.Amount,AT.Member_Code,
MM.Member_Name,MF.Family_Code,MF.Family_Name, At.ExpenseType,Book_Type1,Sub_Type1

--Insert Expense Cr Account
Insert into #temp (Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Member_code,MemberName,Family_code,FamilyName,Narration)
select	AT.Trans_No,
		Case 
			When Book_Type1 = 'BK'  THEN  
				CASE  WHEN Sub_Type1 = 'C' THEN 'CASH' ELSE  'BANK' 
			END
			WHEN Book_Type1 = 'JV' THEN  'Journal Entry'
			WHEN Book_Type1 = 'RC' THEN  'Bank Reconcilation' 
			WHEN Book_Type1 = 'IN' THEN  'Income Expense'
			WHEN Book_Type1 = 'IPO' THEN  'IPO'
			ELSE I.Entry_Type
		END as 'Entry_Type',
		At.Vouch_No,
		AT.Trans_Dt,
		Chq_No,
		ma.AC_Code,
		ma.AC_Name,
		AT.Dr_Code,
		(Select Top(1) Ac_Name From Mst_Account Where AC_Code = AT.Dr_Code),
	     0.0,
		CASE WHEN At.ExpenseType = 'L' THEN At.Amount ELSE 0.0 END,
		AT.Member_Code,
		MM.Member_Name,
		MF.Family_Code,
		MF.Family_Name,
		''
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
join Mst_Family MF on MF.Family_Code=MM.Family_Code
Join Mst_Account ma ON ma.AC_Code  = At.Cr_Code And ma.Member_Code = AT.Member_Code  and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.Grp_Id = ma.Grp_id
Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no AND BB.Member_Code = @Membercode and BB.YearCode = @Yearcode
Where At.Book_Type1 = 'BB' and (AT.Trans_Dt  <= @ToDate AND AT.Trans_Dt>=@StartYearDate) AND (Select Count(*) From Mst_Account Where AC_Code = AT.Cr_Code AND Year_Code = @Yearcode And Member_Code IN (Select Member_Code From #Membercode))  > 0 
AND At.Year_Code = @Yearcode 
AND ma.AC_Code in (select AC_Code from #Account)
AND MM.Member_Code in(Select Member_Code from #Membercode)
AND MF.Family_Code in(Select Family_Code from #FamilyAccount) 
AND AT.EntryType = 10 
Group By AT.Trans_No,I.Entry_Type,At.Vouch_No,At.Trans_Dt,Chq_No,ma.AC_Code,ma.AC_Name,AT.Dr_Code, AT.Cr_Code,AT.Amount,AT.Member_Code,
MM.Member_Name,MF.Family_Code,MF.Family_Name, At.ExpenseType,Book_Type1,Sub_Type1

Insert into #Openings (Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Member_code,MemberName,Family_code,FamilyName,Narration)
 select		'',
			'Opening' as 'Entry_Type', 
			'',
			@fromdate,
			'',
			ma.AC_Code,
			ma.AC_Name,
			'',
			'',
			CASE
				WHEN  ma.Op_Cal = 1 Then  ma.Op_Bal ELSE 0.0
			END,
			CASE
				WHEN  ma.Op_Cal = -1 Then  ma.Op_Bal ELSE 0.0
			END,
			MM.Member_Code,
			MM.Member_Name,
			MF.Family_Code,
			MF.Family_Name,
			''
	from Mst_Account ma
	JOIN Mst_Member MM On MM.Member_Code=MA.Member_Code
	JOIN Mst_Family MF on MF.Family_Code=MM.Family_Code 
	WHERE ma.Op_Bal != 0 And ma.Member_Code IN (Select Member_Code From #Membercode) and ma.Year_Code = @Yearcode
	AND ma.AC_Code in (select AC_Code from #Account)
	AND MM.Member_Code in(Select Member_Code from #Membercode)
    AND MF.Family_Code in(Select Family_Code from #FamilyAccount) 
	UNION All 
	Select  '',
			'Opening', 
			'',
			@fromdate,
			'',
			t.AC_Code,
			t.AC_Name,
			'',
			'',
			t.Debit_Amount,
			t.Credit_Amount,
			t.Member_code,
			t.MemberName,
			t.Family_code,
			t.FamilyName,
			''
	From #temp t
	where Balance !=0 and t.Date < @FromDate  


	
	Insert into #temp (Trans_No,Entry_Type,[Bill_No],[Date],[Check_Number],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Debit_Amount,Credit_Amount,Member_code,MemberName,Family_code,FamilyName,Narration)
	Select  Trans_No,
			Entry_Type,
			[Bill_No],
			[Date],
			[Check_Number],
			Ac_Code,
			Ac_Name,
			Sub_Ac_Code,
			Sub_Ac_Name,
			CASE 
				WHEN (Sum(Debit_Amount) - Sum(Credit_Amount)) > 0  THEN ABS((Sum(Debit_Amount) - Sum(Credit_Amount))) ELSE 0 
			END,
			CASE 
				WHEN (Sum(Debit_Amount) - Sum(Credit_Amount)) < 0  THEN ABS((Sum(Debit_Amount) - Sum(Credit_Amount))) ELSE 0 
			END,
			Member_code,
			MemberName,
			Family_code,
			FamilyName,
			Narration
	from #Openings	
	Group By Member_code,MemberName,Family_code,FamilyName,Trans_No,Entry_Type,[Bill_No],[Check_Number],[Date],Ac_Code,Ac_Name,Sub_Ac_Code,Sub_Ac_Name,Narration





Select * from #temp  t
where Balance!=0 and t.Date >= @FromDate  
Order by FamilyName,MemberName,Ac_Name,Date,Trans_No--,Entry_Type,Bill_No


-- Expenses
Select AT.ExpenseType, At.Trans_No,Round(At.Amount,4) as 'Amount',Ma.AC_Name,Bt.Bill_no 
FROM  AC_Trans AT
JOIN Mst_Account MA ON Ma.AC_Code = (CASE WHEN AT.ExpenseType = 'A' THEN AT.Dr_Code WHEN AT.ExpenseType = 'L' THEN At.Cr_Code END) AND MA.Member_Code in(Select Member_Code from #Membercode) AND MA.Year_Code = @Yearcode
JOIN BrokerBill_Trans BT on At.Trans_No = Bt.Trans_No
WHERE AT.EntryType = 10
AND AT.Year_Code = @yearcode
AND bt.TransType != 'Opening'
AND AT.Member_Code in(Select Member_Code from #Membercode)
Group by Bt.Bill_no, ma.AC_Name, At.Trans_No,AT.ExpenseType,At.Amount Having At.Amount > 0 order by 5,1,2


Drop Table #temp
Drop Table #Openings
Drop Table #Account
end





















GO
/****** Object:  StoredProcedure [dbo].[rpt_Final_Statement_Report]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_Final_Statement_Report]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[rpt_Final_Statement_Report] AS' 
END
GO






--exec rpt_Final_Statement_Report 'A0004','1120172018','04/01/2017','03/31/2018',0
 
 --Select * from Mst_AcGroup
 --Select * from Mst_Account
ALTER Procedure [dbo].[rpt_Final_Statement_Report]
(
 @Membercode Varchar(Max),
 @Yearcode Varchar(500),
 @FromDate Varchar(50),
 @ToDate varchar(50),
 @IsPnl bit
  
)
AS 
  BEGIN
  SET NOCOUNT ON;
Create Table #temp
(
	Ac_Code varchar(10),
	Ac_Name varchar(500),
	Debit_Amount float,
	Credit_Amount float,
	Group_id int,
	Groupname Varchar(500),
	HGroup varchar(500),
	Libilities_Assets_Type Varchar(500),
	Narration Varchar(500),
	Trasdate varchar(100),
	VoucherNo varchar(500)
)
	
--Insert only Dr Amount
Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo)
select  ma.AC_Code,
		ma.AC_Name,
		Amount,
		0.0,
		ma.Grp_id,
		ma.Grp_Name,
		mag.hname,
		ma.EFFECT,
		AT.Narr1,
		AT.Trans_Dt,
		At.Vouch_No
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Dr_Code And ma.Member_Code = @Membercode AND ma.Year_Code = @Yearcode
--Join Mst_AcGroup MAG On MAG.Grp_Id=ma.Grp_id
Join Mst_AcGroup MAG On MAG.GRP_NAME=ma.Grp_Name 

Where At.Book_Type1 != 'BB' and (AT.Trans_Dt >= @FromDate and  AT.Trans_Dt  <= @ToDate) AND (Select Count(*) From Mst_Account Where AC_Code = AT.CR_Code)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode  and At.Amount!=0 AND Book_type1!='RC'
	Group By ma.AC_Code,ma.AC_Name,AT.Cr_Code,Amount,AT.Member_Code,MM.Member_Name,MAG.GRP_NAME,
	ma.Grp_Name,mag.hname,ma.EFFECT,AT.Narr1,AT.Trans_Dt,At.Vouch_No,ma.Grp_id,AT.Sr_No,At.Trans_No


--Insert Into Cr Amount
Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo)
select	
		ma.AC_Code,
		ma.AC_Name,
		0.0,
		Amount,
		ma.Grp_id,
		ma.Grp_Name,
		mag.hname,
		ma.EFFECT,
		At.Narr1,
		At.Trans_Dt,
		At.Vouch_No

from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Cr_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
--Join Mst_AcGroup MAG On MAG.Grp_Id=ma.Grp_id
Join Mst_AcGroup MAG On MAG.GRP_NAME=ma.Grp_Name

Where At.Book_Type1 != 'BB' and  (AT.Trans_Dt >= @FromDate and  AT.Trans_Dt  <= @ToDate) AND (Select Count(*) From Mst_Account Where AC_Code = AT.Dr_Code)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode and At.Amount!=0 AND Book_type1!='RC'
Group By AT.Trans_No,I.Entry_Type,At.Vouch_No,Trans_Dt,Chq_No,ma.AC_Code,ma.AC_Name,
AT.Dr_Code,Amount,AT.Member_Code,MM.Member_Name,ma.Grp_id,ma.Grp_Name,mag.hname,ma.EFFECT,
At.Narr1,AT.Trans_Dt,At.Vouch_No,ma.Grp_id,AT.Sr_No
		
		Print @fromDate + '-' +  @ToDate

-- Insert SHAREINVESTMENT/FO INVESTMENT  DR EXCLUDE BROKER
Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo)
select	
		ma.AC_Code,
		ma.AC_Name,
		0.0,
		CASE WHEN(MAG.GRP_NAME = 'BROKER' OR MAG.GRP_NAME='BROKER (C.A)') THEN BB.Net_amt
			 ELSE AT.Amount
		END as 'Amount',
		
		ma.Grp_id,
		ma.Grp_Name,
		mag.hname,
		ma.EFFECT,
		At.Narr1,
		At.Trans_Dt,
		At.Vouch_No

from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Cr_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
--Join Mst_AcGroup MAG On MAG.Grp_Id=ma.Grp_id
Join Mst_AcGroup MAG On MAG.GRP_NAME=ma.Grp_Name
Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no  and BB.Member_code= @Membercode  and BB.YearCode = @Yearcode
Where At.Book_Type1 = 'BB' and AT.Trans_Dt  <= @ToDate AND (Select Count(*) From Mst_Account Where AC_Code = AT.Dr_Code)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode
AND AT.EntryType != 10  and (MAG.GRP_NAME!='BROKER' and MAG.GRP_NAME!='BROKER (C.A)')
Group By ma.AC_Code,ma.AC_Name,AT.Amount,AT.Member_Code,MM.Member_Name,MAG.GRP_NAME,BB.Net_amt,mag.GRP_NAME,ma.Grp_id,
ma.Grp_Name,mag.hname,ma.EFFECT,At.Narr1,AT.Trans_Dt,At.Vouch_No,AT.Sr_No,At.Trans_No,BB.Member_code, BB.YearCode

-- Insert Brokers SHAREINVESTMENT/FO INVESTMENT  CR EXCLUDE BROKER
Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo)
select	
		ma.AC_Code,
		ma.AC_Name,
		
		CASE WHEN(MAG.GRP_NAME = 'BROKER' OR MAG.GRP_NAME='BROKER (C.A)') THEN BB.Net_amt
			 ELSE AT.Amount
		END as 'Amount',
		0.0,
		ma.Grp_id,
		ma.Grp_Name,
		mag.hname,
		ma.EFFECT,
		At.Narr1,
		At.Trans_Dt,
		At.Vouch_No
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Dr_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
--Join Mst_AcGroup MAG On MAG.Grp_Id=ma.Grp_id
Join Mst_AcGroup MAG On MAG.GRP_NAME=ma.Grp_Name
Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no  and BB.Member_code= @Membercode  and BB.YearCode = @Yearcode
Where At.Book_Type1 = 'BB' and AT.Trans_Dt  <= @ToDate AND (Select Count(*) From Mst_Account Where AC_Code = AT.Cr_Code)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode
AND AT.EntryType != 10 and (MAG.GRP_NAME!='BROKER' and MAG.GRP_NAME!='BROKER (C.A)')
Group By ma.AC_Code,ma.AC_Name,AT.Dr_Code,At.Cr_Code,AT.Amount,AT.Member_Code,MM.Member_Name,MAG.GRP_NAME,
BB.Net_amt,mag.GRP_NAME,ma.Grp_Name,mag.hname,ma.EFFECT,At.Narr1,AT.Trans_Dt,At.Vouch_No,ma.Grp_id,At.Trans_No,BB.Member_code, BB.YearCode

--Insert Only Broker Amount

Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo)
select	
		ma.AC_Code,
		ma.AC_Name,
		
		CASE WHEN At.Ac_Type = 'D' THEN At.Net_amt ELSE 0.0 END,
		CASE WHEN At.Ac_Type = 'C' THEN At.Net_amt ELSE 0.0 END,
		ma.Grp_id,
		ma.Grp_Name,
		mag.hname,
		ma.EFFECT,
		At.Narrat1,
		At.Trans_Dt,
		''
from BrokerBill AT
Join Ent_EntryTypes I On I.SR_NO = AT.isFNOBill
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Broker_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
--Join Mst_AcGroup MAG On MAG.Grp_Id=ma.Grp_id
Join Mst_AcGroup MAG On MAG.GRP_NAME=ma.Grp_Name
Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no  and BB.Member_code= @Membercode  and BB.YearCode = @Yearcode
Where At.Book_Type = 'BB' and AT.Trans_Dt  <= @ToDate --AND (Select Count(*) From Mst_Account Where AC_Code = AT.Cr_Code)  > 0 
AND AT.Member_Code = @Membercode AND At.YearCode = @Yearcode

Group By ma.AC_Code,ma.AC_Name,AT.Broker_Code,At.Ac_Type,At.Net_amt,AT.Amount,AT.Member_Code,MM.Member_Name,
MAG.GRP_NAME,BB.Net_amt,mag.GRP_NAME,ma.Grp_Name,mag.hname,ma.EFFECT,At.Narrat1,AT.Trans_Dt,ma.Grp_id,AT.Bill_no,AT.Valan_code,BB.Member_code, BB.YearCode

--Insert  Expense Dr Amount
Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo)
select	
		ma.AC_Code,
		ma.AC_Name,
		CASE WHEN At.ExpenseType = 'A' THEN At.Amount ELSE 0.0 END,
		0.0,--CASE WHEN At.ExpenseType = 'L' THEN At.Amount ELSE 0.0 END,
		ma.Grp_id,
		ma.Grp_Name,
		mag.hname,
		ma.EFFECT,
		At.Narr1,
		At.Trans_Dt,
		At.Vouch_No
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Dr_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
--Join Mst_AcGroup MAG On MAG.Grp_Id=ma.Grp_id
Join Mst_AcGroup MAG On MAG.GRP_NAME=ma.Grp_Name
Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no and BB.Member_code= @Membercode  and BB.YearCode = @Yearcode
Where At.Book_Type1 = 'BB' and AT.Trans_Dt  <= @ToDate AND (Select Count(*) From Mst_Account Where AC_Code = AT.Dr_code)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode 
AND AT.EntryType = 10  
Group By ma.AC_Code,ma.AC_Name,AT.Dr_Code, AT.Cr_Code,AT.Amount,AT.Member_Code,MM.Member_Name, 
At.ExpenseType,mag.GRP_NAME,ma.Grp_Name,mag.hname,ma.EFFECT,At.Trans_No,At.Narr1,AT.Trans_Dt,At.Vouch_No,ma.Grp_id,BB.Member_code, BB.YearCode

--Insert  Expense CR Amount

Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo)
select	
		ma.AC_Code,
		ma.AC_Name,
		0.0,--CASE WHEN At.ExpenseType = 'A' THEN At.Amount ELSE 0.0 END,
		CASE WHEN At.ExpenseType = 'L' THEN At.Amount ELSE 0.0 END,
		ma.Grp_id,
		ma.Grp_Name,
		mag.hname,
		ma.EFFECT,
		At.Narr1,
		At.Trans_Dt,
		At.Vouch_No
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Cr_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
--Join Mst_AcGroup MAG On MAG.Grp_Id=ma.Grp_id
Join Mst_AcGroup MAG On MAG.GRP_NAME=ma.Grp_Name
Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no and BB.Member_code= @Membercode  and BB.YearCode = @Yearcode
Where At.Book_Type1 = 'BB' and AT.Trans_Dt  <= @ToDate AND (Select Count(*) From Mst_Account Where AC_Code = AT.Cr_Code)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode 
AND AT.EntryType = 10  
Group By ma.AC_Code,ma.AC_Name,AT.Dr_Code, AT.Cr_Code,AT.Amount,AT.Member_Code,MM.Member_Name, 
At.ExpenseType,mag.GRP_NAME,ma.Grp_Name,mag.hname,ma.EFFECT,At.Trans_No,At.Narr1,AT.Trans_Dt,At.Vouch_No,ma.Grp_id,BB.Member_code, BB.YearCode


Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo)
select	
		ma.AC_Code,
		ma.AC_Name,
		case  when ma.Op_Cal > 0 then ISNULL(ma.Op_Bal,0) else 0 end as 'Debit_Amount',
		case  when ma.Op_Cal < 0 then ISNULL(ma.Op_Bal,0) else 0 end as 'Credit_Amount',			
		ma.Grp_id,
		ma.Grp_Name,
		mag.hname,
		ma.EFFECT,
		'',
		'',
		''
		
from Mst_Account ma
Join Mst_Member MM on MM.Member_Code=ma.Member_Code
--Join Mst_AcGroup MAG On MAG.Grp_Id=ma.Grp_id
Join Mst_AcGroup MAG On MAG.GRP_NAME=ma.Grp_Name
Where ma.Member_Code = @Membercode AND Year_Code = @Yearcode
AND ma.Grp_Name NOT like 'Expense%'
Group by ma.AC_Code,ma.AC_Name,ma.Grp_id,ma.Grp_Name,mag.hname,ma.EFFECT,ma.Op_Cal,ma.Op_Bal
order by ma.AC_Code

SELECT		Ac_Code,
		    UPPER(LTRIM(RTRIM(Ac_Name))) AS 'Ac_Name',
			CASE WHEN (SUM(Debit_Amount) - SUM(Credit_Amount)) > 0 THEN Round(SUM(Debit_Amount) - SUM(Credit_Amount),2) ELSE 0.0 END as 'Debit_Amount',
			CASE WHEN (SUM(Debit_Amount) - SUM(Credit_Amount)) < 0 THEN Round(SUM(Debit_Amount) - SUM(Credit_Amount),2) ELSE 0.0 END as 'Credit_Amount',
			Group_id ,
			Groupname,
			HGroup,
			Libilities_Assets_Type
FROM	#temp 
WHERE @IsPnl = 0 OR (@IsPnl = 1 AND VoucherNo != 'P&L')
GROUP BY Ac_Code,Ac_Name,Group_id,Groupname,HGroup,Libilities_Assets_Type
ORDER BY HGroup,Ac_Code,Ac_Name
Drop Table #temp

END




























GO
/****** Object:  StoredProcedure [dbo].[rpt_TrailBalance_Yearwise]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[rpt_TrailBalance_Yearwise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[rpt_TrailBalance_Yearwise] AS' 
END
GO

--exec rpt_TrailBalance_Yearwise 'K0001','1120182019','03/31/2019'
 
 --Select * from Mst_AcGroup
 --Select * from Mst_Account
ALTER Procedure [dbo].[rpt_TrailBalance_Yearwise]
(
 @Membercode Varchar(Max),
 @Yearcode Varchar(500),
 @ToDate varchar(50)

)
AS 
  BEGIN
  SET NOCOUNT ON;
Create Table #temp
(
	Ac_Code varchar(10),
	Ac_Name varchar(500),
	Debit_Amount float,
	Credit_Amount float,
	Group_id int,
	Groupname Varchar(500),
	HGroup varchar(500),
	Libilities_Assets_Type Varchar(500),
	Narration Varchar(500),
	Trasdate varchar(100),
	VoucherNo varchar(500),
	InternalEntry Varchar(100)

)
	
--Insert only Dr Amount
Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo,InternalEntry)
select  ma.AC_Code,
		ma.AC_Name,
		Amount,
		0.0,
		ma.Grp_id,
		ma.Grp_Name,
		mag.hname,
		mag.EFFECT,
		AT.Narr1,
		AT.Trans_Dt,
		At.Vouch_No,
	    ma.InternalEntry
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Dr_Code And ma.Member_Code = @Membercode AND ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.GRP_NAME=ma.Grp_Name

Where At.Book_Type1 != 'BB' and AT.Trans_Dt  <= @ToDate AND (Select Count(*) From Mst_Account Where AC_Code = AT.CR_Code)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode  and At.Amount>0 AND Book_type1!='RC'-- and mag.EFFECT Is Not NULL
Group By ma.AC_Code,ma.AC_Name,AT.Cr_Code,Amount,AT.Member_Code,MM.Member_Name,ma.Grp_id,
ma.Grp_Name,mag.hname,mag.EFFECT,AT.Narr1,AT.Trans_Dt,At.Vouch_No,ma.InternalEntry,AT.Sr_No,AT.Trans_No


--Insert Into Cr Amount
Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo,InternalEntry)
select	
		ma.AC_Code,
		ma.AC_Name,
		0.0,
		Amount,
		ma.Grp_id,
		ma.Grp_Name,
		mag.hname,
		mag.EFFECT,
		At.Narr1,
		At.Trans_Dt,
		At.Vouch_No,
	    ma.InternalEntry

from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Cr_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
--Join Mst_AcGroup MAG On MAG.Grp_Id=ma.Grp_id
Join Mst_AcGroup MAG On MAG.GRP_NAME=ma.Grp_Name

Where At.Book_Type1 != 'BB' and AT.Trans_Dt  <= @ToDate AND (Select Count(*) From Mst_Account Where AC_Code = AT.Dr_Code)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode and At.Amount>0 AND Book_type1!='RC' -- and mag.EFFECT Is Not NULL
Group By AT.Trans_No,I.Entry_Type,At.Vouch_No,Trans_Dt,Chq_No,ma.AC_Code,ma.AC_Name,
AT.Dr_Code,Amount,AT.Member_Code,MM.Member_Name,ma.Grp_id,ma.Grp_Name,mag.hname,MAG.EFFECT,At.Narr1,AT.Trans_Dt,At.Vouch_No,ma.InternalEntry,AT.Sr_No
		

-- Insert SHAREINVESTMENT/FO INVESTMENT  DR EXCLUDE BROKER
Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo,InternalEntry)
select	
		ma.AC_Code,
		ma.AC_Name,
		0.0,
		CASE WHEN(MAG.GRP_NAME = 'BROKER' OR MAG.GRP_NAME='BROKER (C.A)') THEN BB.Net_amt
			 ELSE AT.Amount
		END as 'Amount',		
		ma.Grp_id,
		ma.Grp_Name,
		mag.hname,
		mag.EFFECT,
		At.Narr1,
		At.Trans_Dt,
		At.Vouch_No,
	    ma.InternalEntry

from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Cr_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.GRP_NAME=ma.Grp_Name	
	
Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no 
Where At.Book_Type1 = 'BB' and AT.Trans_Dt  <= @ToDate AND (Select Count(*) From Mst_Account Where AC_Code = AT.Dr_Code)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode
AND AT.EntryType != 10  and (MAG.GRP_NAME!='BROKER' and MAG.GRP_NAME!='BROKER (C.A)')
Group By ma.AC_Code,ma.AC_Name,AT.Amount,AT.Member_Code,MM.Member_Name,MAG.GRP_NAME,BB.Net_amt,ma.Grp_id,
ma.Grp_Name,mag.hname,MAG.EFFECT,At.Narr1,AT.Trans_Dt,At.Vouch_No,ma.InternalEntry,AT.Sr_No,AT.Trans_No

---- Insert Brokers SHAREINVESTMENT/FO INVESTMENT  CR EXCLUDE BROKER
Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo,InternalEntry)
select	
		ma.AC_Code,
		ma.AC_Name,		
		CASE WHEN(MAG.GRP_NAME = 'BROKER' OR MAG.GRP_NAME='BROKER (C.A)') THEN BB.Net_amt
			 ELSE AT.Amount
		END as 'Amount',
		0.0,
		ma.Grp_id,
		ma.Grp_Name,
		mag.hname,
		mag.EFFECT,
		At.Narr1,
		At.Trans_Dt,
		At.Vouch_No,
		ma.InternalEntry
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Dr_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.GRP_NAME=ma.Grp_Name

Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no 
Where At.Book_Type1 = 'BB' and AT.Trans_Dt  <= @ToDate AND (Select Count(*) From Mst_Account Where AC_Code = AT.Cr_Code)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode
AND AT.EntryType != 10 and(MAG.GRP_NAME!='BROKER' and MAG.GRP_NAME!='BROKER (C.A)')
Group By ma.AC_Code,ma.AC_Name,AT.Dr_Code,At.Cr_Code,AT.Amount,AT.Member_Code,MM.Member_Name,MAG.GRP_NAME,
BB.Net_amt,ma.Grp_id,ma.Grp_Name,mag.hname,mag.EFFECT,At.Narr1,AT.Trans_Dt,At.Vouch_No,ma.InternalEntry,AT.Sr_No,AT.Trans_No



--Insert Only Broker Amount

Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo,InternalEntry)
select	
		ma.AC_Code,
		ma.AC_Name,
		
		CASE WHEN At.Ac_Type = 'D' THEN At.Net_amt ELSE 0.0 END,
		CASE WHEN At.Ac_Type = 'C' THEN At.Net_amt ELSE 0.0 END,
		ma.Grp_id,
		ma.Grp_Name,
		mag.hname,
		mag.EFFECT,
		At.Narrat1,
		At.Trans_Dt,
		'',
		ma.InternalEntry
from BrokerBill AT
Join Ent_EntryTypes I On I.SR_NO = AT.isFNOBill
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON ma.AC_Code  = At.Broker_Code And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.Grp_Id=ma.Grp_id

Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no 
Where At.Book_Type = 'BB' and AT.Trans_Dt  <= @ToDate --AND (Select Count(*) From Mst_Account Where AC_Code = AT.Cr_Code)  > 0 
AND AT.Member_Code = @Membercode AND At.YearCode = @Yearcode

Group By ma.AC_Code,ma.AC_Name,AT.Broker_Code,At.Ac_Type,At.Net_amt,AT.Amount,AT.Member_Code,MM.Member_Name,
MAG.GRP_NAME,BB.Net_amt,ma.Grp_id,ma.Grp_Name,mag.hname,mag.EFFECT,At.Narrat1,AT.Trans_Dt,
ma.InternalEntry,ma.InternalEntry,AT.Bill_no,AT.Valan_code


--Insert  Expense
Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo,InternalEntry)
select	
		ma.AC_Code,
		ma.AC_Name,
		CASE WHEN At.ExpenseType = 'A' THEN At.Amount ELSE 0.0 END,
		CASE WHEN At.ExpenseType = 'L' THEN At.Amount ELSE 0.0 END,
		ma.Grp_id,
		ma.Grp_Name,
		mag.hname,
		mag.EFFECT,
		At.Narr1,
		At.Trans_Dt,
		At.Vouch_No,
		ma.InternalEntry
from AC_Trans AT
Join Ent_EntryTypes I On I.SR_NO = AT.InvestmentType
Join Mst_Member MM On MM.Member_Code=AT.Member_Code
Join Mst_Account ma ON (ma.AC_Code  = At.Dr_Code OR ma.AC_Code  = At.Cr_Code ) And ma.Member_Code = @Membercode  and ma.Year_Code = @Yearcode
Join Mst_AcGroup MAG On MAG.Grp_Id=ma.Grp_id

Left Join BrokerBill BB ON  At.Trans_No = BB.Trans_no 
Where At.Book_Type1 = 'BB' and AT.Trans_Dt  <= @ToDate AND (Select Count(*) From Mst_Account Where AC_Code = AT.Cr_Code)  > 0 
AND AT.Member_Code = @Membercode AND At.Year_Code = @Yearcode 
AND AT.EntryType = 10  
AND (MAG.GRP_NAME!='BROKER' and MAG.GRP_NAME!='BROKER (C.A)')
Group By ma.AC_Code,ma.AC_Name,AT.Dr_Code, AT.Cr_Code,AT.Amount,AT.Member_Code,MM.Member_Name, 
At.ExpenseType,ma.Grp_id,ma.Grp_Name,mag.hname,mag.EFFECT,At.Trans_No,At.Narr1,AT.Trans_Dt,At.Vouch_No,ma.InternalEntry
SELECT		Ac_Code,
			Ac_Name,
			sum(Debit_Amount) as'Debit_Amount',
			Sum(Credit_Amount) as 'Credit_Amount',
			Group_id ,
			Groupname,
			HGroup,
			Libilities_Assets_Type,
			InternalEntry
FROM	#temp 
GROUP BY Ac_Code,Ac_Name,Group_id,Groupname,HGroup,Libilities_Assets_Type,InternalEntry --,Credit_Amount,Debit_Amount
ORDER BY Groupname,Ac_Code,Ac_Name

--Opening Balance
--Insert into #temp (Ac_Code,Ac_Name,Debit_Amount,Credit_Amount,Group_id,Groupname,HGroup,Libilities_Assets_Type,Narration,Trasdate,VoucherNo)

select	
		ma.AC_Code,
		ma.AC_Name,
		case  when ma.Op_Cal > 0 then ISNULL(ma.Op_Bal,0) else 0 end as 'Debit_Amount',
		case  when ma.Op_Cal < 0 then ISNULL(ma.Op_Bal,0) else 0 end as 'Credit_Amount',			
		ma.Grp_id as'Group_id',
		ma.Grp_Name as 'Groupname',
		mag.hname as 'HGroup',
		mag.EFFECT as 'Libilities_Assets_Type',
		ma.InternalEntry as 'InternalEntry'		
from Mst_Account ma
Join Mst_Member MM on MM.Member_Code=ma.Member_Code
Join Mst_AcGroup MAG On MAG.Grp_Id=ma.Grp_id
Where ma.Member_Code = @Membercode AND Year_Code = @Yearcode
--AND ma.Grp_Name NOT like 'Expense%'
order by ma.Grp_Name,ma.AC_Code,ma.AC_Name




-- Insert Expenses
		--Select AT.ExpenseType, At.Trans_No,Round(At.Amount,4) as 'Amount',Ma.AC_Name,Bt.Bill_no 
		--FROM  AC_Trans AT
		--JOIN Mst_Account MA ON Ma.AC_Code = (CASE WHEN AT.ExpenseType = 'A' THEN AT.Dr_Code WHEN AT.ExpenseType = 'L' THEN At.Cr_Code END) AND MA.Member_Code = @Membercode AND MA.Year_Code = @Yearcode
		--JOIN BrokerBill_Trans BT on At.Trans_No = Bt.Trans_No
		--WHERE AT.EntryType = 10
		--AND AT.Year_Code = @yearcode
		--AND bt.TransType != 'Opening'
		--AND AT.Member_Code = @Membercode
		--Group by Bt.Bill_no, ma.AC_Name, At.Trans_No,AT.ExpenseType,At.Amount Having At.Amount > 0 
		--order by 5,1


Drop Table #temp

end


























GO
/****** Object:  StoredProcedure [dbo].[SaveBrokerage_Rate]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SaveBrokerage_Rate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[SaveBrokerage_Rate] AS' 
END
GO


ALTER procedure [dbo].[SaveBrokerage_Rate]
(
 @MemberCode Varchar(20),
 @YearCode Varchar(20),
 @AccountCode Varchar(20),
 @investmentType Varchar(30),
 @Buy float,
 @Sell float,
 @Max float,
 @Min float,
 @IsPerOrder bit
)
As
 BEGIN
 SET NOCOUNT ON;
	
	IF( (SELECT COUNT(*) FROM Brokerage_Master WHERE Year_Code  = @YearCode AND Member_Code  = @MemberCode AND AC_code = @AccountCode AND Investment_Type = @investmentType) = 0)
		BEGIN
			INSERT INTO [dbo].[Brokerage_Master]
					   ([AC_code]
					   ,[Investment_Type]
					   ,[Buy_Brokrage]
					   ,[Sell_Brokerage]
					   ,[Max_Brokrage]
					   ,[Min_Brokrge]
					   ,[Per_Order]
					   ,[Member_Code]
					   ,[Year_Code])
				 VALUES
				 (@AccountCode,@investmentType,@Buy,@Sell,@Max,@Min,@IsPerOrder,@MemberCode,@YearCode)
		END
	ELSE
		BEGIN
		     UPdate Brokerage_Master Set Buy_Brokrage=@Buy,
			                             Sell_Brokerage=@Sell,
										 Max_Brokrage=@Max,
										 Min_Brokrge=@Min,
										 Per_Order=@IsPerOrder

										 WHERE Year_Code  = @YearCode AND Member_Code  = @MemberCode AND AC_code = @AccountCode AND Investment_Type = @investmentType
		END
 ENd
  --Select * from Mst_Account where AC_Name = 'Harshil Test'
  --Select * from Brokerage_Master
  --Select * from Ent_EntryTypes




















GO
/****** Object:  StoredProcedure [dbo].[SaveRights]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SaveRights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[SaveRights] AS' 
END
GO

ALTER procedure [dbo].[SaveRights]
(
 @membercode   varchar(500),
 @scriptcode   varchar(500)
)
As
	BEGIN 
	Select @membercode
	END



















GO
/****** Object:  StoredProcedure [dbo].[ScriptLedger]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ScriptLedger]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[ScriptLedger] AS' 
END
GO
ALTER procedure [dbo].[ScriptLedger]
(
  
 @Investmenttype int,
/* @Fromdate     date  ,
 @Todate      date ,*/
 @holdingtype   varchar(10),
 @membercode   varchar(Max),
 @scriptcode   varchar(Max),
 @yearcode   varchar(500)

)
 As 
 Begin
 SET NOCOUNT ON;
 declare @scrname varchar(100),@tdate date,@debit float,@credit float,@camt float,@bqty float,@sqty float,@bdate date,@counter int,@sdate date,@typ varchar(100)
  CREATE TABLE #tmptable2
(
   Script_Name varchar(100),
   Transaction_Date varchar(12),
   Description varchar(60),Bought_Amount varchar(12),Sold_Amount varchar(12),Quantity varchar(10)
)

 Declare curname cursor read_only for 
 Select Distinct (Mst_Script.Script_Name),BrokerBill_Trans.Trans_Dt,Sum(Case When TransType='Bought' THEN Amount ELSE 0 END) As[Debit],
 Sum(Case When TransType='Sold' THEN Amount ELSE 0 END) As[Credit],

 (Sum(Case When TransType='Bought' THEN Amount ELSE 0 END) - Sum(Case When TransType='Sold' THEN Amount ELSE 0 END) )As [Closing Amount],

 Sum(CASE When TransType='Bought' Then Qty ELSE 0 END) As [BQty], Sum(CASE When TransType='Sold' Then Qty ELSE 0 END) As [SQty] 

 from BrokerBill_Trans

 join Mst_Script
 on
 BrokerBill_Trans.Script_Code=Mst_Script.Script_Code
 where isFNOBill=@Investmenttype and YearCode=@yearcode  and Ac_Type=@holdingtype and Member_code=@membercode
 Group by
 Mst_Script.Script_Name,Trans_Dt;
 open curname
 fetch next from curname into @scrname ,@tdate,@debit,@credit,@camt,@bqty,@sqty

 while @@FETCH_STATUS=0
 begin
 if(@bqty<>0)
 begin
 insert into #tmptable2(Script_Name,Transaction_Date,Description,Bought_Amount,Sold_Amount,Quantity) values(@scrname,@tdate,'Bought',@debit,0,@bqty);
 end
 if(@sqty<=@bqty and @sqty<>0)
 begin 
 
 insert into #tmptable2(Script_Name,Transaction_Date,Description,Bought_Amount,Sold_Amount,Quantity) values(@scrname,@tdate,'Sold',0,@credit,@sqty);
 end
 else if(@sqty>@bqty)
 begin
 insert into #tmptable2(Script_Name,Transaction_Date,Description,Bought_Amount,Sold_Amount,Quantity) values(@scrname,@tdate,'Sold',0,(@bqty/@sqty)*@credit,@bqty);
 insert into #tmptable2(Script_Name,Transaction_Date,Description,Bought_Amount,Sold_Amount,Quantity) values(@scrname,@tdate,'Sold',0,((@sqty-@bqty)/@sqty)*@credit,@sqty-@bqty);
 end 
 insert into #tmptable2(Script_Name,Transaction_Date,Description,Bought_Amount,Sold_Amount,Quantity) values('','','Closing Value','',Case When @camt>0 THEN @camt ELSE 0 END,'');
 if(@debit<>0 and @credit<>0)
 begin
 declare @spec float
 declare @short float
 
 --Speculation Gain---

 if(@bqty>=@sqty and @bdate<=@sdate)
 begin
 set @spec=@credit-(@debit/@bqty)*@sqty;
 end
 else if(@bqty<=@sqty)
 begin
 set @spec=(@credit/@sqty)*@bqty-@debit;
 end
 
 insert into #tmptable2(Script_Name,Transaction_Date,Description,Bought_Amount,Sold_Amount,Quantity) values('','','Speculation Gain/Loss',@spec,'','');
 end


 --Short Term--


 else if((@bqty>=@sqty) and DATEDIFF(d,@bdate,@sdate)<365 and DATEDIFF(d,@bdate,@sdate)>=0)

 begin
 set @short=@credit-(@debit/@bqty)*@sqty;
 end
 else if(@bqty<=@sqty)
 begin
 set @short=(@credit/@sqty)*@bqty-@debit;
 end
 
 insert into #tmptable2(Script_Name,Transaction_Date,Description,Bought_Amount,Sold_Amount,Quantity) values('','','Short term Gain/Loss',@short,'','');
 end

 fetch next from curname into @scrname ,@tdate,@debit,@credit,@camt,@bqty,@sqty
 end
 close curname
 deallocate curname
 select * from #tmptable2
 























GO
/****** Object:  StoredProcedure [dbo].[Securities_Transcation_Tax_Scriptwsie_Calculation]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Securities_Transcation_Tax_Scriptwsie_Calculation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Securities_Transcation_Tax_Scriptwsie_Calculation] AS' 
END
GO

--exec Securities_Transcation_Tax_Scriptwsie_Calculation '1120172018','Y0001','1','04/01/2017','03/31/2018','','0'

ALTER Procedure [dbo].[Securities_Transcation_Tax_Scriptwsie_Calculation]
(
  @Yearcode Varchar(1000),
  @Membercode Varchar(Max),
  @InvestmentCode Varchar(50),
  @FromDate Varchar(50),
  @ToDate varchar(50),
  @BrokerCode Varchar(Max),
  @HoldingType Varchar(500),
  @BSEISINNO bit=0
)
As
BEGIN
SET NOCOUNT ON;
	DECLARE @sqlstr AS NVARCHAR(max) 
	Create  TABLE #Temp
	(
		Bill_no varchar(1000),Qty varchar(150),BillDate varchar(150) ,G_Rate Varchar(50) ,GrossAmount Varchar(1000),
		STT varchar(1000),Script_Name varchar(150),  Script_Code varchar(150),
		Intraday Varchar(50),TransType varchar(50),Brokercode Varchar(500),BrokerName Varchar(500)									
	)
		   DECLARE @TempMemberCode varchar(1000)
			IF(@Membercode = '')
				BEGIN 
					Select Member_Code 
					INTO #Members 
					FROM Mst_Member Where Member_Code IN (SELECT Value FROM membercodestable(@Membercode,','))
			
					declare @tmp varchar(250)
					     SET @tmp = ''
					select @tmp = @tmp + Member_Code + ',' from #Members
				       	 SET @TempMemberCode = 	IsNULL((select SUBSTRING(@tmp, 0, LEN(@tmp))),'')
				  END
			      ELSE 
				         SET @TempMemberCode =@Membercode


				 IF(@BrokerCode<>'')
		          BEGIN
						 SET @sqlstr ='Select MA.AC_Name As''Broker Name'',BrokerBill.Broker_Code as ''Broker Code'''
				  END
				  ELSE
				  BEGIN
					     SET @sqlstr='Select  MA.AC_Name As''Broker Name'',BrokerBill.Broker_Code as ''Broker Code'''
		          END 

				  IF(@InvestmentCode=0 or @InvestmentCode=2)
		          BEGIN
				          IF(@BSEISINNO=0 AND (@InvestmentCode=0 or @InvestmentCode=2)) 
						  BEGIN
		                        SET @sqlstr=@sqlstr +',MST_Script.script_code, Mst_Script.Script_Name as ''Script Name'''	
						  END
						  ELSE IF(@BSEISINNO=1 AND @InvestmentCode=0)	
						  BEGIN
						        SET @sqlstr=@sqlstr +',MST_Script.script_code,(Mst_Script.Script_Name +''['' + Mst_Script.BSE_Code +'']''+''['' + Mst_Script.ISIN_No +'']'') as ''Script Name'''	
						  END				 
		          END
		          ELSE
		          BEGIN
		                 SET @sqlstr = @sqlstr + ',MST_Script.script_code, (Mst_Script.Script_Name + Convert(Varchar,Last_Date,103) + (case WHEN Strike_Price != 0 THEN  ''/'' + Convert(Varchar(20),Strike_Price) ELSE '''' END) +  (case WHEN OptionType != '''' THEN  ''/'' + Convert(Varchar(20),OptionType) ELSE '''' END)) As ''Script Name'''		
		          END
						 SET @sqlstr = @sqlstr + ',(BrokerBill_Trans.Bill_no) As ''Bill No'''
						 SET @sqlstr = @sqlstr + ',Convert(Varchar, BrokerBill_Trans.Trans_Dt,103) As ''Bill Date'''
						 SET @sqlstr = @sqlstr + ',SUM((isnull(BrokerBill_Trans.Qty,0))) As Qty'						 	
						 SET @sqlstr = @sqlstr + ',SUM(isnull(BrokerBill_Trans.G_Rate,0)*isnull(BrokerBill_Trans.Qty,0))/ SUM(isnull(BrokerBill_Trans.Qty,0)) As ''Gross Rate'''
						 SET @sqlstr = @sqlstr + ',SUM((isnull(BrokerBill_Trans.G_Rate,0))*(isnull(BrokerBill_Trans.Qty,0))) As ''Gross Amount'''
				  if(@InvestmentCode=0 )
				  BEGIN
						 SET @sqlstr = @sqlstr + ',cast(SUM(CASE WHEN (BrokerBill_Trans.isIntraDay)=0 then (((isnull(BrokerBill_Trans.G_Rate,0))*(isnull(BrokerBill_Trans.Qty,0)))*0.1/100)ELSE (CASE WHEN  BrokerBill_Trans.TransType=''Sold'' and (BrokerBill_Trans.isIntraDay)=1 then((isnull(BrokerBill_Trans.G_Rate,0)) * (isnull(BrokerBill_Trans.Qty,0))) * (0.025/100)Else 0 END) END)as decimal(10,4)) As STT'
				  END
				  ELSE 
				  BEGIN
						 SET @sqlstr = @sqlstr + ', SUM(
															 CASE WHEN ISNULL(BrokerBill_Trans.Strike_Price,0) = 0  and BrokerBill_Trans.OptionType IS NULL and BrokerBill_Trans.TransType = ''Sold'' 
															 	  THEN ISNULL(BrokerBill_Trans.G_Rate,0) * ISNULL(BrokerBill_Trans.Qty,0) * (0.01/100)
																  WHEN BrokerBill_Trans.TransType=''Sold'' AND ISNULL(BrokerBill_Trans.Strike_Price,0) != 0 AND BrokerBill_Trans.OptionType IS NOT NULL AND BrokerBill_Trans.OptionType != ''''
																  THEN ISNULL(BrokerBill_Trans.G_Rate,0) * ISNULL(BrokerBill_Trans.Qty,0) * (0.05/100)  
																  WHEN BrokerBill_Trans.TransType=''Sold'' AND (BrokerBill_Trans.OptionType = ''CA'' OR BrokerBill_Trans.OptionType = ''PA'')
																  THEN  isnull(BrokerBill_Trans.G_Rate,0) * isnull(BrokerBill_Trans.Qty,0) * (0.125/100)  
																  ELSE  0.0
																 
														     END
														)  As STT'
				  END	
				  			 
						 SET @sqlstr = @sqlstr + ',( CASE WHEN BrokerBill_Trans.isIntraDay = 0 OR BrokerBill_Trans.isIntraDay IS NULL THEN ''Delievery'' ELSE ''Intraday'' END) As ''Intraday Type'''
						 SET @sqlstr = @sqlstr + ',(BrokerBill_Trans.TransType) As ''Type '''
						 SET @sqlstr = @sqlstr + 'inTo #Temp from BrokerBill_Trans '
						 SET @sqlstr = @sqlstr + ' Inner join BrokerBill On BrokerBill.Trans_no=BrokerBill_Trans.Trans_No'			 
						 SET @sqlstr=  @sqlstr + ' Inner Join Mst_Script On Mst_Script.Script_Code = BrokerBill_Trans.Script_Code'
						 SET @sqlstr=  @sqlstr + ' Inner Join Mst_Account MA On MA.AC_Code=BrokerBill.Broker_Code '

						 IF(@Membercode <> '')
							SET @sqlstr=  @sqlstr + ' AND MA.Member_code in (SELECT Value FROM membercodestable(' + Char(39) + @TempMemberCode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))'
						 
						 SET @sqlstr  = @sqlstr + ' AND MA.Year_Code = ''' + @Yearcode + ''''
			
						 SET @sqlstr  = @sqlstr + ' where BrokerBill_Trans.isFNOBill = '+ Char(39) + @InvestmentCode + Char(39)
						 SET @sqlstr  = @sqlstr + ' and (BrokerBill_Trans.Trans_Dt between ' + Char(39) + @FromDate  + Char(39) + 'and' + Char(39) + @ToDate + Char(39) +')'
						 SET @sqlstr  = @sqlstr + ' and BrokerBill_Trans.Ac_Type =  (select case  when ' + Char(39) +  @HoldingType + Char(39) + ' = ''0'' then BrokerBill_Trans.Ac_Type  else '+ @HoldingType +' end)' 		        
                         SET @sqlstr  = @sqlstr + ' and (isstock NOT IN (''BF'',''CF'') OR isstock is null )'
						  SET @sqlstr = @sqlstr + ' and (IsSLBS=0 OR IsSLBS is null)'
						 SET @sqlstr = @sqlstr + ' and (FrmNm !=''IPO'')'

				  IF(@Membercode <> '')
						 SET @sqlstr  = @sqlstr + ' and BrokerBill_Trans.Member_code in (SELECT Value FROM membercodestable(' + Char(39) + @TempMemberCode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))'
 
						 SET @sqlstr  = @sqlstr + ' and BrokerBill_Trans.YearCode = ''' + @Yearcode + ''''

				  IF(@BrokerCode <> '')
				          BEGIN
					      SET @sqlstr =@sqlstr + 'and BrokerBill.Broker_Code in (SELECT Value FROM membercodestable('+ Char(39) + @BrokerCode + Char(39) + ',' + Char(39) + ',' + Char(39) + '))  ' 
				          END
						 SET @sqlstr  = @sqlstr + ' Group by BrokerBill_Trans.Bill_no,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.Trans_Dt,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.TransType,'
						 SET @sqlstr  = @sqlstr + ' Mst_Script.Script_Code,'
						 SET @sqlstr  = @sqlstr + ' Mst_Script.Script_Name,'
						 SET @sqlstr  = @sqlstr + ' Last_Date,'
						 SET @sqlstr  = @sqlstr + ' Strike_Price,'
						 SET @sqlstr  = @sqlstr + ' OptionType,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill.Broker_Code,'
						 SET @sqlstr  = @sqlstr + ' MA.AC_Name,'
						 SET @sqlstr  = @sqlstr + ' Mst_Script.BSE_Code,'
						 SET @sqlstr  = @sqlstr + ' Mst_Script.ISIN_No,'
						 SET @sqlstr  = @sqlstr + ' BrokerBill_Trans.isIntraDay '
						 SET @sqlstr=@sqlstr +    '  SELECT * FROM   #temp t order by 2,4,11'   	

						SET @sqlstr=@sqlstr +    ' DROP TABLE #temp '	
						print @sqlstr

						execute (@sqlstr)

 END

 
 



























GO
/****** Object:  StoredProcedure [dbo].[sp_Insert_AccountData]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_Insert_AccountData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_Insert_AccountData] AS' 
END
GO
ALTER PROCEDURE [dbo].[sp_Insert_AccountData]
(@xmlString VARCHAR(MAX))
AS
BEGIN
SET NOCOUNT ON;
      DECLARE @xmlHandle INT
      DECLARE @stagingTable TABLE
      (
		Member_Code	varchar	(7),Year_Code	varchar	(10), AC_Code	varchar	(7), AC_Name	varchar	(100),
		Grp_Name	varchar	(50), Grp_id	int, Effect	varchar	(1), Effect1	varchar(1), Op_Bal	money,
		Op_Cal	money, InternalEntry	int, Contact_Person	varchar	(50), Add1	varchar	(50), Add2	varchar	(50),
		Add3	varchar	(50), Mobile_No	varchar	(25), Tel_No	varchar	(25), Fax_No	varchar	(25), email	varchar	(75),
		website	varchar	(75), Pan_No	varchar	(50), UCC_Code	varchar	(50), DecimalPlaces	int, DefaultAcInBrokerBill	int,
		IsBrokeragePerUnit	int, EQB_Brokerage	money, EQS_Brokerage	money, FOB_Brokerage	money, FOS_Brokerage	money,
		IDB_Brokerage	money, IDS_Brokerage	money, Investment_Code	varchar	(7), CURB_Brokerage	float	(8),
		CURS_Brokerage	float	(8), MCXB	float	(8), MCXS	float	(8), MFB	float	(8), MFS	float	(8),
		eqintradaybuy	float	(8), eqintradaysell	float	(8)
      )
      EXEC sp_xml_preparedocument @xmlHandle output, @xmlString 
      
	  INSERT INTO @stagingTable
		SELECT  Member_Code,Year_Code,AC_Code,AC_Name,Grp_Name,Grp_id,Effect,Effect1,
		Op_Bal,Op_Cal,InternalEntry,Contact_Person,Add1,Add2,Add3,Mobile_No,
		Tel_No,Fax_No,email,website,Pan_No,UCC_Code,DecimalPlaces,DefaultAcInBrokerBill,
		IsBrokeragePerUnit,EQB_Brokerage,EQS_Brokerage,FOB_Brokerage,FOS_Brokerage,IDB_Brokerage,
		IDS_Brokerage,Investment_Code,CURB_Brokerage,CURS_Brokerage,MCXB,MCXS,MFB,MFS,eqintradaybuy,eqintradaysell   
      FROM  OPENXML (@xmlHandle, '/DataTable',1)
      WITH (
					Member_Code	varchar	(7)  '@Member_Code',Year_Code	varchar	(10)  '@Year_Code',
					AC_Code	varchar	(7) '@AC_Code',AC_Name	varchar	(100) '@AC_Name',
					Grp_Name	varchar	(50) '@Grp_Namec',Grp_id	int '@Grp_id',
					Effect	varchar	(1) '@Effect',Effect1	varchar(1) '@Effect1',
					Op_Bal	money '@Op_Bal',Op_Cal	money '@Op_Cal',
					InternalEntry	int '@InternalEntry',				Contact_Person	varchar	(50) '@Contact_Person',
					Add1	varchar	(50) '@Add1',Add2	varchar	(50) '@Add2',Add3	varchar	(50) '@Add3',
					Mobile_No	varchar	(25) '@Mobile_No',Tel_No	varchar	(25) '@Tel_No',Fax_No	varchar	(25) '@Fax_No',
					email	varchar	(75) '@email',website	varchar	(75) '@website',Pan_No	varchar	(50) '@Pan_No',
					UCC_Code	varchar	(50) '@UCC_Code',DecimalPlaces	int '@DecimalPlaces',
					DefaultAcInBrokerBill	int '@DefaultAcInBrokerBill',IsBrokeragePerUnit	int '@IsBrokeragePerUnit',
					EQB_Brokerage	money '@EQB_Brokerage',EQS_Brokerage	money '@EQS_Brokerage',
					FOB_Brokerage	money '@FOB_Brokerage',FOS_Brokerage	money '@FOS_Brokerage',
					IDB_Brokerage	money '@IDB_Brokerage',IDS_Brokerage	money '@IDS_Brokerage',
					Investment_Code	varchar	(7) '@Investment_Code',CURB_Brokerage	float	(8) '@CURB_Brokerage',
					CURS_Brokerage	float	(8) '@CURS_Brokerage',MCXB	float	(8) '@MCXB',
					MCXS	float	(8) '@MCXS',MFB	float	(8) '@MFB',MFS	float	(8) '@MFS',
					eqintradaybuy	float	(8) '@eqintradaybuy',eqintradaysell	float	(8) '@eqintradaysell'
            )

      INSERT INTO mst_account
	   (
			Member_Code,Year_Code,AC_Code,AC_Name,Grp_Name,Grp_id,Effect,Effect1,
			Op_Bal,Op_Cal,InternalEntry,Contact_Person,Add1,Add2,Add3,Mobile_No,
			Tel_No,Fax_No,email,website,Pan_No,UCC_Code,DecimalPlaces,DefaultAcInBrokerBill,
			IsBrokeragePerUnit,EQB_Brokerage,EQS_Brokerage,FOB_Brokerage,FOS_Brokerage,IDB_Brokerage,
			IDS_Brokerage,Investment_Code,CURB_Brokerage,CURS_Brokerage,MCXB,MCXS,MFB,MFS,eqintradaybuy,eqintradaysell)
           
		    (SELECT
			Member_Code,Year_Code,AC_Code,AC_Name,Grp_Name,Grp_id,Effect,Effect1,
			Op_Bal,Op_Cal,InternalEntry,Contact_Person,Add1,Add2,Add3,Mobile_No,
			Tel_No,Fax_No,email,website,Pan_No,UCC_Code,DecimalPlaces,DefaultAcInBrokerBill,
			IsBrokeragePerUnit,EQB_Brokerage,EQS_Brokerage,FOB_Brokerage,FOS_Brokerage,IDB_Brokerage,
			IDS_Brokerage,Investment_Code,CURB_Brokerage,CURS_Brokerage,MCXB,MCXS,MFB,MFS,eqintradaybuy,eqintradaysell FROM @stagingTable)
     
			EXEC sp_xml_removedocument @xmlHandle
END
























GO
/****** Object:  StoredProcedure [dbo].[Sp_TradeFileData]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Sp_TradeFileData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Sp_TradeFileData] AS' 
END
GO


--[Sp_TradeFileData] '04/01/2018', '11/05/2018','D0001','1120182019','308' 
--[Sp_TradeFileData] '04/01/2018', '10/04/2019','','','313'
--[Sp_TradeFileData] '04/01/2018', '10/04/2018','30001','1120182019','315' 
--[Sp_TradeFileData] '04/01/2018', '10/04/2018','','','336' 
--[Sp_TradeFileData] '04/01/2018', '03/31/2019','','','332'
--[Sp_TradeFileData] '04/01/2018', '03/31/2019','','','348'
--[Sp_TradeFileData] '04/01/2018', '03/31/2019','','','35'


ALTER Procedure [dbo].[Sp_TradeFileData] 
@FromDate varchar(20),
@ToDate varchar(20),
@MemberCode varchar(20),
@YearCode varchar(20),
@FormatNumber varchar(20)
As
Begin
	if @FormatNumber = '308' 
	BEGIN

		--select * from trf_body
		--select * from BrokerBill_Format_Expense


		SELECT *,convert(datetime, TradeDate, 103) FROM TRF_header Where convert(datetime, TradeDate, 103) >= @FromDate and convert(datetime, TradeDate, 103)  <= @ToDate

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate,T1.BrokRate, BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',Replace(T1.CNNO,'NSE-EQ','NSECM') AS 'BillNo', replace(T1.cnno,'NSE-EQ','') as 'cnno', T2.TradeDate,T2.SNo, ROW_NUMBER() OVER(ORDER BY  convert(date, T2.TradeDate, 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON ContractNote = replace(T1.cnno,'NSE-EQ','')
		Where convert(datetime, T2.TradeDate, 103) >= @FromDate and convert(datetime, TradeDate, 103)  <= @ToDate
		--where convert(datetime,convert(varchar,T2.TradeDate,103)) >=  '08/01/2018' and  convert(datetime,convert(varchar,T2.TradeDate,103)) <= '08/03/2018' 
		GROUP BY  T1.OrderNo, T1.S_Desc, T1.BS, T1.Qnty, T1.GrossRate, T1.BrokRate, T1.NetRate, T1.NetTotal, T1.CNNO, T1.cnno, T2.TradeDate, T2.SNo
	   

		SELECT        REPLACE(REPLACE(TRF_footer.CNNO, 'NSE-EQ', 'NSECM'), 'BSE-EQ', 'BSECM') as CNNO, REPLACE(REPLACE(TRF_footer.CNNO, 'NSE-EQ', ''), 'BSE-EQ', '') AS Bill,
		 SUM(cast(TRF_footer.Amount as float)) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, 
							 Ma.AC_Code, TRF_header.TradeDate
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name and (BrokerBill_Format_Expense.Member_Code = @MemberCode) AND (BrokerBill_Format_Expense.Year_Code = @YearCode)
								 INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode)
								 INNER JOIN
								 TRF_header ON SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(TRF_footer.CNNO) - 6) = TRF_header.ContractNote
		WHERE        (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <= @ToDate)  
		and BrokerBill_Format_Expense.BrokerBill_Format_No=@FormatNumber 
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate
		ORDER BY ISNUMERIC(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)) DESC, Try_Parse(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6) AS decimal(10, 2)), SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)
	END
	ELSE if  @FormatNumber = '313'
	BEGIN
		SELECT *,convert(datetime, TradeDate, 103) FROM TRF_header Where convert(datetime, TradeDate, 103) >= @FromDate and convert(datetime, TradeDate, 103)  <= @ToDate

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate,(cast(T1.Qnty as float)*cast(T1.GrossRate as float)) As'Gross Amount',T1.BrokRate,(cast(T1.Qnty as float)*cast(T1.BrokRate as float))  as 'BrokerAmount',T1.NetRate, ABS(T1.NetTotal) as NetTotal,T1.CNNO AS 'BillNo', 
		T1.cnno, T2.TradeDate,T2.SNo, ROW_NUMBER() OVER(ORDER BY  convert(date, T2.TradeDate, 103)) AS NameId,T2.ContractNote as'MemberName'  
		FROM TRF_body T1 LEFT JOIN TRF_header T2 ON left(ContractNote,8) = left(T1.cnno,8)
		Where convert(datetime, T2.TradeDate, 103) >= @FromDate and convert(datetime, T2.TradeDate, 103)  <= @ToDate
		--where convert(datetime,convert(varchar,T2.TradeDate,103)) >=  '08/01/2018' and  convert(datetime,convert(varchar,T2.TradeDate,103)) <= '08/03/2018' 
		GROUP BY  T1.OrderNo, T1.S_Desc, T1.BS, T1.Qnty, T1.GrossRate, T1.BrokRate, T1.NetRate, T1.NetTotal, T1.CNNO, T1.cnno, T2.TradeDate, T2.SNo,T2.ContractNote,T1.TardeNo
	    Order by T2.ContractNote

		SELECT        TRF_footer.CNNO, TRF_footer.CNNO AS 'Bill', SUM(cast(TRF_footer.Amount as float)) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, 
							 Ma.AC_Code, TRF_header.TradeDate
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
								 INNER JOIN	Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
								 INNER JOIN	 TRF_header ON left(TRF_footer.CNNO,8) = left(TRF_header.ContractNote,8)
		WHERE      Ma.Member_Code = @MemberCode AND Ma.Year_Code = @YearCode and  BrokerBill_Format_Expense.BrokerBill_Format_No='313' and   (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <= @ToDate) --AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode)
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate
		ORDER BY ISNUMERIC(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 8)) DESC, Try_Parse(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 8) AS decimal(10, 2)), SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 8)
	END 
	Else if  @FormatNumber = '315'
	BEGIN
		SELECT *,convert(datetime, TradeDate, 103) FROM TRF_header Where convert(datetime, TradeDate, 103) >= @FromDate and convert(datetime, TradeDate, 103)  <= @ToDate

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate,(cast(T1.Qnty as float)*cast(T1.GrossRate as float)) as 'GrossAmount',T1.BrokRate,(cast(T1.BrokRate as float)*cast(T1.Qnty as float)) AS 'BrokerageAmount', T1.NetRate, ABS(cast(T1.NetTotal as float))NetTotal,T1.CNNO AS 'BillNo', T1.cnno, T2.TradeDate,T2.SNo, ROW_NUMBER() OVER(ORDER BY  convert(date, T2.TradeDate, 103)) AS NameId 
		FROM TRF_body T1 LEFT JOIN TRF_header T2 ON ContractNote =  T1.cnno
		Where convert(datetime, T2.TradeDate, 103) >= @FromDate and convert(datetime, TradeDate, 103)  <= @ToDate
		--where convert(datetime,convert(varchar,T2.TradeDate,103)) >=  '08/01/2018' and  convert(datetime,convert(varchar,T2.TradeDate,103)) <= '08/03/2018' 
		GROUP BY  T1.OrderNo, T1.S_Desc, T1.BS, T1.Qnty, T1.GrossRate, T1.BrokRate, T1.NetRate, T1.NetTotal, T1.CNNO, T1.cnno, T2.TradeDate, T2.SNo
	   

		SELECT        TRF_footer.CNNO, SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(TRF_footer.CNNO) - 6) AS Bill, SUM(cast(TRF_footer.Amount as float)) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
                      TRF_header.TradeDate, BrokerBill_Format_Expense.Member_code, BrokerBill_Format_Expense.year_code
        FROM          TRF_footer 
                         INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
						 INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
						 INNER JOIN  TRF_header ON SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(TRF_footer.CNNO) - 6) = TRF_header.ContractNote
        WHERE            CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate AND CONVERT(datetime, TRF_header.TradeDate, 103) <= @ToDate AND BrokerBill_Format_Expense.BrokerBill_Format_No = '315'
			             and Ma.Member_Code = @MemberCode AND Ma.Year_Code = @YearCode
        GROUP BY         TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, BrokerBill_Format_Expense.Member_code, BrokerBill_Format_Expense.year_code, 
                         Ma.Member_Code, Ma.Year_Code   
	END
	Else if (@FormatNumber = '328')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate,BrokRate AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		where CNNO not like '%NSEF%'
		SELECT       left(ContractNote,charindex('-',ContractNote)-1) as ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '332')  -- RwadiwalFNO
	BEGIN
		
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', TRF_body.GrossRate As'GrossRate', case when TRF_body.BrokRate is null then '0' else TRF_body.BrokRate end As'Brokerage', 
        TRF_body.NetRate As'NetRate', TRF_body.NetTotal As'NetAmount', TRF_body.BFCF As'BFCF', case when TRF_body.ClosingRate is null then '0' else TRF_body.ClosingRate end As'ClosingRate'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

		
		Select TRF_footer.CNNO, SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(TRF_footer.CNNO) - 5) AS Bill, 
			cast(SUM(cast(TRF_footer.Amount as float)) as varchar) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name, Ma.AC_Code,TH.TradeDate
		from Trf_footer
		INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
		INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
		Inner JOIN   TRF_header As TH ON TH.ContractNote=SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(TRF_footer.CNNO) - 5)
		Where BrokerBill_Format_Expense.BrokerBill_Format_No = '332' --and convert(datetime,TH.TradeDate,103)>=@FromDate and convert(datetime,TH.TradeDate,103)<=@ToDate
		Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,Ma.AC_Name, Ma.AC_Code,TH.ContractNote,TH.TradeDate
		
		Order by TH.TradeDate ASC	  
	END


	Else if(@FormatNumber='336')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', case when TRF_body.GrossRate is null then TRF_body.ClosingRate else TRF_body.GrossRate end As 'GrossRate', TRF_body.BrokRate As'Brokerage', 
        TRF_body.NetRate As'NetRate', replace(TRF_body.NetTotal,'-','') As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

		
			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber and CNNO like '%NSEFO'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if(@FormatNumber='336')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', case when TRF_body.GrossRate is null then TRF_body.ClosingRate else TRF_body.GrossRate end As 'GrossRate', TRF_body.BrokRate As'Brokerage', 
        TRF_body.NetRate As'NetRate', replace(TRF_body.NetTotal,'-','') As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

		
			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber and CNNO like '%NSEFO'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if @FormatNumber = '338' or @FormatNumber = '342' or @FormatNumber = '340' or @FormatNumber = '347'
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, BrokRate AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT        ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '339')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', abs(cast(rtrim(ltrim(NetTotal)) as numeric(16,6))/cast(rtrim(ltrim(Qnty)) as int)) as GrossRate, case when BrokRate is null then '0' else BrokRate end  AS 'BrokarageRate', NetRate, abs((cast(rtrim(ltrim(NetTotal)) as numeric(16,6))/cast(rtrim(ltrim(Qnty)) as int)) * cast(rtrim(ltrim(Qnty)) as int)) AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		--select * FROM            TRF_body
		--select  cast(rtrim(ltrim(NetTotal)) as numeric(16,6))/cast(rtrim(ltrim(Qnty)) as int) as GrossRate from TRF_body
		SELECT        ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '341')
	BEGIN
		SELECT TH.ContractNote As'BillNo',TH.SNo as 'SettlementNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', TRF_body.GrossRate As'GrossRate', TRF_body.BrokRate As'Brokerage', 
        TRF_body.NetRate As'NetRate', TRF_body.NetTotal As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code='30001' and Ma.Year_Code='1120182019'
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = '341'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	
	Else if (@FormatNumber = '343')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate,  BrokRate   AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT        ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '344')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, case when BrokRate is null then 0.00 else BrokRate end  AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT        ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '346')
	BEGIN
		SELECT *,convert(datetime, TradeDate, 103) FROM TRF_header Where convert(datetime, TradeDate, 103) >= @FromDate and convert(datetime, TradeDate, 103)  <= @ToDate
		order by ContractNote

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate,T1.BrokRate, BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',T1.CNNO AS 'BillNo', REPLACE(REPLACE(T1.cnno, 'NSECM', ''), 'BSECM', '') as cnno, T2.TradeDate,T2.SNo, ROW_NUMBER() OVER(ORDER BY  convert(date, T2.TradeDate, 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON ContractNote = replace(replace(T1.cnno,'NSECM',''),'BSECM','')
		Where convert(datetime, T2.TradeDate, 103) >= @FromDate and convert(datetime, TradeDate, 103)  <= @ToDate
		order by cnno
	
	   
		 SELECT        a.CNNO as CNNO, REPLACE(REPLACE(a.CNNO, 'NSECM', ''), 'BSECM', '') AS Bill, sum(a.Amount) AS Amount, a.BrokerBill_Format_No, a.AC_Name, a.AC_Code, 
									 a.TradeDate, a.Year_Code
					FROM            (SELECT        TF.TaxText, TF.Amount, MA.AC_Name, MA.AC_Code, REPLACE(TF.CNNO, 'BSECM', 'NSECM') AS CNNO, BFE.BrokerBill_Format_No, MA.Year_Code, TRF_header.TradeDate
										FROM            Mst_Account AS MA INNER JOIN
																 BrokerBill_Format_Expense AS BFE ON BFE.Tax_code = MA.AC_Code AND MA.Member_Code = BFE.Member_code AND MA.Year_Code = BFE.year_code INNER JOIN
																 TRF_footer AS TF ON TF.TaxText = BFE.Tax_Name INNER JOIN
																 TRF_header ON REPLACE(REPLACE(TF.CNNO, 'NSECM', ''), 'BSECM', '') = TRF_header.ContractNote
										WHERE        (BFE.BrokerBill_Format_No = '346') AND (MA.Member_Code = @MemberCode) AND (MA.Year_Code = @YearCode) AND (CONVERT(datetime, TRF_header.TradeDate, 103) >= CONVERT(DATETIME, @FromDate, 102)) AND 
																 (CONVERT(datetime, TRF_header.TradeDate, 103) <= CONVERT(DATETIME, @ToDate, 102))
										GROUP BY MA.AC_Name, TF.TaxText, TF.Amount, MA.AC_Code, TF.CNNO, BFE.BrokerBill_Format_No, MA.Year_Code, TRF_header.TradeDate) AS a
		GROUP BY AC_Name,  AC_Code, a.cnno,a.BrokerBill_Format_No,a.CNNO,a.TradeDate,a.Year_Code
		Order by CNNO
		--WHERE          
		--and
	END
	Else if (@FormatNumber = '348')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', case when TRF_body.GrossRate is null then '0' else TRF_body.GrossRate end  As'GrossRate', case when TRF_body.BrokRate is null then '0' else TRF_body.BrokRate end As'Brokerage', 
        case when TRF_body.NetRate is null then '0' else TRF_body.NetRate end As'NetRate', replace(TRF_body.NetTotal,'-','') As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = '348' and CNNO like '%NSEFO'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '349')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, BrokRate  AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		where CNNO not like '%NSEF%'

		SELECT        ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END

	Else if (@FormatNumber = '350')
	BEGIN
		SELECT        distinct TRF_header.ContractNote, TRF_header.TradeDate, TRF_header.UccCode, TRF_header.SNo, TRF_header.SType, TRF_header.Exchange, TRF_header.Membercode, 
                         TRF_header.TradeMember, TRF_header.BSE_SNo, CONVERT(datetime,(TRF_header.TradeDate), 103) AS Expr1
		FROM            TRF_header INNER JOIN
								 TRF_body ON TRF_header.ContractNote =  replace(replace(TRF_body.CNNO,'NSE-EQ',''),'BSE-EQ','')
		WHERE      TRF_body.CNNO not like '%NSE-F&O%' and  (CONVERT(datetime, (TRF_header.TradeDate), 103) >= @FromDate) AND (CONVERT(datetime,(TRF_header.TradeDate), 103) 
								 <= @ToDate)
		Order by TRF_header.TradeDate

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate,case when T1.BrokRate is null then 0 else T1.BrokRate end as BrokRate, 
               case when T1.BrokRate is null then 0 else T1.BrokRate end as BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',
               replace(replace(T1.CNNO,'NSE-EQ','NSECM'),'BSE-EQ','BSECM') AS 'BillNo', replace(replace(T1.CNNO,'NSE-EQ',''),'BSE-EQ','') as cnno,
               T2.TradeDate,T2.SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime,(TradeDate) , 103)) AS NameId 
	    FROM TRF_body T1 
		       LEFT JOIN TRF_header T2 ON ContractNote = replace(replace(T1.cnno,'NSE-EQ',''),'BSE-EQ','')
		       Where T1.cnno not like '%NSE-F&O%' and convert(datetime, (TradeDate ), 103) >= @FromDate and convert(datetime, (TradeDate), 103)  <= @ToDate		
		Order by NameId
	   
	    SELECT        REPLACE(REPLACE(TRF_footer.CNNO, 'NSE-EQ', 'NSECM'), 'BSE-EQ', 'BSECM') as CNNO, REPLACE(REPLACE(TRF_footer.CNNO, 'NSE-EQ', ''), 'BSE-EQ', '') AS Bill, TRF_footer.Amount AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
								 TRF_header.TradeDate, Ma.Year_Code
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name  AND BrokerBill_Format_Expense.Member_code=@MemberCode AND BrokerBill_Format_Expense.year_code=@YearCode
								 INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND  Ma.Year_Code= @YearCode AND Ma.Member_Code=@MemberCode
								 INNER JOIN
								 TRF_header ON REPLACE(REPLACE(TRF_footer.CNNO, 'NSE-EQ', ''), 'BSE-EQ', '') = TRF_header.ContractNote
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) --and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code,TRF_footer.Amount
		ORDER BY ISNUMERIC(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)) DESC, Try_Parse(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6) AS decimal(10, 2)), SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)	
		END

	Else if (@FormatNumber = '351')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate,BrokRate AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT       left(ContractNote,charindex('-',ContractNote)-1) as ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '352')
	BEGIN
		--Arihant Capital
		SELECT        distinct LEFT(TRF_header.ContractNote, CHARINDEX('-', TRF_header.ContractNote) - 1) AS ContractNote, TRF_header.TradeDate, TRF_header.UccCode, TRF_header.SNo, 
                         TRF_header.SType, TRF_header.Exchange, TRF_header.Membercode, TRF_header.TradeMember, TRF_header.BSE_SNo
		FROM            TRF_header INNER JOIN
								 TRF_body ON left(ContractNote,charindex('-',ContractNote)-1) = replace(replace(replace(replace(TRF_body.cnno,'NSE',''),'BSE',''),'-O',''),'-N','')
		Where convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)  <= @ToDate

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate, T1.BrokRate as BrokRate, T1.BrokRate as BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',replace(replace(replace(replace(T1.CNNO,'NSE','NSECM'),'BSE','BSECM'),'BSECM-O','BSECM'),'NSE-N','NSECM') AS 'BillNo', replace(replace(replace(replace(T1.cnno,'NSE',''),'BSE',''),'-O',''),'-N','') as cnno, T2.TradeDate,T2.SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON left(ContractNote,charindex('-',ContractNote)-1) =  replace(replace(replace(replace(T1.cnno,'NSE',''),'BSE',''),'-O',''),'-N','')
		Where convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103) >= convert(datetime, cast(@FromDate as datetime), 103) and convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)  <= convert(datetime, cast(@ToDate as datetime), 103)
		--where convert(datetime,convert(varchar,T2.TradeDate,103)) >=  '08/01/2018' and  convert(datetime,convert(varchar,T2.TradeDate,103)) <= '08/03/2018' 
		--GROUP BY  T1.OrderNo, T1.S_Desc, T1.BS, T1.Qnty, T1.GrossRate, T1.BrokRate, T1.NetRate, T1.NetTotal, T1.CNNO, T1.cnno, T2.TradeDate, T2.SNo
		Order by NameId
	   
	   --select convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103) from TRF_header
		

	    SELECT        replace(replace(REPLACE(REPLACE(TRF_footer.CNNO, 'NSE', 'NSECM'), 'BSE', 'BSECM'),'BSE-O','BSECM'),'NSE-N','NSECM') as CNNO, replace(replace(REPLACE(REPLACE(TRF_footer.CNNO, 'NSE', ''), 'BSE', ''),'-O',''),'-N','') AS Bill, TRF_footer.Amount AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
								 TRF_header.TradeDate, Ma.Year_Code
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code INNER JOIN
								 TRF_header ON replace(replace(REPLACE(REPLACE(TRF_footer.CNNO, 'NSE', ''), 'BSE', ''),'-O',''),'-N','') = left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1)
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) --and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code,TRF_footer.Amount
		ORDER BY ISNUMERIC(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)) DESC, Try_Parse(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6) AS decimal(10, 2)), SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)
	END
	Else if (@FormatNumber = '353')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, BrokRate  AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT        left(ContractNote,charindex('-',ContractNote)-1) as ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '354')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, BrokRate  AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '355')
	BEGIN
	
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', isnull(TRF_body.BS,'') As'BuySale', 
		TRF_body.Qnty As'Qty', isnull(TRF_body.GrossRate,0) As'GrossRate', isnull(TRF_body.BrokRate,0) As'Brokerage', 
        TRF_body.NetRate As'NetRate', TRF_body.NetTotal As'NetAmount', case when BFCF is null then TRF_body.OrderNo else TRF_body.BFCF end As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

		SELECT        TRF_footer.CNNO, SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(TRF_footer.CNNO) - 5) AS Bill, SUM(CAST(TRF_footer.Amount AS float)) AS Amount, 
								 BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name AS 'ExpenseName', Ma.AC_Code AS 'Taxcode'
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name AND BrokerBill_Format_Expense.Member_code = @MemberCode AND
								  BrokerBill_Format_Expense.year_code = @YearCode INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND Ma.Member_Code = @MemberCode AND Ma.Year_Code = @YearCode
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber) and (right(TRF_footer.CNNO,5) = 'NSEFO')
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, TRF_footer.CNNO, Ma.AC_Name, Ma.AC_Code
		 
	END
	Else if (@FormatNumber = '360')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, BrokRate  AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT substring(ContractNote,charindex('/',ContractNote)+1,10) as ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '361')
	BEGIN
		--Kunvarji Finstock Pvt. Ltd.
		SELECT * FROM TRF_header Where convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)  <= @ToDate

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate, T1.BrokRate as BrokRate, T1.BrokRate as BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',T1.CNNO AS 'BillNo', replace(replace(T1.CNNO,'NSECM',''),'BSECM','') as cnno, T2.TradeDate,T2.SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON ContractNote = replace(replace(T1.cnno,'NSECM',''),'BSECM','')
		Where convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)  <= @ToDate
		--where convert(datetime,convert(varchar,T2.TradeDate,103)) >=  '08/01/2018' and  convert(datetime,convert(varchar,T2.TradeDate,103)) <= '08/03/2018' 
		--GROUP BY  T1.OrderNo, T1.S_Desc, T1.BS, T1.Qnty, T1.GrossRate, T1.BrokRate, T1.NetRate, T1.NetTotal, T1.CNNO, T1.cnno, T2.TradeDate, T2.SNo
		Order by NameId
	   
	    SELECT        TRF_footer.CNNO as CNNO, REPLACE(REPLACE(TRF_footer.CNNO, 'NSECM', ''), 'BSECM', '') AS Bill,sum(TRF_footer.Amount) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
								 TRF_header.TradeDate, Ma.Year_Code
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code AND BrokerBill_Format_Expense.Member_code = Ma.Member_code INNER JOIN
								 TRF_header ON REPLACE(REPLACE(TRF_footer.CNNO, 'NSECM', ''), 'BSECM', '') = TRF_header.ContractNote
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code
		ORDER BY ISNUMERIC(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)) DESC, Try_Parse(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6) AS decimal(10, 2)), SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)
	END
	Else if (@FormatNumber = '359')
	BEGIN
		--JM FINANCIAL SERVICES LTD
		SELECT left(ContractNote,charindex('-',ContractNote)-1) as ContractNote,TradeDate,UccCode,SNo,SType,Exchange,Membercode,TradeMember,BSE_SNo 
		FROM TRF_header 
		Where convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)  <= @ToDate

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate, T1.BrokRate as BrokRate, T1.BrokRate as BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',T1.CNNO AS 'BillNo', replace(replace(T1.CNNO,'NSECM',''),'BSECM','') as cnno, T2.TradeDate,T2.SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON left(ContractNote,charindex('-',ContractNote)-1) = replace(replace(T1.cnno,'NSECM',''),'BSECM','')
		Where convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)  <= @ToDate
		--where convert(datetime,convert(varchar,T2.TradeDate,103)) >=  '08/01/2018' and  convert(datetime,convert(varchar,T2.TradeDate,103)) <= '08/03/2018' 
		--GROUP BY  T1.OrderNo, T1.S_Desc, T1.BS, T1.Qnty, T1.GrossRate, T1.BrokRate, T1.NetRate, T1.NetTotal, T1.CNNO, T1.cnno, T2.TradeDate, T2.SNo
		Order by NameId
	   
	    SELECT        TRF_footer.CNNO as CNNO, REPLACE(REPLACE(TRF_footer.CNNO, 'NSECM', ''), 'BSECM', '') AS Bill,sum(TRF_footer.Amount) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
								 TRF_header.TradeDate, Ma.Year_Code
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code AND BrokerBill_Format_Expense.Member_code = Ma.Member_code INNER JOIN
								 TRF_header ON REPLACE(REPLACE(TRF_footer.CNNO, 'NSECM', ''), 'BSECM', '') = left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1)
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code
		ORDER BY ISNUMERIC(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)) DESC, Try_Parse(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6) AS decimal(10, 2)), SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)
	END
	Else if (@FormatNumber = '364')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, BrokRate  AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT left(ContractNote,charindex('-',ContractNote)-1) as ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '365')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, BrokRate  AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '366')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, BrokRate  AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '367')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, case when BrokRate is null then '0' else BrokRate end  AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '368')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '369')
	BEGIN
		--NIRMAL BANG SECURITIES PVT.LTD. EQUITY
		SELECT left(ContractNote,charindex('-',ContractNote)-1) as ContractNote,TradeDate,UccCode,SNo,SType,Exchange,Membercode,TradeMember,BSE_SNo 
		FROM TRF_header 
		Where convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)  <= @ToDate

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate, T1.BrokRate as BrokRate, T1.BrokRate as BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',REPLACE(REPLACE(replace(T1.CNNO,'-',''),'NSE','NSECM'),'BSE','BSECM') AS 'BillNo', REPLACE(replace(replace(T1.CNNO,'NSE',''),'BSE',''),'-','') as cnno, TradeDate,SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON left(T2.ContractNote,charindex('-',T2.ContractNote)-1) = REPLACE(replace(replace(T1.cnno,'NSE',''),'BSE',''),'-','')
		Where convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103)  <= @ToDate
		--where convert(datetime,convert(varchar,T2.TradeDate,103)) >=  '08/01/2018' and  convert(datetime,convert(varchar,T2.TradeDate,103)) <= '08/03/2018' 
		--GROUP BY  T1.OrderNo, T1.S_Desc, T1.BS, T1.Qnty, T1.GrossRate, T1.BrokRate, T1.NetRate, T1.NetTotal, T1.CNNO, T1.cnno, T2.TradeDate, T2.SNo
		Order by NameId
	   
	    SELECT        replace(replace(REPLACE(TRF_footer.CNNO,'-',''),'BSE','BSECM'),'NSE','NSECM') as CNNO, REPLACE(REPLACE(REPLACE(TRF_footer.CNNO, 'NSE', ''), 'BSE', ''),'-','') AS Bill,sum(TRF_footer.Amount) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
								 TRF_header.TradeDate, Ma.Year_Code
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code AND BrokerBill_Format_Expense.Member_code = Ma.Member_code INNER JOIN
								 TRF_header ON replace(REPLACE(REPLACE(TRF_footer.CNNO, 'NSE', ''), 'BSE', ''),'-','') = left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1)
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code
		ORDER BY ISNUMERIC(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)) DESC, Try_Parse(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6) AS decimal(10, 2)), SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)
	END
	Else if (@FormatNumber = '371')
	BEGIN
		--R.WADIWALA SECURITIES PVT.LTD. EQUITY
		SELECT      distinct  TRF_header.ContractNote, TRF_header.TradeDate, TRF_header.UccCode, TRF_header.SNo, TRF_header.SType, TRF_header.Exchange, TRF_header.Membercode, 
                         TRF_header.TradeMember, TRF_header.BSE_SNo
		FROM            TRF_header INNER JOIN
									 (SELECT        Replace(REPLACE(REPLACE(T1.CNNO, '-', ''), 'NSEEQUITY', 'NSECM'),'BSEEQUITY','BSECM') AS 'BillNo', Replace(REPLACE(T1.CNNO, 'NSEEQUITY', ''),'BSEEQUITY', '') AS cnno
									   FROM            TRF_body AS T1 LEFT OUTER JOIN
                                                         TRF_header AS T2 ON T2.ContractNote =  Replace(REPLACE(T1.CNNO, 'NSEEQUITY', ''),'BSEEQUITY', '')) AS Detail ON TRF_header.ContractNote = Detail.cnno 
		Where convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103)  <= @ToDate

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate, T1.BrokRate as BrokRate, T1.BrokRate as BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',replace(REPLACE(replace(T1.CNNO,'-',''),'NSEEQUITY','NSECM'),'BSEEQUITY','BSECM') AS 'BillNo',replace(replace(T1.CNNO,'NSEEQUITY',''),'BSEEQUITY','') as cnno, TradeDate,SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON T2.ContractNote =  Replace(REPLACE(T1.CNNO, 'NSEEQUITY', ''),'BSEEQUITY', '')
		Where convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103)  <= @ToDate
		--where convert(datetime,convert(varchar,T2.TradeDate,103)) >=  '08/01/2018' and  convert(datetime,convert(varchar,T2.TradeDate,103)) <= '08/03/2018' 
		--GROUP BY  T1.OrderNo, T1.S_Desc, T1.BS, T1.Qnty, T1.GrossRate, T1.BrokRate, T1.NetRate, T1.NetTotal, T1.CNNO, T1.cnno, T2.TradeDate, T2.SNo
		Order by NameId
	   
	    SELECT        replace(REPLACE(TRF_footer.CNNO,'NSEEQUITY','NSECM'),'BSEEQUITY','BSECM') as CNNO, replace(REPLACE(TRF_footer.CNNO, 'NSEEQUITY', ''),'BSEEQUITY', '') AS Bill,sum(TRF_footer.Amount) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
								 TRF_header.TradeDate, Ma.Year_Code
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code AND BrokerBill_Format_Expense.Member_code = Ma.Member_code INNER JOIN
								 TRF_header ON replace(REPLACE(TRF_footer.CNNO, 'NSEEQUITY', ''),'BSEEQUITY', '') = TRF_header.ContractNote
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code
		ORDER BY ISNUMERIC(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)) DESC, Try_Parse(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6) AS decimal(10, 2)), SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)
	END
	Else if (@FormatNumber = '372')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
		Else if (@FormatNumber = '374')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', isnull(BrokRate,'0')  AS 'Brokerage',isnull(GrossRate,'0')  AS 'GrossRate',
		        TRF_body.NetRate As'NetRate', TRF_body.NetTotal As'NetAmount', TRF_body.BFCF As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = '374' and CNNO like '%NSEFO'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '373')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO, TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%NSECM'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '376')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO, TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '378')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%BSECM'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '379')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull((cast(BrokRate as float)) /cast(Qnty as float),'0') AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%NSECM'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '380')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', TRF_body.GrossRate As'GrossRate', isnull(TRF_body.BrokRate,0) As'Brokerage', 
        case when TRF_body.NetRate is null then TRF_body.GrossRate else TRF_body.NetRate end As'NetRate', TRF_body.NetTotal As'NetAmount', TRF_body.OrderNo As'BFCF', case when TRF_body.ClosingRate is null then TRF_body.GrossRate 
		else TRF_body.ClosingRate end As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = '380' and CNNO like '%NSEFO'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '383')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, 
			isnull(abs(cast(GrossRate as numeric(12,2)) - cast(NetRate as numeric(12,2))),'0')  AS 'BrokarageRate', 
			isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '384')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '385')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '386')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '387')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '388')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', TRF_body.GrossRate As'GrossRate', TRF_body.BrokRate As'Brokerage', 
        TRF_body.NetRate As'NetRate', TRF_body.NetTotal As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = '388' and CNNO like '%NSEFO'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '389')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '390')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', TRF_body.GrossRate As'GrossRate', TRF_body.BrokRate As'Brokerage', 
        TRF_body.NetRate As'NetRate', TRF_body.NetTotal As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber and CNNO like '%NSEFO'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '392')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', isnull(GrossRate,'0') AS 'GrossRate', isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '393')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '394')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', case when TRF_body.GrossRate is null then TRF_body.ClosingRate else TRF_body.GrossRate end As 'GrossRate', TRF_body.BrokRate As'Brokerage', 
        TRF_body.NetRate As'NetRate', replace(TRF_body.NetTotal,'-','') As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber and CNNO like '%NSEFO'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '395')
	BEGIN
		--Kantilal Chhaganlal Securities Pvt. Ltd.-BSE-EQUITY-TRADEFILE-2018
		SELECT        TRF_header.ContractNote, TRF_header.TradeDate, TRF_header.UccCode, TRF_header.SNo, TRF_header.SType, TRF_header.Exchange, TRF_header.Membercode, 
                         TRF_header.TradeMember, TRF_header.BSE_SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103)) AS NameId 
		FROM            TRF_header INNER JOIN
									 (SELECT        distinct REPLACE(REPLACE(T1.CNNO, '-', ''), 'BSEEQ', 'BSECM') AS 'BillNo', REPLACE(T1.CNNO, 'BSEEQ', '') AS cnno
									   FROM            TRF_body AS T1 LEFT OUTER JOIN
                                                         TRF_header AS T2 ON T2.ContractNote = REPLACE(T1.CNNO, 'BSEEQ', '')) AS Detail ON TRF_header.ContractNote = Detail.cnno 
		Where convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103)  <= @ToDate
		order by NameId

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate, T1.BrokRate as BrokRate, T1.BrokRate as BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',REPLACE(replace(T1.CNNO,'-',''),'BSEEQ','BSECM') AS 'BillNo',replace(T1.CNNO,'BSEEQ','') as cnno, TradeDate,SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON T2.ContractNote = replace(T1.cnno,'BSEEQ','')
		Where convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103)  <= @ToDate
		--where convert(datetime,convert(varchar,T2.TradeDate,103)) >=  '08/01/2018' and  convert(datetime,convert(varchar,T2.TradeDate,103)) <= '08/03/2018' 
		--GROUP BY  T1.OrderNo, T1.S_Desc, T1.BS, T1.Qnty, T1.GrossRate, T1.BrokRate, T1.NetRate, T1.NetTotal, T1.CNNO, T1.cnno, T2.TradeDate, T2.SNo
		Order by NameId
	   
	    SELECT        REPLACE(TRF_footer.CNNO,'BSEEQ','BSECM') as CNNO, REPLACE(TRF_footer.CNNO, 'BSEEQ', '') AS Bill,sum(TRF_footer.Amount) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
								 TRF_header.TradeDate, Ma.Year_Code
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code AND BrokerBill_Format_Expense.Member_code = Ma.Member_code INNER JOIN
								 TRF_header ON REPLACE(TRF_footer.CNNO, 'BSEEQ', '') = TRF_header.ContractNote
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code
		ORDER BY ISNUMERIC(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)) DESC, Try_Parse(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6) AS decimal(10, 2)), SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)
	END
	Else if (@FormatNumber = '396')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%NSECM' or  CNNO like '%BSECM'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '398')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		replace(TRF_body.Qnty,'-','') As'Qty', case when TRF_body.GrossRate is null then TRF_body.ClosingRate else TRF_body.GrossRate end As 'GrossRate', TRF_body.BrokRate As'Brokerage', 
        TRF_body.NetRate As'NetRate', replace(TRF_body.NetTotal,'-','') As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber and CNNO like '%NSEFO'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '399')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		replace(TRF_body.Qnty,'-','') As'Qty', case when TRF_body.GrossRate is null then TRF_body.ClosingRate else TRF_body.GrossRate end As 'GrossRate', TRF_body.BrokRate As'Brokerage', 
        TRF_body.GrossRate As'NetRate', replace(TRF_body.NetTotal,'-','') As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber and CNNO like '%NSEFO'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '402')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%BSE-EQ' or CNNO like '%NSE-EQ'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '403')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '405')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	
	Else if (@FormatNumber = '406')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '407')
	BEGIN
		SELECT        left(ContractNote,charindex('-',ContractNote)-1)  AS ContractNote, TRF_header.TradeDate, TRF_header.UccCode, TRF_header.SNo, TRF_header.SType, TRF_header.Exchange, TRF_header.Membercode, 
                         TRF_header.TradeMember, TRF_header.BSE_SNo,BillNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103)) AS NameId 
		FROM            TRF_header INNER JOIN
									 (SELECT        distinct REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(T1.CNNO, 'BSE', 'BSECM'),'NSE-N','NSECM'),'NSE-D','NSECM'),'BSE-O','BSECM'),'-D','') AS 'BillNo', REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(T1.CNNO, 'BSE', ''),'NSE-N',''),'NSE-D',''),'-O',''),'-D','') AS cnno
									   FROM            TRF_body AS T1 LEFT OUTER JOIN
                                                         TRF_header AS T2 ON left(T2.ContractNote,charindex('-',T2.ContractNote)-1) = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(T1.CNNO, 'BSE', ''),'NSE-N',''),'NSE-D',''),'-O',''),'-D','')) AS Detail ON left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote )-1)= Detail.cnno 
		Where convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103)  <= @ToDate
		order by NameId

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate, T1.BrokRate as BrokRate, T1.BrokRate as BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(T1.CNNO, 'BSE', 'BSECM'),'NSE-N','NSECM'),'NSE-D','NSECM'),'-O',''),'-D','') AS 'BillNo',REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(T1.CNNO, 'BSE', ''),'NSE-N',''),'NSE-D',''),'-O',''),'-D','') as cnno, TradeDate,SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON left(T2.ContractNote,charindex('-',T2.ContractNote)-1) = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(T1.CNNO, 'BSE', ''),'NSE-N',''),'NSE-D',''),'-O',''),'-D','')
		Where convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103)  <= @ToDate
		--where convert(datetime,convert(varchar,T2.TradeDate,103)) >=  '08/01/2018' and  convert(datetime,convert(varchar,T2.TradeDate,103)) <= '08/03/2018' 
		--GROUP BY  T1.OrderNo, T1.S_Desc, T1.BS, T1.Qnty, T1.GrossRate, T1.BrokRate, T1.NetRate, T1.NetTotal, T1.CNNO, T1.cnno, T2.TradeDate, T2.SNo
		Order by NameId
	   
	    --SELECT  REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TRF_footer.CNNO, 'BSE', 'BSECM'),'NSE-N','NSECM'),'NSE-D','NSECM'),'BSE-O','BSECM'),'-D','') as CNNO, REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TRF_footer.CNNO, 'BSE-O', ''),'NSE-N',''),'NSE-D',''),'BSE',''),'BSE-D','') AS Bill,sum(TRF_footer.Amount) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
		--						 TRF_header.TradeDate, Ma.Year_Code,ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		--FROM            TRF_footer INNER JOIN
		--						 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name INNER JOIN
		--						 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code AND BrokerBill_Format_Expense.Member_code = Ma.Member_code INNER JOIN
		--						 TRF_header ON REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TRF_footer.CNNO, 'BSE-O', ''),'NSE-N',''),'NSE-D',''),'BSE',''),'BSE-D','') = left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1)
		--WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		--GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code
		--ORDER BY NameId

		SELECT  REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TRF_footer.CNNO, 'BSE', 'BSECM'),'NSE-N','NSECM'),'NSE-D','NSECM'),'BSE-O','BSECM')
				,'-D','') as CNNO, 
				REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TRF_footer.CNNO, 'BSE-O', ''),'NSE-N',''),'NSE-D',''),'BSE',''),'-D','') AS Bill,
				sum(TRF_footer.Amount) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
				TRF_header.TradeDate, Ma.Year_Code,ROW_NUMBER() OVER(ORDER BY  convert(datetime, 
				cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM  TRF_footer INNER JOIN
				BrokerBill_Format_Expense ON LTRIM(RTRIM(TRF_footer.TaxText)) = LTRIM(RTRIM(BrokerBill_Format_Expense.Tax_Name))
		INNER JOIN
				Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code AND BrokerBill_Format_Expense.Member_code = Ma.Member_code INNER JOIN
				TRF_header ON REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TRF_footer.CNNO, 'BSE-O', ''),'NSE-N',''),'NSE-D',''),'BSE',''),'-D','') = left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1)
		WHERE (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  
		AND (BrokerBill_Format_Expense.Member_Code = @MemberCode) 
		AND (BrokerBill_Format_Expense.Year_Code = @YearCode) 
		and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) 
				AND (CONVERT(datetime, TRF_header.TradeDate, 103) <= @ToDate)
				GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code
				ORDER BY NameId	END
	Else if (@FormatNumber = '408')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '409')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '410')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '411')
	BEGIN
		--NIRMAL BANG SECURITIES PVT.LTD. EQUITY
		SELECT left(ContractNote,charindex('-',ContractNote)-1) as ContractNote,TradeDate,UccCode,SNo,SType,Exchange,Membercode,TradeMember,BSE_SNo 
		FROM TRF_header 
		Where convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)  <= @ToDate

		

		
		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate,(cast(T1.Qnty as float)*cast(T1.GrossRate as float)) As'Gross Amount',T1.BrokRate,(cast(T1.Qnty as float)*cast(T1.BrokRate as float))  as 'BrokerAmount',T1.NetRate, ABS(T1.NetTotal) as NetTotal,replace(replace(REPLACE(replace(replace(T1.cnno,'NSE',''),'BSE',''),'-N',''),'-D',''),'-O','') AS 'BillNo', replace(replace(REPLACE(replace(replace(T1.cnno,'NSE',''),'BSE',''),'-N',''),'-D',''),'-O','') as cnno, T2.TradeDate,T2.SNo,T2.BSE_SNo as BSE_SNo,  ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId,T2.ContractNote as'MemberName'   
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON left(T2.ContractNote,charindex('-',T2.ContractNote)-1) = replace(replace(REPLACE(replace(replace(T1.cnno,'NSE',''),'BSE',''),'-N',''),'-D',''),'-O','')
		Where (T1.S_Desc not like '%FUTSTK%' and T1.S_Desc not like '%FUTIST%' and T1.S_Desc not like '%FUTCUR%' and T1.S_Desc not like '%OPTIDX%' and T1.S_Desc not like '%OPTSTK%') and convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103)  <= @ToDate
		Order by left(T2.ContractNote,charindex('-',T2.ContractNote)-1)

		drop table tempTable

	    SELECT        replace(replace(replace(REPLACE(REPLACE(TRF_footer.CNNO, 'NSE', ''), 'BSE', ''),'-N',''),'-D',''),'-O','') as CNNO, replace(replace(replace(REPLACE(REPLACE(TRF_footer.CNNO, 'NSE', ''), 'BSE', ''),'-N',''),'-D',''),'-O','') AS Bill,TRF_footer.Amount as Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
								 TRF_header.TradeDate,replace(replace(replace(replace(TRF_header.ContractNote,'#',' '),left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1),''),'-',''),'@','-') as'Member_Name'
		into tempTable
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name  AND BrokerBill_Format_Expense.Member_code = @MemberCode AND BrokerBill_Format_Expense.Year_code = @YearCode  
								 INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code AND BrokerBill_Format_Expense.Member_code = Ma.Member_code 
								 INNER JOIN
								 TRF_header ON ltrim(replace(replace(replace(REPLACE(REPLACE(TRF_footer.CNNO, 'NSE', ''), 'BSE', ''),'-N',''),'-D',''),'-O','')) = ltrim(left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1))
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber) AND (Ma.Year_Code = @YearCode) and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		ORDER BY left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1)

		SELECT        CNNO, Bill, Sum(cast(Amount as float)) AS Amount, BrokerBill_Format_No, AC_Name, AC_Code, TradeDate, Member_Name
		FROM            tempTable
		GROUP BY CNNO, Bill, BrokerBill_Format_No, AC_Name, AC_Code, TradeDate, Member_Name
		order by Bill
	END
	Else if (@FormatNumber = '412')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '413')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '414')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, abs(cast(GrossRate as numeric(12,4)) - cast(NetRate as numeric(12,4))) AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(cast(NetRate as numeric(12,2))*cast(REPLACE(Qnty, '-', '') as numeric(12,2)),'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%NSECM'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '415')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		replace(TRF_body.Qnty,'-','') As'Qty', case when TRF_body.GrossRate is null then TRF_body.ClosingRate else TRF_body.GrossRate end As 'GrossRate', isnull(TRF_body.BrokRate,'0') As'Brokerage', 
        TRF_body.GrossRate As'NetRate', replace(TRF_body.NetTotal,'-','') As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber and CNNO like '%NSEFO'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '418')
	BEGIN
		SELECT        ContractNote  AS ContractNote, TRF_header.TradeDate, TRF_header.UccCode, TRF_header.SNo, TRF_header.SType, TRF_header.Exchange, TRF_header.Membercode, 
                         TRF_header.TradeMember, TRF_header.BSE_SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103)) AS NameId 
		FROM            TRF_header INNER JOIN
									 (SELECT        distinct T1.CNNO AS 'BillNo', T1.CNNO AS cnno
									   FROM            TRF_body AS T1 LEFT OUTER JOIN
                                                         TRF_header AS T2 ON T2.ContractNote = replace(replace(T1.CNNO,'BSECM',''),'NSECM','') ) AS Detail ON TRF_header.ContractNote= replace(replace(Detail.cnno ,'BSECM',''),'NSECM','') 
		Where convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103)  <= @ToDate
		order by NameId

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate,abs(cast(T1.GrossRate as numeric(12,4)) - cast(T1.NetRate as numeric(12,4)))   as BrokRate, abs(cast(T1.GrossRate as numeric(12,4)) - cast(T1.NetRate as numeric(12,4)))   as BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',T1.CNNO AS 'BillNo',REPLACE(REPLACE(T1.CNNO, 'BSECM', ''),'NSECM','') as cnno, TradeDate,SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON T2.ContractNote =  replace(replace(T1.CNNO,'BSECM',''),'NSECM','')
		Where convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103)  <= @ToDate
		--where convert(datetime,convert(varchar,T2.TradeDate,103)) >=  '08/01/2018' and  convert(datetime,convert(varchar,T2.TradeDate,103)) <= '08/03/2018' 
		--GROUP BY  T1.OrderNo, T1.S_Desc, T1.BS, T1.Qnty, T1.GrossRate, T1.BrokRate, T1.NetRate, T1.NetTotal, T1.CNNO, T1.cnno, T2.TradeDate, T2.SNo
		Order by NameId
	   
	    SELECT       TRF_footer.CNNO  as CNNO, REPLACE(REPLACE(TRF_footer.CNNO, 'BSECM', ''),'NSECM','') AS Bill,sum(TRF_footer.Amount) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
								 TRF_header.TradeDate, Ma.Year_Code,ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code AND BrokerBill_Format_Expense.Member_code = Ma.Member_code INNER JOIN
								 TRF_header ON replace(replace(TRF_footer.CNNO,'BSECM',''),'NSECM','') = TRF_header.ContractNote
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code
		ORDER BY NameId
	END
	Else if (@FormatNumber = '420')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
        Else if (@FormatNumber = '421')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '426')  -- Nirmalbung FNO
	BEGIN
				SELECT        LEFT(TH.ContractNote, CHARINDEX('-', TH.ContractNote) - 1) AS 'BillNo', TH.TradeDate, TRF_body.S_Desc AS 'ScriptName', TRF_body.BS AS 'BuySale', 
								 TRF_body.Qnty AS 'Qty', TRF_body.GrossRate, TRF_body.BrokRate AS 'Brokerage', TRF_body.NetRate, TRF_body.NetTotal AS 'NetAmount', case when OrderNo ='B/F' then 'BF' else case when OrderNo ='C/F' then 'CF' else null end end as BFCF, 
								 TRF_body.ClosingRate,TRF_body.CNNO,TH.ContractNote as'MemberName'
				FROM            TRF_body INNER JOIN
										 TRF_header AS TH ON LEFT(TH.ContractNote, CHARINDEX('-', TH.ContractNote) - 1) = REPLACE(TRF_body.CNNO, 'NSEF-F', '')
			    Where --(TRF_body.S_Desc like '%FUT%'  or  TRF_body.S_Desc like '%OPTIDX%' or TRF_body.S_Desc like '%OPTSTK%') 
				convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate
				

				drop table tempTable

				SELECT        REPLACE(TRF_footer.CNNO, 'NSEF-F', '') as CNNO, REPLACE(TRF_footer.CNNO, 'NSEF-F', '') AS Bill,TRF_footer.Amount as Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
										 TRF_header.TradeDate,replace(replace(replace(replace(TRF_header.ContractNote,'#',' '),left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1),''),'-',''),'@','-') as'Member_Name'
				into tempTable
				FROM            TRF_footer INNER JOIN
										 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name  AND BrokerBill_Format_Expense.Member_code = @MemberCode AND BrokerBill_Format_Expense.Year_code = @YearCode  
										 INNER JOIN
										 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code AND BrokerBill_Format_Expense.Member_code = Ma.Member_code 
										 INNER JOIN
										 TRF_header ON ltrim(REPLACE(TRF_footer.CNNO, 'NSEF-F', '')) = ltrim(left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1))
				WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber) AND (Ma.Year_Code = @YearCode) and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
				ORDER BY left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1)

				SELECT        CNNO, Bill, Sum(cast(Amount as float)) AS Amount, BrokerBill_Format_No, AC_Name, AC_Code, TradeDate, Member_Name
				FROM            tempTable
				GROUP BY CNNO, Bill, BrokerBill_Format_No, AC_Name, AC_Code, TradeDate, Member_Name
				order by Bill
				
	END
	Else if (@FormatNumber = '429')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT       left(ContractNote,charindex('-',ContractNote)-1) as ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
Else if (@FormatNumber = '430')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT  ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
Else if (@FormatNumber = '431')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT  ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '435')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '436')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '437')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '439')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', case when TRF_body.GrossRate is null then '0' else  TRF_body.GrossRate end As'GrossRate', case when TRF_body.BrokRate is null then '0' else TRF_body.BrokRate end As'Brokerage', 
        TRF_body.NetRate As'NetRate', TRF_body.NetTotal As'NetAmount', case when TRF_body.BFCF is null then TRF_body.orderno else TRF_body.BFCF end AS 'BFCF', case when TRF_body.ClosingRate is null then '0' else TRF_body.ClosingRate end As'ClosingRate',case when TH.SNo is null then 'BillNo' else TH.SNo end As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

		SELECT        TRF_footer.CNNO, SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(TRF_footer.CNNO) - 5) AS Bill, cast(SUM(CAST(TRF_footer.Amount AS float)) as nvarchar(50)) AS Amount, 
								 BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name , Ma.AC_Code 
		FROM            TRF_footer INNER JOIN
								  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name AND BrokerBill_Format_Expense.Member_code = @MemberCode AND
								  BrokerBill_Format_Expense.year_code = @YearCode 
								  INNER JOIN
								  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND Ma.Member_Code = @MemberCode AND Ma.Year_Code = @YearCode
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber) and (right(TRF_footer.CNNO,5) = 'NSEFO')
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, TRF_footer.CNNO, Ma.AC_Name, Ma.AC_Code
		ORDER BY TRF_footer.CNNO
	END
	Else if (@FormatNumber = '441')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', cast(ABS(cast(isnull(NetTotal,'0') as numeric(12,2)) / cast(isnull(replace(Qnty,'D',''),'0') as numeric(12,2))) as varchar(50)) AS 'NetRate' , isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		select * from trf_body
		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '442')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '443')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%BSE'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '444')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%BSECM'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '450')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if(@FormatNumber='453')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', case when TRF_body.GrossRate is null then TRF_body.ClosingRate else TRF_body.GrossRate end As 'GrossRate', TRF_body.BrokRate As'Brokerage', 
        TRF_body.NetRate As'NetRate', replace(TRF_body.NetTotal,'-','') As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

		
		Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
		SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
		Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
		 from Trf_footer
		 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
		  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
		  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
		  Where BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber and CNNO like '%NSEFO'
	      Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '454')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		where CNNO like '%NSECM' or CNNO like '%BSECM'
		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '457')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '461')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '462')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate',cast(isnull(NetRate,'0') as numeric(12,2)) * cast(isnull(Qnty,'0') as numeric(12,2)) AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body 

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '466')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%BSECM'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '497')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%BSECM'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '467')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%NSECM'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '498')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%NSECM'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '468')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%NSECM'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '471')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', rtrim(ltrim(replace(TRF_body.S_Desc,'00:00:00',''))) As'ScriptName', case when TRF_body.BS='B' then 'Buy' else 'Sell' end as 'BuySale', 
		TRF_body.Qnty As'Qty', case when TRF_body.GrossRate is null then TRF_body.NetRate else TRF_body.GrossRate end As'GrossRate', TRF_body.BrokRate As'Brokerage', 
        TRF_body.NetRate As'NetRate', TRF_body.NetTotal As'NetAmount', case when TRF_body.OrderNo='0' then 'BF'  else TRF_body.OrderNo end  As'BFCF', case when TRF_body.ClosingRate is null then 0 else TRF_body.ClosingRate end  As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(REPLACE(TRF_body.CNNO, 'NSE-F&OBF', ''),'NSE-F&O','')
		Where  cast(TRF_body.Qnty as int) > 0 and cast(left(right(TH.TradeDate,7),2) + '/' + left(TH.TradeDate,2) + '/' + right(TH.TradeDate,4) as datetime) >= @FromDate and cast(left(right(TH.TradeDate,7),2) + '/' + left(TH.TradeDate,2) + '/' + right(TH.TradeDate,4) as datetime) <= @ToDate

		---Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate
		order by TH.ContractNote
		--select cast(right(left(TradeDate,7),2) + '/' + right(TradeDate,2) + '/' + left(TradeDate,4) as datetime) From TRF_header 
		SELECT        replace(REPLACE(TRF_footer.CNNO, 'NSE-F&O', ''),'NSE-F&OBF', '') as CNNO, replace(REPLACE(TRF_footer.CNNO, 'NSE-F&O', ''),'NSE-F&OBF', '') AS Bill,cast(sum(TRF_footer.Amount) as varchar(50)) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
								 TRF_header.TradeDate, Ma.Year_Code
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code AND BrokerBill_Format_Expense.Member_code = Ma.Member_code INNER JOIN
								 TRF_header ON replace(REPLACE(TRF_footer.CNNO, 'NSE-F&O', ''),'NSE-F&OBF', '') = TRF_header.ContractNote
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) 
					and cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime) >= @FromDate and  cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime)  <= @ToDate
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code
		ORDER BY ISNUMERIC(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)) DESC, Try_Parse(SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6) AS decimal(10, 2)), SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(CNNO) - 6)
		--SELECT        TRF_footer.CNNO, SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(TRF_footer.CNNO) - 5) AS Bill, SUM(CAST(TRF_footer.Amount AS float)) AS Amount, 
		--						 BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name AS 'ExpenseName', Ma.AC_Code AS 'Taxcode'
		--FROM            TRF_footer INNER JOIN
		--						 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name AND BrokerBill_Format_Expense.Member_code = @MemberCode AND
		--						  BrokerBill_Format_Expense.year_code = @YearCode INNER JOIN
		--						 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND Ma.Member_Code = @MemberCode AND Ma.Year_Code = @YearCode
		--WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber) and (right(TRF_footer.CNNO,5) = 'NSE-F&O') and 
		--GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, TRF_footer.CNNO, Ma.AC_Name, Ma.AC_Code
		--order by TRF_footer.CNNO
	END
	Else if (@FormatNumber = '475')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		replace(TRF_body.Qnty,'-','') As'Qty', case when TRF_body.GrossRate is null then TRF_body.ClosingRate else TRF_body.GrossRate end As 'GrossRate', isnull(TRF_body.BrokRate,'0') As'Brokerage', 
        TRF_body.GrossRate As'NetRate', replace(TRF_body.NetTotal,'-','') As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

		Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
		SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
		Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
		 from Trf_footer
		 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
		  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
		  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
		  Where BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber and CNNO like '%NSEFO'
	       Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '476') --Progressive Shares & Broker Equity
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%BSEE%' or CNNO like '%NSEEQ%'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '481') --Cochin NSE
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '477') --JM Finance Equity BSE NSE 2018
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%BSECM' or CNNO like '%NSECM'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '482')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT  ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '483')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT  ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '492')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', case when BS = 'S'  then cast(GrossRate as numeric(12,2)) - cast(BrokRate as numeric(12,2)) else cast(GrossRate as numeric(12,2)) + cast(BrokRate as numeric(12,2)) end   AS 'NetRate', 
		case when BS = 'S' then cast(isnull(NetTotal,'0') as numeric(12,4)) - (cast(Qnty as numeric(12,4)) * cast(BrokRate as numeric(12,4))) else cast(isnull(NetTotal,'0') as numeric(12,4)) + (cast(Qnty as numeric(12,4)) * cast(BrokRate as numeric(12,4))) end AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT  ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '494')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT left(ContractNote,charindex('-',ContractNote)-1) as ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '496' or @FormatNumber = '499')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT  ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '502')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		replace(TRF_body.Qnty,'-','') As'Qty', case when TRF_body.GrossRate is null then TRF_body.ClosingRate else TRF_body.GrossRate end As 'GrossRate', isnull(TRF_body.BrokRate,'0') As'Brokerage', 
        TRF_body.GrossRate As'NetRate', replace(TRF_body.NetTotal,'-','') As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFNO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

		Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
		SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
		Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
		 from Trf_footer
		 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
		  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
		  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
		  Where BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber and CNNO like '%NSEFNO'
	       Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '504')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		replace(TRF_body.Qnty,'-','') As'Qty', case when TRF_body.GrossRate is null then TRF_body.ClosingRate else TRF_body.GrossRate end As 'GrossRate', isnull(TRF_body.BrokRate,'0') As'Brokerage', 
        TRF_body.GrossRate As'NetRate', replace(TRF_body.NetTotal,'-','') As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

		Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
		SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
		Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
		 from Trf_footer
		 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
		  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
		  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
		  Where BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber and CNNO like '%NSEFO'
	       Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '508')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT  ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '428')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', case when TRF_body.BS is null then case when cast(TRF_body.Qnty as int)>0 then 'B' else 'S' end else TRF_body.BS end As'BuySale', 
		replace(TRF_body.Qnty,'-','') As'Qty', isnull(TRF_body.GrossRate,0) As'GrossRate', isnull(TRF_body.BrokRate,0) As'Brokerage', 
        TRF_body.NetRate As'NetRate', TRF_body.NetTotal As'NetAmount', TRF_body.OrderNo As'BFCF', isnull(TRF_body.ClosingRate,0) As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate
		order by TH.ContractNote

		SELECT        TRF_footer.CNNO, SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(TRF_footer.CNNO) - 5) AS Bill, SUM(CAST(TRF_footer.Amount AS float)) AS Amount, 
								 BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name AS 'ExpenseName', Ma.AC_Code AS 'Taxcode'
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name AND BrokerBill_Format_Expense.Member_code = @MemberCode AND
								  BrokerBill_Format_Expense.year_code = @YearCode INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND Ma.Member_Code = @MemberCode AND Ma.Year_Code = @YearCode
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber) and (right(TRF_footer.CNNO,5) = 'NSEFO')
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, TRF_footer.CNNO, Ma.AC_Name, Ma.AC_Code
		order by TRF_footer.CNNO

		Select * from trf_Header Where convert(datetime, TradeDate, 103) >= @FromDate and convert(datetime, TradeDate, 103)  <= @ToDate 

	END
	Else if (@FormatNumber = '513')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body

		SELECT  ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '515')
	BEGIN
		SELECT left(TH.ContractNote,charindex('-',TH.ContractNote)-1) As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', TRF_body.GrossRate As'GrossRate', TRF_body.BrokRate As'Brokerage', 
        case when TRF_body.NetRate = '0.00' then TRF_body.GrossRate else TRF_body.NetRate end As 'NetRate', TRF_body.NetTotal As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		left(TH.ContractNote, charindex('-', TH.ContractNote) - 1) = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = '515' and CNNO like '%NSEFO'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '517')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate,BrokRate AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		where CNNO  like '%BSECM'
		SELECT       left(ContractNote,charindex('-',ContractNote)-1) as ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '518')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate,BrokRate AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		where CNNO  like '%NSECM'
		SELECT       left(ContractNote,charindex('-',ContractNote)-1) as ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '519')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate,BrokRate AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		where CNNO  not like '%NSEFO'
		SELECT       ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '520')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', case when TRF_body.GrossRate is null then TRF_body.ClosingRate else TRF_body.GrossRate end As 'GrossRate', TRF_body.BrokRate As'Brokerage', 
        TRF_body.NetRate As'NetRate', replace(TRF_body.NetTotal,'-','') As'NetAmount', TRF_body.BFCF As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate
		
		Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
		SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
		Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			from Trf_footer
			INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			Where BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber and CNNO like '%NSEFO'
	        Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '521')
	BEGIN
		SELECT        distinct left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1)  AS ContractNote, TRF_header.TradeDate, TRF_header.UccCode, TRF_header.SNo, TRF_header.SType, TRF_header.Exchange, TRF_header.Membercode, TRF_header.TradeMember, TRF_header.BSE_SNo
		FROM            TRF_header 
		Where convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103)  <= @ToDate
		order by ContractNote

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate, T1.BrokRate as BrokRate, T1.BrokRate as BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(T1.CNNO, 'BSE', 'BSECM'),'NSE-N','NSECM'),'NSE-D','NSECM'),'-O',''),'BSE-D','BSECM'),'BSECM-D','BSECM') AS 'BillNo',REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(T1.CNNO, 'BSE', ''),'NSE-N',''),'NSE-D',''),'-O',''),'-D',''),'BSE-D','') as cnno, TradeDate,SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON left(T2.ContractNote,charindex('-',T2.ContractNote)-1) = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(T1.CNNO, 'BSE', ''),'NSE-N',''),'NSE-D',''),'-O',''),'-D', ''),'BSE-D','')
		Where convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103)  <= @ToDate
		--where convert(datetime,convert(varchar,T2.TradeDate,103)) >=  '08/01/2018' and  convert(datetime,convert(varchar,T2.TradeDate,103)) <= '08/03/2018' 
		--GROUP BY  T1.OrderNo, T1.S_Desc, T1.BS, T1.Qnty, T1.GrossRate, T1.BrokRate, T1.NetRate, T1.NetTotal, T1.CNNO, T1.cnno, T2.TradeDate, T2.SNo
		Order by T2.ContractNote
	   
	    SELECT        REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TRF_footer.CNNO, 'BSE', 'BSECM'),'NSE-N','NSECM'),'NSE-D','NSECM'),'BSE-O','BSECM'),'BSE-D','BSECM'),'BSECM-D','BSECM') as CNNO, REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TRF_footer.CNNO, 'BSE-O', ''),'NSE-N',''),'NSE-D',''),'BSE',''),'BSE-D',''),'-D','') AS Bill,sum(TRF_footer.Amount) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
								 TRF_header.TradeDate, Ma.Year_Code,ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code AND BrokerBill_Format_Expense.Member_code = Ma.Member_code INNER JOIN
								 TRF_header ON REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TRF_footer.CNNO, 'BSE-O', ''),'NSE-N',''),'NSE-D',''),'BSE',''),'BSE-D',''),'-D',''),'BSECM-D','') = left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1)
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code
		ORDER BY TRF_footer.CNNO
	END
	Else if (@FormatNumber = '438')
	BEGIN
		SELECT        distinct TRF_header.ContractNote  AS ContractNote, TRF_header.TradeDate, TRF_header.UccCode, TRF_header.SNo, TRF_header.SType, TRF_header.Exchange, TRF_header.Membercode, TRF_header.TradeMember, TRF_header.BSE_SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103)) AS NameId 
		FROM            TRF_header 
		Where convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103)  <= @ToDate
		order by ContractNote
		

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate,abs(cast(T1.GrossRate as numeric(12,4)) - cast(T1.NetRate as numeric(12,4)))   as BrokRate, abs(cast(T1.GrossRate as numeric(12,4)) - cast(T1.NetRate as numeric(12,4)))   as BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',T1.CNNO AS 'BillNo',REPLACE(REPLACE(T1.CNNO, 'BSECM', ''),'NSECM','') as cnno, TradeDate,SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON T2.ContractNote =  replace(replace(T1.CNNO,'BSECM',''),'NSECM','')
		Where convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103)  <= @ToDate
		
		Order by NameId
	   
	    SELECT         TRF_header.ContractNote  as CNNO, TRF_header.ContractNote AS Bill,sum(TRF_footer.Amount) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
								 TRF_header.TradeDate, Ma.Year_Code,ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name  AND BrokerBill_Format_Expense.Member_code=@MemberCode AND BrokerBill_Format_Expense.year_code=@YearCode
								 INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND  Ma.Member_Code=@MemberCode AND Ma.Year_Code= @YearCode
								 INNER JOIN
								 TRF_header ON replace(replace(TRF_footer.CNNO,'BSECM',''),'NSECM','') = TRF_header.ContractNote
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		GROUP BY   TRF_header.ContractNote, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code
		ORDER BY NameId
	END
	Else if (@FormatNumber = '522')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%NSECM'

		SELECT ContractNote,TradeDate, BSE_SNo, SNo FROM TRF_header	
	END
	Else if (@FormatNumber = '322')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%NSE'

		SELECT        TOP 1 ContractNote, TradeDate,(Select top 1 BSE_SNo from TRF_header order by BSE_SNo DESC) as  BSE_SNo,(Select top 1 SNo from TRF_header order by SNo desc) as SNo FROM TRF_header
	END
	Else if (@FormatNumber = '321')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty, '-', '') AS 'Qty' , GrossRate, isnull(BrokRate,'0')  AS 'BrokarageRate', isnull(NetRate,'0') AS 'NetRate', isnull(NetTotal,'0') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body where CNNO like '%BSE'

		SELECT        top 1 ContractNote, TradeDate,(Select top 1 BSE_SNo from TRF_header order by BSE_SNo asc) as BSE_SNo,(Select top 1 BSE_SNo from TRF_header order by BSE_SNo desc) as  SNo FROM TRF_header
	END
End 




--[Sp_TradeFileData] '04/01/2018', '11/13/2018','D0001','1120182019','426' 
--SELECT * FROM TRF_header
--SELECT * FROM TRF_BODY



GO
/****** Object:  StoredProcedure [dbo].[Sp_TradeFileData1]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Sp_TradeFileData1]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Sp_TradeFileData1] AS' 
END
GO



--[Sp_TradeFileData] '04/01/2018', '11/05/2018','D0001','1120182019','308' 
--[Sp_TradeFileData] '04/01/2018', '10/04/2019','','','313'
--[Sp_TradeFileData] '04/01/2018', '10/04/2018','30001','1120182019','315' 
--[Sp_TradeFileData] '04/01/2018', '10/04/2018','','','336' 
--[Sp_TradeFileData] '04/01/2018', '03/31/2019','','','332'
--[Sp_TradeFileData] '04/01/2018', '03/31/2019','','','348'
--[Sp_TradeFileData] '04/01/2018', '03/31/2019','','','35'


ALTER Procedure [dbo].[Sp_TradeFileData1] 
@FromDate varchar(20),
@ToDate varchar(20),
@MemberCode varchar(20),
@YearCode varchar(20),
@FormatNumber varchar(20)
As
Begin
	if (@FormatNumber = '523')
	BEGIN
		Select * from TRF_body
	END
	Else if (@FormatNumber = '533')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', isnull(BrokRate,'0')  AS 'Brokerage',isnull(GrossRate,'0')  AS 'GrossRate',
		        TRF_body.NetRate As'NetRate', TRF_body.NetTotal As'NetAmount', TRF_body.BFCF As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = '533' and CNNO like '%NSEFO'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '535')
	BEGIN
		--SHREE BAHUBALI STOCK BROKING LIMITED EQUITY COMBINE
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate,BrokRate AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		where CNNO  not like '%NSEFO'
		SELECT       ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '536')
	BEGIN
		--RRS FNO
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', case when TRF_body.GrossRate is null then '0' else  TRF_body.GrossRate end As'GrossRate', case when TRF_body.BrokRate is null then '0' else TRF_body.BrokRate end As'Brokerage', 
        TRF_body.NetRate As'NetRate', TRF_body.NetTotal As'NetAmount', case when TRF_body.BFCF is null then TRF_body.orderno else TRF_body.BFCF end AS 'BFCF', case when TRF_body.ClosingRate is null then '0' else TRF_body.ClosingRate end As'ClosingRate',case when TH.SNo is null then 'BillNo' else TH.SNo end As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

		SELECT        TRF_footer.CNNO, SUBSTRING(TRF_footer.CNNO, 1, DATALENGTH(TRF_footer.CNNO) - 5) AS Bill, cast(SUM(CAST(TRF_footer.Amount AS float)) as nvarchar(50)) AS Amount, 
								 BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name , Ma.AC_Code 
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name AND BrokerBill_Format_Expense.Member_code = @MemberCode AND
								  BrokerBill_Format_Expense.year_code = @YearCode INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND Ma.Member_Code = @MemberCode AND Ma.Year_Code = @YearCode
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber) and (right(TRF_footer.CNNO,5) = 'NSEFO')
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, TRF_footer.CNNO, Ma.AC_Name, Ma.AC_Code
		ORDER BY TRF_footer.CNNO
	END
	Else if (@FormatNumber = '540')
	BEGIN
		--M. J. PATEL SHARE & STOCK BROKERS LTD.
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate,BrokRate AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		where CNNO  not like '%NSEFO'
		SELECT       ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '543')
	BEGIN
		--PHILLIPCAPITAL (INDIA) PVT LTD
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate,BrokRate AS 'BrokarageRate',cast(ABS(cast(isnull(NetTotal,'0') as numeric(12,2)) / cast(isnull(replace(Qnty,'D',''),'0')  as numeric(12,2))) as varchar(50)) AS 'NetRate' , NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		where CNNO  not like '%NSEFO'
		SELECT       ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '549')
	BEGIN
		--YES SECURITIES (INDIA) LIMITED EQUITY
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate,BrokRate AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		where CNNO  not like '%NSEFO'
		SELECT       ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '550')
	BEGIN
		--PHILLIPCAPITAL (INDIA) PVT LTD - FNO
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', TRF_body.GrossRate As'GrossRate', TRF_body.BrokRate As'Brokerage', 
        TRF_body.NetRate As'NetRate', TRF_body.NetTotal As'NetAmount', TRF_body.OrderNo As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		--Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

			Select TRF_footer.CNNO ,SUBSTRING(Trf_footer.CNNO, 1, DATALENGTH(Trf_footer.CNNO) - 5) AS Bill ,
			SUM(cast(TRF_footer.Amount as float)) AS Amount,BrokerBill_Format_Expense.BrokerBill_Format_No,
			Ma.AC_Name As'ExpenseName', Ma.AC_Code as'Taxcode'
			 from Trf_footer
			 INNER JOIN  BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
			  and BrokerBill_Format_Expense.Member_code=@MemberCode and BrokerBill_Format_Expense.year_code=@YearCode
			  INNER JOIN  Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code  and Ma.Member_Code=@MemberCode and Ma.Year_Code=@YearCode
			  Where BrokerBill_Format_Expense.BrokerBill_Format_No = '550' and CNNO like '%NSEFO'
	          Group By TRF_footer.CNNO,BrokerBill_Format_Expense.BrokerBill_Format_No,TRF_footer.CNNO,Ma.AC_Name, Ma.AC_Code
	END
	Else if (@FormatNumber = '551')
	BEGIN

	SELECT *,convert(datetime, TradeDate, 103) FROM TRF_header Where convert(datetime, TradeDate, 103) >= @FromDate and convert(datetime, TradeDate, 103)  <= @ToDate

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate,abs(cast(T1.GrossRate as numeric(12,4)) - cast(T1.NetRate as numeric(12,4)))   as BrokRate,
		 abs(cast(T1.GrossRate as numeric(12,4)) - cast(T1.NetRate as numeric(12,4)))   as BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',
		 T1.CNNO AS 'BillNo',T1.CNNO as cnno, 
		 TradeDate,SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON T2.ContractNote = T1.CNNO
		Where convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103) >= @FromDate and convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103)  <= @ToDate
	
		Order by NameId

		 SELECT       TRF_footer.CNNO  as CNNO, TRF_footer.CNNO AS Bill,sum(TRF_footer.Amount) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, 
								 TRF_header.TradeDate, Ma.Year_Code,ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name 
								 INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code AND BrokerBill_Format_Expense.Member_code = Ma.Member_code 
								 INNER JOIN
								 TRF_header ON TRF_footer.CNNO = TRF_header.ContractNote
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code
		ORDER BY NameId

	END
	Else if (@FormatNumber = '552')
	BEGIN
		--PKC STOCK BROKING PVT LTD - EQUITY
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate,BrokRate AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		where CNNO  not like '%NSEFO'
		SELECT       ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '553')
	BEGIN
		--PKC STOCK BROKING PVT LTD - EQUITY PRE GST
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate,BrokRate AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		where CNNO  not like '%NSEFO'
		SELECT       ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '554' )
	BEGIN
		--PKC STOCK BROKING PVT LTD - EQUITY POST GST
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', Qnty AS 'Qty', GrossRate,BrokRate AS 'BrokarageRate', NetRate, NetTotal AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		where CNNO  not like '%NSEFO'
		SELECT       ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END
	Else if (@FormatNumber = '555') 
	BEGIN
		--INDIANIVESH EQUITY TRADEFILE
		SELECT        distinct left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1)  AS ContractNote, TRF_header.TradeDate, 
		TRF_header.UccCode, TRF_header.SNo, TRF_header.SType, TRF_header.Exchange, TRF_header.Membercode, TRF_header.TradeMember, TRF_header.BSE_SNo
		FROM            TRF_header 
		Where convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 
		103) >= @FromDate and convert(datetime, cast(left(right(TRF_header.TradeDate,7),2) + '/' + left(TRF_header.TradeDate,2) + '/' + right(TRF_header.TradeDate,4) as datetime), 103)  <= @ToDate
		order by ContractNote

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate, T1.BrokRate as BrokRate, T1.BrokRate as BrokRate, T1.NetRate, NetRate, 
		ABS(cast(T1.NetTotal as float)) as 'NetTotal',REPLACE(REPLACE(T1.CNNO, 'BSE', 'BSECM'),'NSE','NSECM') AS 'BillNo',
		REPLACE(REPLACE(T1.CNNO, 'BSE', ''),'NSE','') as cnno, 
		TradeDate,SNo, ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON left(T2.ContractNote,charindex('-',T2.ContractNote)-1) = REPLACE(REPLACE(T1.CNNO, 'BSE', ''),'NSE','')
		Where convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103) >= @FromDate
		and convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103)  <= @ToDate
		--where convert(datetime,convert(varchar,T2.TradeDate,103)) >=  '08/01/2018' and  convert(datetime,convert(varchar,T2.TradeDate,103)) <= '08/03/2018' 
		--GROUP BY  T1.OrderNo, T1.S_Desc, T1.BS, T1.Qnty, T1.GrossRate, T1.BrokRate, T1.NetRate, T1.NetTotal, T1.CNNO, T1.cnno, T2.TradeDate, T2.SNo
		Order by T2.ContractNote
	   

		--Select REPLACE(REPLACE(TRF_footer.CNNO, 'BSE', ''),'NSE','')  from TRF_footer
		--Select left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1) from TRF_header

	    SELECT        REPLACE(REPLACE(TRF_footer.CNNO, 'BSE', 'BSECM'),'NSE','NSECM') as CNNO, REPLACE(REPLACE(TRF_footer.CNNO, 'BSE', ''),'NSE','') AS Bill,
		sum(TRF_footer.Amount) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code,
		TRF_header.TradeDate, Ma.Year_Code,ROW_NUMBER() OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId, Ma.Member_Code 
		FROM          TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code 
								 AND BrokerBill_Format_Expense.Member_code = Ma.Member_code INNER JOIN
								 TRF_header ON REPLACE(REPLACE(TRF_footer.CNNO, 'BSE', ''),'NSE','') = left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1)
		WHERE         (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) 
		--and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code, Ma.Member_Code 
		ORDER BY TRF_footer.CNNO
	END
	Else if (@FormatNumber = '559')
	BEGIN
		--INDIANIVESH FNO TRADEFILE

		SELECT   distinct left(TH.ContractNote,charindex('-',TH.ContractNote)-1)  AS 'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', case when TRF_body.GrossRate is null then '0' else  TRF_body.GrossRate end As'GrossRate', case when TRF_body.BrokRate is null then '0' else TRF_body.BrokRate end As'Brokerage', 
        TRF_body.NetRate As'NetRate', TRF_body.NetTotal As'NetAmount', case when TRF_body.orderno = 'B/F' then 'B/F' else case when TRF_body.orderno = 'C/F' then 'C/F' else '' end end AS 'BFCF', 
		case when TRF_body.ClosingRate is null then '0' else TRF_body.ClosingRate end As'ClosingRate',case when TH.SNo is null then 'BillNo' else TH.SNo end As'SettlementNo',TRF_body.TardeNo AS 'TradeNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		left(TH.ContractNote,charindex('-',TH.ContractNote)-1) = REPLACE(TRF_body.CNNO, 'NSEF', '')
		Where convert(datetime, TH.TradeDate, 103) >= @FromDate and convert(datetime, TH.TradeDate, 103)  <= @ToDate

		SELECT         REPLACE(TRF_footer.CNNO, 'NSEF', '') AS Bill,
		 cast(SUM(CAST(TRF_footer.Amount AS float)) as nvarchar(50)) AS Amount, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code,
		TRF_header.TradeDate, Ma.Year_Code,ROW_NUMBER() 
		OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId, 
		Ma.Member_Code 
		FROM          TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code AND BrokerBill_Format_Expense.year_code = Ma.Year_Code 
								 AND BrokerBill_Format_Expense.Member_code = Ma.Member_code INNER JOIN
								 TRF_header ON REPLACE(TRF_footer.CNNO, 'NSEF', '') = left(TRF_header.ContractNote,charindex('-',TRF_header.ContractNote)-1)
		WHERE         (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) AND (Ma.Year_Code = @YearCode) 
		and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code, Ma.Member_Code 
		ORDER BY TRF_footer.CNNO

	END
	Else if (@FormatNumber = '606')
	BEGIN

		--select * from trf_body
		--select * from BrokerBill_Format_Expense


		SELECT *,convert(datetime, TradeDate, 103) FROM TRF_header Where convert(datetime, TradeDate, 103) >= @FromDate and convert(datetime, TradeDate, 103)  <= @ToDate

		SELECT T1.OrderNo, T1.S_Desc,T1.BS,T1.Qnty, T1.GrossRate,abs(cast(T1.GrossRate as numeric(12,4)) - cast(T1.NetRate as numeric(12,4))) as BrokRate, 
		abs(cast(T1.GrossRate as numeric(12,4)) - cast(T1.NetRate as numeric(12,4)))   as BrokRate, T1.NetRate, NetRate, ABS(cast(T1.NetTotal as float)) as 'NetTotal',
		T1.CNNO AS 'BillNo',REPLACE(REPLACE(T1.CNNO, 'BSECM', ''),'NSECM','') as cnno, TradeDate,SNo, ROW_NUMBER() OVER(ORDER BY  
		convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM TRF_body T1 
		LEFT JOIN TRF_header T2 ON T2.ContractNote =  replace(replace(T1.CNNO,'BSECM',''),'NSECM','')
		Where convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103) >= @FromDate 
		and convert(datetime, cast(left(right(T2.TradeDate,7),2) + '/' + left(T2.TradeDate,2) + '/' + right(T2.TradeDate,4) as datetime), 103)  <= @ToDate
		--where convert(datetime,convert(varchar,T2.TradeDate,103)) >=  '08/01/2018' and  convert(datetime,convert(varchar,T2.TradeDate,103)) <= '08/03/2018' 
		GROUP BY  T1.OrderNo, T1.S_Desc, T1.BS, T1.Qnty, T1.GrossRate, T1.BrokRate, T1.NetRate, T1.NetTotal, T1.CNNO, T1.cnno, T2.TradeDate, T2.SNo
		Order by NameId

		 SELECT       TRF_footer.CNNO  as CNNO, REPLACE(REPLACE(TRF_footer.CNNO, 'BSECM', ''),'NSECM','') AS Bill,sum(TRF_footer.Amount) AS Amount, 
		 BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code,ROW_NUMBER() 
		 OVER(ORDER BY  convert(datetime, cast(left(right(TradeDate,7),2) + '/' + left(TradeDate,2) + '/' + right(TradeDate,4) as datetime), 103)) AS NameId 
		FROM            TRF_footer INNER JOIN
								 BrokerBill_Format_Expense ON TRF_footer.TaxText = BrokerBill_Format_Expense.Tax_Name INNER JOIN
								 Mst_Account AS Ma ON Ma.AC_Code = BrokerBill_Format_Expense.Tax_code 
								 AND BrokerBill_Format_Expense.year_code = Ma.Year_Code AND BrokerBill_Format_Expense.Member_code = Ma.Member_code INNER JOIN
								 TRF_header ON replace(replace(TRF_footer.CNNO,'BSECM',''),'NSECM','') = TRF_header.ContractNote
		WHERE        (BrokerBill_Format_Expense.BrokerBill_Format_No = @FormatNumber)  AND (Ma.Member_Code = @MemberCode) 
		AND (Ma.Year_Code = @YearCode) and (CONVERT(datetime, TRF_header.TradeDate, 103) >= @FromDate) 
		AND (CONVERT(datetime, TRF_header.TradeDate, 103) <=@ToDate)
		GROUP BY TRF_footer.CNNO, BrokerBill_Format_Expense.BrokerBill_Format_No, Ma.AC_Name, Ma.AC_Code, TRF_header.TradeDate, Ma.Year_Code
		ORDER BY NameId
	END
	Else if (@FormatNumber = '608')
	BEGIN
		SELECT        OrderNo, S_Desc AS 'ScriptName', BS AS 'BuySale', REPLACE(Qnty,'-','') AS 'Qty', GrossRate,BrokRate AS 'BrokarageRate', NetRate, REPLACE(NetTotal,'-','') AS 'NetAmount', ClosingRate, StrikePrice, BFCF, CNNO,TardeNo as TradeNo
		FROM            TRF_body
		where CNNO  not like '%NSEFO'
		SELECT       ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header
	END

	Else if (@FormatNumber = '609')
	BEGIN
		SELECT TH.ContractNote As'BillNo',  TH.TradeDate As'TradeDate', TRF_body.S_Desc As'ScriptName', TRF_body.BS As'BuySale', 
		TRF_body.Qnty As'Qty', isnull(BrokRate,'0')  AS 'Brokerage',isnull(GrossRate,'0')  AS 'GrossRate',
		        TRF_body.NetRate As'NetRate', TRF_body.NetTotal As'NetAmount', TRF_body.BFCF As'BFCF', TRF_body.ClosingRate As'ClosingRate',TH.SNo As'SettlementNo'
        FROM  TRF_body 
        INNER JOIN TRF_header AS TH ON 
		TH.ContractNote = REPLACE(TRF_body.CNNO, 'NSEFO', '')
		SELECT       ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header		
	END

	Else if (@FormatNumber = '612')
	BEGIN		
		SELECT TB.S_Desc AS 'ScriptName', TB.BS AS'BuySale',TB.Qnty AS'Qty',TB.GrossRate AS'GrossRate',TB.BrokRate As'Brokerage',TB.NetRate AS'NetRate',TB.CNNO from TRF_BODY TB
		WHERE TB.CNNO  LIKE('%BSE%')
		GROUP BY TB.OrderNo,TB.TardeNo,TB.S_Desc, TB.BS,TB.Qnty,TB.GrossRate,TB.BrokRate,TB.NetRate,TB.CNNO,TB.CNNO 
		ORDER BY TB.OrderNo,TB.TardeNo

		SELECT       ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header		
	END
	Else if (@FormatNumber = '613')
	BEGIN		
		SELECT TB.S_Desc AS 'ScriptName', TB.BS AS'BuySale',TB.Qnty AS'Qty',TB.GrossRate AS'GrossRate',TB.BrokRate As'Brokerage',TB.NetRate AS'NetRate',TB.CNNO from TRF_BODY TB
		WHERE TB.CNNO  LIKE('%NSE%')
		GROUP BY TB.OrderNo,TB.TardeNo,TB.S_Desc, TB.BS,TB.Qnty,TB.GrossRate,TB.BrokRate,TB.NetRate,TB.CNNO,TB.CNNO 
		ORDER BY TB.OrderNo,TB.TardeNo

		SELECT  ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header		
	END
	ELSE IF(@FormatNumber='620')
	BEGIN

	SELECT ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header	

	Select S_Desc As'ScriptName',BS As'BuySale',Qnty As 'Qty',GrossRate,BrokRate As'Brokerage',NetRate AS'NetRate' from TRF_body
    WHERE CNNO Like '%NSE-EQ%' 
    ORDER By OrderNo

	Select  MA.AC_Name As'Expense Name',MA.AC_Code As'Ac Code', Sum(TF.Amount) As'Amount' from TRF_footer TF
    INNER JOIN BrokerBill_format_Expense BBF ON BBF.Tax_Name=TF.TaxText AND BBF.Member_code=@MemberCode AND BBF.year_code=@YearCode
    INNER JOIN Mst_Account MA ON MA.AC_Code=BBF.Tax_code AND MA.Member_Code=@MemberCode and MA.Year_code=@YearCode
    Where TF.CNNO LIKE '%NSE-EQ%'
    AND BBF.BrokerBill_Format_No=@FormatNumber
	Group By MA.AC_Name,MA.AC_Code
	END
ELSE IF(@FormatNumber='623')
	BEGIN
	SELECT ContractNote, TradeDate, BSE_SNo, SNo FROM TRF_header	

	Select S_Desc As'ScriptName',BS As'BuySale',Qnty As 'Qty',GrossRate,BrokRate As'Brokerage',NetRate AS'NetRate',ClosingRate As'ClosingRate',BFCF from TRF_body
    WHERE CNNO Like '%NSEFO%' 
    ORDER By OrderNo,TardeNo

	Select  MA.AC_Name As'Expense Name',MA.AC_Code As'Ac Code', Sum(TF.Amount) As'Amount' from TRF_footer TF
    INNER JOIN BrokerBill_format_Expense BBF ON BBF.Tax_Name=TF.TaxText AND BBF.Member_code=@MemberCode AND BBF.year_code=@YearCode
    INNER JOIN Mst_Account MA ON MA.AC_Code=BBF.Tax_code AND MA.Member_Code=@MemberCode and MA.Year_code=@YearCode
    Where TF.CNNO LIKE '%NSEFO%'
    AND BBF.BrokerBill_Format_No=@FormatNumber
	Group By MA.AC_Name,MA.AC_Code
	END

End 




--[Sp_TradeFileData] '04/01/2018', '11/13/2018','D0001','1120182019','426' 
--SELECT * FROM TRF_header
--SELECT * FROM TRF_BODY



GO
/****** Object:  StoredProcedure [dbo].[spAddProject]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAddProject]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[spAddProject] AS' 
END
GO
ALTER PROCEDURE [dbo].[spAddProject]  
   @ProjectID INT,  
   @MemberID INT,  
   @Name VARCHAR(10)  
AS  
BEGIN 
SET NOCOUNT ON; 
   BEGIN TRY  
      BEGIN TRANSACTION;  
         -- Insert record into Project table  
         INSERT INTO tblProject(ProjectID, Name) VALUES(1, 'TestProject');  

         -- Insert record into ProjectMember table  
         INSERT INTO tblProjectMember(MemberID, ProjectID) VALUES(2, 1);  

         COMMIT TRANSACTION;  
   END TRY  
   BEGIN CATCH  
      IF @@TRANCOUNT > 0  
         ROLLBACK TRANSACTION; 
 
      DECLARE @ErrorNumber INT = ERROR_NUMBER();  
      DECLARE @ErrorLine INT = ERROR_LINE();  
      DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
  
      PRINT 'Actual error number: ' + CAST(@ErrorNumber AS VARCHAR(10));  
      PRINT 'Actual line number: ' + CAST(@ErrorLine AS VARCHAR(10));  

      --RAISERROR(@ErrorMessage);  
   END CATCH 
    
END;  












GO
/****** Object:  StoredProcedure [dbo].[SplitAutoUploadEntry ]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SplitAutoUploadEntry ]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[SplitAutoUploadEntry ] AS' 
END
GO



-- Execute Merger_Openning_Report 'E0152',1100014,'04/01/2018','03/31/2019','R0001','1120182019',0

-- Select * from BrokerBill_Trans Where Script_Code = 'S0009' 
ALTER PROCEDURE [dbo].[SplitAutoUploadEntry ] (@ScriptCode VARCHAR(Max), 
                                                @AcType     VARCHAR(500), 
                                                @FromDate   DATETIME, 
                                                @ToDate     DATETIME, 
                                                @MemCode    VARCHAR(Max), 
                                                @YearCode   VARCHAR(20),
												@Istransfer Varchar(10)) 
AS 

SET NOCOUNT ON;
CREATE TABLE #mainoutputtable_1_Final_merger
        ( 
           id INT,
		   Trans_no varchar(20),
		   Sr_no int,
		   flag_HT VARCHAR(200),
		   opening_bill_no varchar(500) ,
		   dupid INT,
		   prioritys INT,
		   Script_Code varchar(10),
		   AcountType varchar(20),
		   BrokerCode varchar(10),
		   Consultant_Code varchar(10),
		   Script_Name varchar(max),
		   Holding_Type varchar(max),
           opening_date VARCHAR(50),
		   opening_qty  Int ,
		   opening_rate  FLOAT DEFAULT 0,
		   opening_amount FLOAT DEFAULT 0, 
           purchase_date VARCHAR(50),
		   purchase_bill_no VARCHAR(100),
		   purchase_qty int ,
		   purchase_rate FLOAT DEFAULT 0,
		   purchase_amount FLOAT DEFAULT 0 , 
           sold_date VARCHAR(50),
		   sold_bill_no VARCHAR(100),
		   sold_qty Int ,
		   sold_rate FLOAT DEFAULT 0,
		   sold_amount FLOAT DEFAULT 0, 
           gain_loss FLOAT DEFAULT 0,
		   gain FLOAT DEFAULT 0,
		   loss FLOAT DEFAULT 0,
		   closing_qty Int, 
           closing_rate FLOAT DEFAULT 0,
		   closing_value FLOAT DEFAULT 0,
		   short_term FLOAT DEFAULT 0,
		   long_term FLOAT DEFAULT 0, 
           speculation FLOAT DEFAULT 0, 
		   gain_speculation FLOAT DEFAULT 0,
		   loss_speculation FLOAT DEFAULT 0,
		   Consultant_name VARCHAR(500), 
           nse_rate FLOAT DEFAULT 0,
		   bse_rate FLOAT DEFAULT 0,
		   Other_amt FLOAT DEFAULT 0,
		   sort   VARCHAR(5),
		   type VARCHAR(50)
        ) 

		INSERT INTO #mainoutputtable_1_Final_merger
		EXECUTE proc_Stockholdingposition_Equity 0,0,@AcType,@MemCode,@YearCode,@FromDate,@ToDate,@ScriptCode,'','','', '0' ,'0','details','0'

		--proc_Stockholdingposition_Equity 0,0,'1100014','30001','1120182019','2018-04-01 12:00:00:00','2019-03-31 03:50:37:50','','','','', '0' ,'0','details'
	--	EXECUTE proc_Stockholdingposition_Equity 0,0,'1100014','R0001','1120182019','2018-04-01 12:00:00:00','2019-03-31 03:50:37:50','E0152','','','', '0' ,'0','details',0
		--Select * from #mainoutputtable_1_Final_merger

		SELECT	 qty ,rate ,transdt ,consultantcode , consultantname ,demateCode , transno ,srno,dematname,ScriptName,ScriptCode 
	    from 
		(SELECT	closing_qty		as 'qty',
				closing_rate	as 'rate',
				CASE 
					WHEN opening_date IS NOT NULL 
					THEN opening_date 
					ELSE purchase_date 
				END as 'transdt',
				temp.Consultant_Code as 'consultantcode', 
				cons.Consultant_Name as 'consultantname',
				BBD.dp_code          as 'demateCode',
				temp.Trans_no        as 'transno',
				temp.Sr_no           as 'srno',
				MD.DP_Name          as  'dematname',
				temp.Script_Name    as  'ScriptName',
				temp.Script_Code    as  'ScriptCode'
		FROM    #mainoutputtable_1_Final_merger temp
		LEFT JOIN Mst_Consultant cons 
			ON temp.Consultant_Code = cons.Consultant_Code
        Inner Join BrokerBill_DmatInfo BBD 
		    ON temp.Trans_no=BBD.Trans_No and temp.Script_Code=BBD.Script_Code  and BBD.Member_code=@MemCode and BBD.YearCode=@YearCode --and temp.Sr_no = BBD.Sr_No 
        Inner Join Mst_Demat MD
		    ON MD.DP_Code=BBD.dp_code and MD.Member_code=@MemCode and MD.Year_Code=@YearCode
		   
		WHERE  closing_qty > 0
		  
		Group By closing_qty,closing_rate,opening_date,purchase_date,MD.DP_Name,
		temp.Consultant_Code,cons.Consultant_Name,BBD.dp_code,temp.Trans_no,temp.Sr_no,temp.Script_Code,temp.Script_Name ) as a
		WHERE a.transdt = ( SELECT CASE WHEN @Istransfer = 1 THEN (SELECT a.transdt WHERE a.transdt <= @ToDate) ELSE a.transdt  END)
		  AND a.transdt = ( SELECT CASE WHEN @Istransfer = 1 THEN (SELECT a.transdt WHERE a.transdt >= @FromDate) ELSE a.transdt  END)
		 
		--ORDER  BY transdt, transno, srno,ScriptCode
		 ORDER BY ScriptCode, transdt, transno, srno




















GO
/****** Object:  StoredProcedure [dbo].[StockInTradePurchaseAndSaleAccount_Amount]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[StockInTradePurchaseAndSaleAccount_Amount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[StockInTradePurchaseAndSaleAccount_Amount] AS' 
END
GO

--exec Auto_Pnl_Entry '1100001325','03/31/2018','Y0001','1120172018','1100020','1100019',18254021.59
ALTER Procedure [dbo].[StockInTradePurchaseAndSaleAccount_Amount]
(
 @Transaction_No bigint,
 @Trans_Dt  DateTime,
 @Member_Code varchar(Max),
 @Year_Code varchar(20),
 @DRCode varchar(Max),
 @CRCode varchar(Max),
 @Amount  float

)

AS 
BEGIN
SET NOCOUNT ON;
	DELETE From AC_Trans Where Vouch_No='P&L' and Member_Code=@Member_Code and Year_Code=@Year_Code
 
    -- INSERT FOR PURCHASE ENTRY
    Insert INTO AC_Trans 

			(Trans_No,Sr_No,Trans_Dt,Member_Code,Year_Code,Vouch_No,Dr_Code,Cr_Code,Book_Type1,Narr1,Internal,Amount,InvestmentType,PayAgtBill,frmpg,EntryType)
	Values 
			(@Transaction_No,'1',@Trans_Dt,@Member_Code,@Year_Code,'P&L','1100034','1100001','JV','PURCHASE ACCOUNT','N',@Amount,'0','0','JV',0)

    -- INSERT FOR SALE ENTRY

	 Insert INTO AC_Trans 

			(Trans_No,Sr_No,Trans_Dt,Member_Code,Year_Code,Vouch_No,Dr_Code,Cr_Code,Book_Type1,Narr1,Internal,Amount,InvestmentType,PayAgtBill,frmpg,EntryType)
	Values 
			(@Transaction_No,'1',@Trans_Dt,@Member_Code,@Year_Code,'P&L','1100001','1100035','JV','SALE ACCOUNT','N',@Amount,'0','0','JV',0)


END























GO
/****** Object:  StoredProcedure [dbo].[t_transferstock]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[t_transferstock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[t_transferstock] AS' 
END
GO

-- Execute [dbo].[t_transferstock] 'A0001','1120172018','04/01/2017','03/31/2018'
ALTER PROCEDURE [dbo].[t_transferstock] (@memcode varchar(Max),
@yearcode varchar(100),
@Fromdate varchar(30),
@Todate varchar(30))

AS
BEGIN
SET NOCOUNT ON;
 /* Procedure starts here */
  CREATE TABLE #tmptable3 (
    srno int,
    consultant_name varchar(500),
	Script_Code varchar(100),
    Script_Name varchar(100),
    Holding_Type varchar(200),
    Opening_Date varchar(50),
    Opening_Qty varchar(100),
    Opening_Rate varchar(100),
    Opening_Amount varchar(100),
    Purchase_Date varchar(50),
    Purchase_Bill_No varchar(100),
    Purchase_Qty varchar(100),
    Purchase_Rate varchar(100),
    Purchase_Amount varchar(100),
    Sold_Date varchar(50),
    Sold_Bill_No varchar(100),
    Sold_Qty varchar(100),
    Sold_Rate varchar(100),
    Sold_Amount varchar(100),
    Gain_Loss varchar(100) DEFAULT ' ',
    short_term varchar(100) DEFAULT ' ',
    long_term varchar(100) DEFAULT ' ',
    speculation varchar(100) DEFAULT ' ',
    loss_speculation varchar(100) DEFAULT ' ',
    gain_speculation varchar(100) DEFAULT ' ',
    closing_qty varchar(100) DEFAULT ' ',
    closing_rate varchar(100) DEFAULT ' ',
    closing_value varchar(100) DEFAULT ' ',
    closing_date varchar(100) DEFAULT ' ',
    flag int DEFAULT 0,
	consultant_code varchar(500)

  )

  CREATE TABLE #tmptable4 (
    srno int,
    Script_Code varchar(100),
    Script_Name varchar(100),
    closing_qty varchar(100) DEFAULT ' ',
    flag int DEFAULT 0,
	Consultant_Code varchar(100)

  )

  CREATE TABLE #tmptable5 (
    Script_Name varchar(100),
    Opening_Qty varchar(100),
    Opening_Rate varchar(100),
    Opening_Amount varchar(100),
    Purchase_Qty varchar(100),
    Purchase_Rate varchar(100),
    Purchase_Amount varchar(100),
    Sold_Qty varchar(100),
    Sold_Rate varchar(100),
    Sold_Amount varchar(100),
    Gain_Loss varchar(100) DEFAULT ' ',
    short_term varchar(100) DEFAULT ' ',
    long_term varchar(100) DEFAULT ' ',
    speculation varchar(100) DEFAULT '0',
    loss_speculation varchar(100) DEFAULT '0',
    gain_speculation varchar(100) DEFAULT '0',
    closing_qty varchar(100) DEFAULT ' ',
    closing_rate varchar(100) DEFAULT ' ',
    closing_value varchar(100) DEFAULT ' ',
    closing_date varchar(100) DEFAULT ' ',
    flag int DEFAULT 0,
	Consultant_Code varchar(100)

  )

  DECLARE @scriptcd varchar(100),
          @billno varchar(100),
          @scriptname varchar(100),
          @openingdt varchar(100),
          @openingqty int,
          @openingrate float,
          @openingamount float,
          @purchasedt varchar(100),
          @purchaseBillno varchar(100),
          @purchaseqty int,
          @purchaserate float,
          @purchaseamount float,
          @solddt varchar(100),
          @soldBillno varchar(100),
          @soldqty int,
          @soldrate float,
          @soldamount float,
          @solddetno int,
          @consultantcode varchar(100),
          @consultantname varchar(500),
		  @flags int,
          @flagp int,

		  @forholdingtype int,
          @holdtyp varchar(50),
          @holdtypename varchar(200),
		  @prevyrcd varchar(100),
		  @totalpurchase int,
          @pend int,
          @balp int,
		  @gnloss int,
		  @nwopqty int,
          @nwpurchqty int,
          @nwsoldqty int,
          @pendingsolddt varchar(100),
          @pendingsoldqty int,
          @pendingsoldbillno varchar(100),
          @pendingsoldrate varchar(100),
          @pendingsoldamount varchar(100),
          @pendingopdt varchar(100),
          @pendingopqty int,
          @pendingoprate varchar(100),
          @pendingopamount varchar(100),
          @pendingpurchqty int,
          @pendingpurchbillno varchar(100),
          @pendingpurchrate varchar(100),
          @pendingpurchamount varchar(100),
          @pendingpurchdt varchar(100),
          @totscrpname varchar(500),
          @totholdtyp varchar(400),
          @totclosqty float,
          @totcloserate float,
          @totalcloseamount float,
          @totclosedt varchar(100),
          @scriptopqty float,
          @scrptoprate float,
          @scrptopamount float,
          @scrptpurchqty float,
          @scrptpurchrate float,
          @scrptpurchamount float,
          @scrptsoldqty float,
          @scrptsoldrate float,
          @scrptsoldamount float,
          @scrptgnloss float,
          @scrptspec float,
          @scrptshortterm float,
          @scrptlongterm float,
          @scrptlossspec float,
          @scrptgainspec float,
          @dtchck varchar(100),
          @shorttrerm float,
          @longterm float,
          @spec float,
          @losspec float,
          @gainspec float,
          @scrptclosingqty float,
          @scrptclosingrate float,
          @scrptclosingamount float;

  DECLARE @totfrholdingtyp int , @totholdtyp1 varchar(100) , @totholdtypname varchar(100) , @subtotqty float , @subtotrate float , @subtotamt float , @totscrp varchar(500);

	  SET @scriptopqty = 0; SET @scrptoprate = 0; SET @scrptopamount = 0; SET @scrptpurchqty = 0; SET @scrptpurchrate = 0;
	  SET @scrptpurchamount = 0; SET @scrptsoldqty = 0; SET @scrptsoldrate = 0; SET @scrptsoldamount = 0;SET @scrptgnloss = 0;
	  SET @scrptshortterm = 0;SET @scrptlongterm = 0; SET @scrptspec = 0; SET @scrptlossspec = 0; SET @scrptgainspec = 0;
	  SET @scrptclosingqty = 0; SET @scrptclosingrate = 0; SET @scrptclosingamount = 0; SET @losspec = 0; SET @losspec = 0;

	  DECLARE @srno int;
	  SET @srno = 1;
	
	DECLARE @Investmenttype varchar(10);
	SET @Investmenttype = 0;
  /* Status loop starts here */

  DECLARE scriptcodecursor CURSOR READ_ONLY FOR
  SELECT DISTINCT (BrokerBill_Trans.Script_Code)
  FROM BrokerBill_Trans
  JOIN Mst_Script ON Mst_Script.Script_Code = BrokerBill_Trans.Script_Code
  WHERE isFNOBill = @Investmenttype  AND Trans_Dt <= @Todate  AND Member_code = @memcode  AND YearCode = @yearcode
  OPEN scriptcodecursor
  FETCH NEXT FROM scriptcodecursor INTO @scriptcd

  WHILE @@FETCH_STATUS = 0
  BEGIN  
    SET @holdtyp = '110036';
    SET @holdtypename = 'Stock In Trade A/c';

    SET @flags = 0;
    SET @flagp = 0;


    DECLARE datacursor CURSOR READ_ONLY FOR
    SELECT Script_Name,
	  (CASE WHEN FrmNm = 'OP' AND Trans_Dt < @Fromdate AND YearCode = @yearcode THEN CONVERT(date, Trans_Dt, 103)ELSE ''END) AS [Opening Date],
      SUM(CASE WHEN Bill_no = 'Opening' AND FrmNm != 'BB' AND Trans_Dt < @Fromdate THEN Qty ELSE '' END) AS [Opening Qty],
      SUM(CASE WHEN FrmNm = 'OP' AND Trans_Dt < @Fromdate THEN Rate ELSE '' END) AS [Opening Rate],
      SUM(CASE WHEN FrmNm = 'OP' AND Trans_Dt < @Fromdate THEN Amount ELSE '' END) AS [Opening Amount],
      (CASE WHEN TransType = 'Bought' AND FrmNm != 'OP' AND Trans_Dt >= @Fromdate AND Trans_Dt <= @Todate THEN CONVERT(date, Trans_Dt, 103) ELSE '' END) AS [Purhase Date],
      (CASE WHEN TransType = 'Bought' AND FrmNm != 'OP' AND Trans_Dt >= @Fromdate AND Trans_Dt <= @Todate THEN Bill_no ELSE '' END) AS [Purchase_Bill_No],
      SUM(CASE WHEN TransType = 'Bought' AND FrmNm != 'OP' AND Trans_Dt >= @Fromdate AND Trans_Dt <= @Todate THEN Qty ELSE 0 END) AS [Purchase Qty],
      SUM(CASE WHEN TransType = 'Bought' AND FrmNm != 'OP' AND Trans_Dt >= @Fromdate AND Trans_Dt <= @Todate THEN Rate ELSE 0 END) AS [Purchase Rate],
      SUM(CASE WHEN TransType = 'Bought' AND FrmNm != 'OP' AND Trans_Dt >= @Fromdate AND Trans_Dt <= @Todate THEN Amount ELSE 0 END) AS [Purchase Amount],
	  Consultant_code
    FROM BrokerBill_Trans
    JOIN Mst_Script
    ON Mst_Script.Script_Code = BrokerBill_Trans.Script_Code
    WHERE isFNOBill = @Investmenttype AND BrokerBill_Trans.Script_Code = @scriptcd AND TransType = 'Bought' AND Ac_Type = @holdtyp AND Member_code = @memcode AND YearCode = @yearcode
    GROUP BY Bill_no, Script_Name, Trans_Dt, TransType, FrmNm, YearCode, Consultant_code
    ORDER BY Trans_Dt
    
	OPEN datacursor
    FETCH NEXT FROM datacursor INTO @scriptname,@openingdt, @openingqty, @openingrate, @openingamount, @purchasedt, @purchaseBillno, @purchaseqty, @purchaserate, @purchaseamount,@consultantcode

    SET @solddetno = 0; SET @totalpurchase = 0;

    WHILE @@FETCH_STATUS = 0
    BEGIN   /* Purchase loop starts here */
      SET @pend = 0; SET @balp = 0;
      IF (@flags = 1)
		BEGIN
			/* insert data and continue */
			INSERT INTO #tmptable3 (srno, Script_Name, consultant_code, Holding_Type, Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, closing_qty, closing_rate, closing_value, closing_date)
						VALUES (@srno, @scriptname,@consultantcode, @holdtypename, @openingdt, @openingqty, @openingrate, (CONVERT(float, @openingqty) * CONVERT(float, @openingrate)), @purchasedt, @purchaseBillno, @purchaseqty, @purchaserate, @purchaseamount, '', '', '', '', '', @openingqty + @purchaseqty, @openingrate + @purchaserate, @openingamount + @purchaseamount, CASE WHEN @openingqty > 0 THEN @openingdt ELSE @purchasedt END);

			SET @srno = @srno + 1;
		END
      ELSE /* Purchase else starts here */
		BEGIN
        DECLARE solddetailscursor CURSOR READ_ONLY FOR
        SELECT Bill_No, CONVERT(date, Trans_Dt, 103), Qty, Rate, Amount, Consultant_code
        FROM BrokerBill_Trans
        WHERE TransType = 'Sold' AND isFNOBill = @Investmenttype AND Trans_Dt >= @Fromdate AND Trans_Dt <= @Todate AND BrokerBill_Trans.Script_Code = @scriptcd
        AND Ac_Type = @holdtyp AND Member_code = @memcode AND YearCode = @yearcode
        ORDER BY Trans_Dt ASC

        /*IF EXISTS(Select Bill_No, CONVERT(DATE, Trans_Dt, 103),Qty,Rate,Amount from BrokerBill_Trans where TransType='Sold' and isFNOBill=@Investmenttype and Trans_Dt>=@Fromdate and Trans_Dt<=@Todate  and BrokerBill_Trans.Script_Code=@scriptcd and Ac_Type='S0001' and Member_code=@memcode and YearCode=@yearcode order by Trans_No ASC offset @solddetno rows)
        begin*/

        OPEN solddetailscursor
        FETCH NEXT FROM solddetailscursor INTO @soldBillno, @solddt, @soldqty, @soldrate, @soldamount,@Consultantcode
        IF (@@FETCH_STATUS = 0)
			BEGIN
				WHILE @@FETCH_STATUS = 0
					BEGIN /* Sales loop starts here */
						IF (@totalpurchase <= 0)
							BEGIN
								SET @totalpurchase = @openingqty + @purchaseqty;
							END
								PRINT @totalpurchase;
								PRINT @soldqty;
						IF (@flagp = 1)
							BEGIN
							/* insert and continue */
								PRINT 'no purchase';
								INSERT INTO #tmptable3 (srno, Script_Name, Holding_Type, Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, closing_qty, closing_rate, closing_value, closing_date,consultant_code)
								VALUES (@srno, @scriptname, @holdtypename, @openingdt, @openingqty, @openingrate, @openingamount, '', '', '', '', '', @solddt, @soldBillno, @soldqty, @soldrate, @soldamount, -@soldqty, @soldrate, -@soldamount, CASE WHEN @openingqty > 0 THEN @openingdt ELSE @purchasedt END,@consultantcode);
								SET @srno = @srno + 1;
							END
						ELSE /* Sales else starts here */
							BEGIN
						IF (@totalpurchase = @soldqty)
							BEGIN
								IF (@pend = 1)
									BEGIN
										SET @gnloss = @soldqty * @soldrate - @soldqty * @openingrate - @soldqty * @purchaserate;
										IF (@openingqty > 0)
											BEGIN
												SET @dtchck = @openingdt;
											END
										ELSE
											BEGIN
												SET @dtchck = @purchasedt;
											END
								IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 365
								AND DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 0)
									BEGIN
										SET @shorttrerm = @gnloss; SET @longterm = 0; SET @spec = 0;
									END
								ELSE
									IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 365)
										BEGIN
											SET @longterm = @gnloss;SET @shorttrerm = 0;SET @spec = 0;
										END
									ELSE
										IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 0)
											BEGIN
												SET @spec = @gnloss; SET @shorttrerm = 0; SET @longterm = 0;
												IF (@spec < 0)
													BEGIN
														SET @losspec = @gnloss;SET @gainspec = 0;
													END
												ELSE
													BEGIN
														SET @gainspec = @gnloss;SET @losspec = 0;
													END


                  END
                  INSERT INTO #tmptable3 (srno, Script_Name, Holding_Type, Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, Gain_Loss, short_term, long_term, speculation, loss_speculation, gain_speculation,consultant_code)
                    VALUES (@srno, @scriptname, @holdtypename, '', '', '', '', '', '', '', '', '', @solddt, @soldBillno, @soldqty, @soldrate, (CONVERT(float, @soldqty) * CONVERT(float, @soldrate)), @gnloss, @shorttrerm, @longterm, @spec, @losspec, @gainspec,@consultantcode);
                  SET @srno = @srno + 1;
                  SET @pend = 0;
                END
                ELSE
                BEGIN
                  SET @gnloss = @soldqty * @soldrate - @openingqty * @openingrate - @purchaseqty * @purchaserate;
                  IF (@openingqty > 0)
                  BEGIN
                    SET @dtchck = @openingdt;
                  END
                  ELSE
                  BEGIN
                    SET @dtchck = @purchasedt;
                  END


                  IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 365
                    AND DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 0)
                  BEGIN

                    SET @shorttrerm = @gnloss;
                    SET @longterm = 0;
                    SET @spec = 0;
                  END
                  ELSE
                  IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 365)
                  BEGIN
                    SET @longterm = @gnloss;
                    SET @shorttrerm = 0;
                    SET @spec = 0;
                  END
                  ELSE
                  IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 0)
                  BEGIN
                    SET @spec = @gnloss;
                    SET @shorttrerm = 0;
                    SET @longterm = 0;


                    IF (@spec < 0)
                    BEGIN
                      SET @losspec = @gnloss;
                      SET @gainspec = 0;
                    END
                    ELSE
                    BEGIN
                      SET @gainspec = @gnloss;
                      SET @losspec = 0;
                    END


                  END


                  INSERT INTO #tmptable3 (srno, Script_Name, Holding_Type, Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, Gain_Loss, short_term, long_term, speculation, loss_speculation, gain_speculation,consultant_code)
                    VALUES (@srno, @scriptname, @holdtypename, @openingdt, @openingqty, @openingrate, @openingamount, @purchasedt, @purchaseBillno, @purchaseqty, @purchaserate, @purchaseamount, @solddt, @soldBillno, @soldqty, @soldrate, (CONVERT(float, @soldqty) * CONVERT(float, @soldrate)), @gnloss, @shorttrerm, @longterm, @spec, @losspec, @gainspec,@consultantcode);

                  SET @srno = @srno + 1;
                END

                FETCH NEXT FROM datacursor INTO @scriptname, @openingdt, @openingqty, @openingrate, @openingamount, @purchasedt, @purchaseBillno, @purchaseqty, @purchaserate, @purchaseamount, @consultantcode
                IF (@@FETCH_STATUS != 0)
                BEGIN
                  SET @flagp = 1;
                END
                SET @pend = 0;
                SET @balp = 1;
              END

						ELSE IF (@totalpurchase > @soldqty)
							BEGIN
								IF (@pend = 1)
									BEGIN
										SET @gnloss = @soldqty * @soldrate - @soldqty * @openingrate - @soldqty * @purchaserate;
										IF (@openingqty > 0)
											BEGIN
												SET @dtchck = @openingdt;
											END
										ELSE
											BEGIN
												SET @dtchck = @purchasedt;
											END


										IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 365
											AND DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 0)
											BEGIN
												SET @shorttrerm = @gnloss;SET @longterm = 0;SET @spec = 0;
											END
										ELSE IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 365)
											BEGIN
												SET @longterm = @gnloss; SET @shorttrerm = 0; SET @spec = 0;
											END
										ELSE IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 0)
											BEGIN
												SET @spec = @gnloss; SET @shorttrerm = 0; SET @longterm = 0;
												IF (@spec < 0)
													BEGIN
													  SET @losspec = @gnloss;
													  SET @gainspec = 0;
													END
												ELSE
													BEGIN
													  SET @gainspec = @gnloss;
													  SET @losspec = 0;
													END
											END
												INSERT INTO #tmptable3 (srno, Script_Name, Holding_Type, Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, Gain_Loss, short_term, long_term, speculation, loss_speculation, gain_speculation,consultant_code)
												VALUES (@srno, @scriptname, @holdtypename, '', '', '', '', '', '', '', '', '', @solddt, @soldBillno, @soldqty, @soldrate, (CONVERT(float, @soldqty) * CONVERT(float, @soldrate)), @gnloss, @shorttrerm, @longterm, @spec, @losspec, @gainspec,@consultantcode);
												SET @srno = @srno + 1;
								END
								ELSE
									BEGIN
									  SET @gnloss = @soldqty * @soldrate - @soldqty * @openingrate - @soldqty * @purchaserate;
									  IF (@openingqty > 0)
										  BEGIN
											SET @dtchck = @openingdt;
										  END
										ELSE
										  BEGIN
											SET @dtchck = @purchasedt;
										  END
										IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 365
											AND DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 0)
											BEGIN
												SET @shorttrerm = @gnloss;SET @longterm = 0;SET @spec = 0;
											END
										ELSE IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 365)
											BEGIN
												SET @longterm = @gnloss;
												SET @shorttrerm = 0;
												SET @spec = 0;
											END
										ELSE IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 0)
											BEGIN
												SET @spec = @gnloss; SET @shorttrerm = 0; SET @longterm = 0;
												IF (@spec < 0)
													BEGIN
														SET @losspec = @gnloss;
														SET @gainspec = 0;
													END
												ELSE
													BEGIN
														SET @gainspec = @gnloss;
														SET @losspec = 0;
													END

											END
												  INSERT INTO #tmptable3 (srno, Script_Name, Holding_Type, Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, Gain_Loss, short_term, long_term, speculation, loss_speculation, gain_speculation,consultant_code)
													VALUES (@srno, @scriptname, @holdtypename, @openingdt, @openingqty, @openingrate, @openingamount, @purchasedt, @purchaseBillno, @purchaseqty, @purchaserate, @purchaseamount, @solddt, @soldBillno, @soldqty, @soldrate, (CONVERT(float, @soldqty) * CONVERT(float, @soldrate)), @gnloss, @shorttrerm, @longterm, @spec, @losspec, @gainspec,@consultantcode);
												  SET @srno = @srno + 1;
									END
                SET @totalpurchase = @totalpurchase - @soldqty;

                SET @pend = 1;
             

              END /* P>S ends here */

              ELSE /* S>P starts here */
              BEGIN
                IF (@pend = 1)
                BEGIN
                  SET @gnloss = @totalpurchase * @soldrate - @totalpurchase * @openingrate - @totalpurchase * @purchaserate;

                  IF (@openingqty > 0)
                  BEGIN
                    SET @dtchck = @openingdt;
                  END
                  ELSE
                  BEGIN
                    SET @dtchck = @purchasedt;
                  END


                  IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 365
                    AND DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 0)
                  BEGIN

                    SET @shorttrerm = @gnloss;
                    SET @longterm = 0;
                    SET @spec = 0;
                  END
                  ELSE
                  IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 365)
                  BEGIN
                    SET @longterm = @gnloss;
                    SET @shorttrerm = 0;
                    SET @spec = 0;
                  END
                  ELSE
                  IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 0)
                  BEGIN
                    SET @spec = @gnloss;
                    SET @shorttrerm = 0;
                    SET @longterm = 0;

                    IF (@spec < 0)
                    BEGIN
                      SET @losspec = @gnloss;
                      SET @gainspec = 0;
                    END
                    ELSE
                    BEGIN
                      SET @gainspec = @gnloss;
                      SET @losspec = 0;
                    END

                  END





                  INSERT INTO #tmptable3 (srno, Script_Name, Holding_Type, Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, Gain_Loss, short_term, long_term, speculation, loss_speculation, gain_speculation,consultant_code)
                    VALUES (@srno, @scriptname, @holdtypename, '', '', '', '', '', '', '', '', '', @solddt, @soldBillno, @totalpurchase, @soldrate, (CONVERT(float, @totalpurchase) * CONVERT(float, @soldrate)), @gnloss, @shorttrerm, @longterm, @spec, @losspec, @gainspec,@consultantcode);

                  SET @srno = @srno + 1;
                END
                ELSE
                BEGIN
                  SET @gnloss = @totalpurchase * @soldrate - @openingqty * @openingrate - @purchaseqty * @purchaserate;


                  IF (@openingqty > 0)
                  BEGIN
                    SET @dtchck = @openingdt;
                  END
                  ELSE
                  BEGIN
                    SET @dtchck = @purchasedt;
                  END


                  IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 365
                    AND DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 0)
                  BEGIN

                    SET @shorttrerm = @gnloss;
                    SET @longterm = 0;
                    SET @spec = 0;
                  END
                  ELSE
                  IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 365)
                  BEGIN
                    SET @longterm = @gnloss;
                    SET @shorttrerm = 0;
                    SET @spec = 0;
                  END
                  ELSE
                  IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 0)
                  BEGIN
                    SET @spec = @gnloss;
                    SET @shorttrerm = 0;
                    SET @longterm = 0;

                    IF (@spec < 0)
                    BEGIN
                      SET @losspec = @gnloss;
                      SET @gainspec = 0;
                    END
                    ELSE
                    BEGIN
                      SET @gainspec = @gnloss;
                      SET @losspec = 0;
                    END

                  END



                  INSERT INTO #tmptable3 (srno, Script_Name, Holding_Type, Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, Gain_Loss, short_term, long_term, speculation, loss_speculation, gain_speculation,consultant_code)
                    VALUES (@srno, @scriptname, @holdtypename, @openingdt, @openingqty, @openingrate, @openingamount, @purchasedt, @purchaseBillno, @purchaseqty, @purchaserate, @purchaseamount, @solddt, @soldBillno, @totalpurchase, @soldrate, (CONVERT(float, @totalpurchase) * CONVERT(float, @soldrate)), @gnloss, @shorttrerm, @longterm, @spec, @losspec, @gainspec,@consultantcode);

                  SET @srno = @srno + 1;
                END
                SET @soldqty = @soldqty - @totalpurchase;

                WHILE (@soldqty > 0)
                BEGIN
                  FETCH NEXT FROM datacursor INTO @scriptname, @openingdt, @openingqty, @openingrate, @openingamount, @purchasedt, @purchaseBillno, @purchaseqty, @purchaserate, @purchaseamount,@consultantcode
                  IF (@@FETCH_STATUS != 0)
                  BEGIN
                    SET @flagp = 1;
                    BREAK;
                  END
                  SET @totalpurchase = @openingqty + @purchaseqty;
                  IF (@soldqty > @totalpurchase)
                  BEGIN
                    SET @gnloss = @totalpurchase * @soldrate - @totalpurchase * @openingrate - @totalpurchase * @purchaserate;


                    IF (@openingqty > 0)
                    BEGIN
                      SET @dtchck = @openingdt;
                    END
                    ELSE
                    BEGIN
                      SET @dtchck = @purchasedt;
                    END


                    IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 365
                      AND DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 0)
                    BEGIN

                      SET @shorttrerm = @gnloss;
                      SET @longterm = 0;
                      SET @spec = 0;
                    END
                    ELSE
                    IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 365)
                    BEGIN
                      SET @longterm = @gnloss;
                      SET @shorttrerm = 0;
                      SET @spec = 0;
                    END
                    ELSE
                    IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 0)
                    BEGIN
                      SET @spec = @gnloss;
                      SET @shorttrerm = 0;
                      SET @longterm = 0;

                      IF (@spec < 0)
                      BEGIN
                        SET @losspec = @gnloss;
                        SET @gainspec = 0;
                      END
                      ELSE
                      BEGIN
                        SET @gainspec = @gnloss;
                        SET @losspec = 0;
                      END

                    END



                    INSERT INTO #tmptable3 (srno, Script_Name, Holding_Type,Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, Gain_Loss, short_term, long_term, speculation, loss_speculation, gain_speculation,consultant_code)
                      VALUES (@srno, @scriptname, @holdtypename, @openingdt, @openingqty, @openingrate, @openingamount, @purchasedt, @purchaseBillno, @purchaseqty, @purchaserate, @purchaseamount, @solddt, @soldBillno, @totalpurchase, @soldrate, (CONVERT(float, @totalpurchase) * CONVERT(float, @soldrate)), @gnloss, @shorttrerm, @longterm, @spec, @losspec, @gainspec,@consultantcode);

                    SET @srno = @srno + 1;
                  END
                  ELSE
                  BEGIN
                    SET @gnloss = @soldqty * @soldrate - @soldqty * @openingrate - @soldqty * @purchaserate;
                    IF (@openingqty > 0)
                    BEGIN
                      SET @dtchck = @openingdt;
                    END
                    ELSE
                    BEGIN
                      SET @dtchck = @purchasedt;
                    END


                    IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 365
                      AND DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 0)
                    BEGIN

                      SET @shorttrerm = @gnloss;
                      SET @longterm = 0;
                      SET @spec = 0;
                    END
                    ELSE
                    IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) > 365)
                    BEGIN
                      SET @longterm = @gnloss;
                      SET @shorttrerm = 0;
                      SET @spec = 0;
                    END
                    ELSE
                    IF (DATEDIFF(D, CONVERT(varchar(10), @dtchck, 103), CONVERT(varchar(10), @solddt, 103)) <= 0)
                    BEGIN
                      SET @spec = @gnloss;
                      SET @shorttrerm = 0;
                      SET @longterm = 0;

                      IF (@spec < 0)
                      BEGIN
                        SET @losspec = @gnloss;
                        SET @gainspec = 0;
                      END
                      ELSE
                      BEGIN
                        SET @gainspec = @gnloss;
                        SET @losspec = 0;
                      END

                    END



                    INSERT INTO #tmptable3 (srno, Script_Name, Holding_Type, Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, Gain_Loss, short_term, long_term, speculation, loss_speculation, gain_speculation,consultant_code)
                      VALUES (@srno, @scriptname, @holdtypename, @openingdt, @openingqty, @openingrate, @openingamount, @purchasedt, @purchaseBillno, @purchaseqty, @purchaserate, @purchaseamount, @solddt, @soldBillno, @soldqty, @soldrate, (CONVERT(float, @soldqty) * CONVERT(float, @soldrate)), @gnloss, @shorttrerm, @longterm, @spec, @losspec, @gainspec,@consultantcode);

                    SET @srno = @srno + 1;
                  END

                  SET @totalpurchase = @totalpurchase - @soldqty;
                  SET @soldqty = @soldqty - (@openingqty + @purchaseqty);

                  PRINT 'Totalpurchase=' + CONVERT(varchar, @totalpurchase);
                  IF (@totalpurchase = 0)
                  BEGIN
                    FETCH NEXT FROM datacursor INTO @scriptname, @openingdt, @openingqty, @openingrate, @openingamount, @purchasedt, @purchaseBillno, @purchaseqty, @purchaserate, @purchaseamount,@consultantcode
                    IF (@@FETCH_STATUS != 0)
                    BEGIN
                      SET @flagp = 1;
                    END
                    ELSE
                    BEGIN
                      SET @totalpurchase = @openingqty + @purchaseqty;
                    END
                  END
                END
                IF (@soldqty > 0)
                BEGIN
                  INSERT INTO #tmptable3 (srno, Script_Name, Holding_Type, Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, closing_qty, closing_rate, closing_value, closing_date,consultant_code)
                    VALUES (@srno, @scriptname, @holdtypename, '', '', '', '', '', '', '', '', '', @solddt, @soldBillno, @soldqty, @soldrate, (CONVERT(float, @soldqty) * CONVERT(float, @soldrate)), -@soldqty, @soldrate, -@soldqty * @soldrate, CASE WHEN @openingqty > 0 THEN @openingdt ELSE @purchasedt END,@consultantcode);
                  SET @srno = @srno + 1;
                END
              END   /* S>P ends here */


            END /* sales else ends here */

            FETCH NEXT FROM solddetailscursor INTO @soldBillno, @solddt, @soldqty, @soldrate, @soldamount,@consultantcode
            SET @solddetno = @solddetno + 1;
          END  /* sales loop ends here */
        END
        ELSE
        BEGIN
          INSERT INTO #tmptable3 (srno, Script_Name, Holding_Type, Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, closing_qty, closing_rate, closing_value, closing_date,consultant_code)
            VALUES (@srno, @scriptname, @holdtypename, @openingdt, @openingqty, @openingrate, (CONVERT(float, @openingqty) * CONVERT(float, @openingrate)), @purchasedt, @purchaseBillno, @purchaseqty, @purchaserate, @purchaseamount, '', '', '', '', '', @openingqty + @purchaseqty, @openingrate + @purchaserate, @openingamount + @purchaseamount, CASE WHEN @openingqty > 0 THEN @openingdt ELSE @purchasedt END,@consultantcode);


          SET @srno = @srno + 1;
        END
        SET @flags = 1;
        PRINT @flags;
        IF (@totalpurchase > 0
          AND @balp = 0)
        BEGIN
          PRINT 'Tp-' + CONVERT(varchar, @totalpurchase);
          UPDATE #tmptable3 SET closing_qty = @totalpurchase, closing_rate = @openingrate + @purchaserate,
								closing_value = @totalpurchase * (@openingrate + @purchaserate),
								closing_date = (CASE WHEN @openingqty > 0 THEN @openingdt ELSE @purchasedt
								END)
          WHERE srno = (SELECT MAX(srno) FROM #tmptable3) AND closing_qty = 0;
        END
        CLOSE solddetailscursor
        DEALLOCATE solddetailscursor


      END /* Purchase else ends here */


      FETCH NEXT FROM datacursor INTO @scriptname, @openingdt, @openingqty, @openingrate, @openingamount, @purchasedt, @purchaseBillno, @purchaseqty, @purchaserate, @purchaseamount,@consultantcode
    END /* Purchase loop ends here */
    SET @flagp = 1;

    CLOSE datacursor
    DEALLOCATE datacursor

    IF (@flags = 0) /* no purchase , run only sales */
    BEGIN
      DECLARE solddetailscursor CURSOR READ_ONLY FOR

      SELECT Script_Name,Bill_No,CONVERT(date, Trans_Dt, 103),Qty,Rate,Amount,Consultant_code
      FROM BrokerBill_Trans
      JOIN Mst_Script
      ON BrokerBill_Trans.Script_Code = Mst_Script.Script_Code
      WHERE TransType = 'Sold'
      AND isFNOBill = @Investmenttype AND Trans_Dt >= @Fromdate AND Trans_Dt <= @Todate AND BrokerBill_Trans.Script_Code = @scriptcd
      AND Ac_Type = @holdtyp AND Member_code = @memcode AND YearCode = @yearcode
      ORDER BY Trans_Dt ASC

      OPEN solddetailscursor

      FETCH NEXT FROM solddetailscursor INTO @scriptname, @soldBillno, @solddt, @soldqty, @soldrate, @soldamount,@consultantcode

      WHILE @@FETCH_STATUS = 0
      BEGIN
        INSERT INTO #tmptable3 (srno, Script_Name, Holding_Type, Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, closing_qty, closing_rate, closing_value, closing_date,consultant_code)
          VALUES (@srno, @scriptname, @holdtypename, '', '', '', '', '', '', '', '', '', @solddt, @soldBillno, @soldqty, @soldrate, (CONVERT(float, @soldqty) * CONVERT(float, @soldrate)), -@soldqty, @soldrate, -@soldamount, CASE WHEN @openingqty > 0 THEN @openingdt ELSE @purchasedt END,@consultantcode);
        SET @srno = @srno + 1;

        FETCH NEXT FROM solddetailscursor INTO @scriptname, @soldBillno, @solddt, @soldqty, @soldrate, @soldamount,@consultantcode
      END
      CLOSE solddetailscursor
      DEALLOCATE solddetailscursor
    END
    /************holding type total start***************************************/
    IF EXISTS (SELECT
        *
      FROM #tmptable3
      WHERE Script_Name = @scriptname
      AND Holding_Type = @holdtypename)
    BEGIN
      DECLARE sumholdingtypecursor CURSOR READ_ONLY FOR

      SELECT
			SUM(CONVERT(float, Opening_Qty)),SUM(CONVERT(float, Opening_Rate)),SUM(CONVERT(float, Opening_Amount)),SUM(CONVERT(float, Purchase_Qty)),
			SUM(CONVERT(float, Purchase_Rate)),SUM(CONVERT(float, Purchase_Amount)),SUM(CONVERT(float, Sold_Qty)),SUM(CONVERT(float, Sold_Rate)),
			SUM(CONVERT(float, Sold_Amount)),SUM(CONVERT(float, Gain_Loss)),SUM(CONVERT(float, short_term)),SUM(CONVERT(float, long_term)),
			SUM(CONVERT(float, speculation)),SUM(CONVERT(float, loss_speculation)),SUM(CONVERT(float, gain_speculation)),
			SUM(CONVERT(float, closing_qty)),SUM(CONVERT(float, closing_rate)),SUM(CONVERT(float, closing_value))
      FROM #tmptable3
      WHERE Script_Name = @scriptname
      AND Holding_Type = @holdtypename;
      OPEN sumholdingtypecursor
      FETCH NEXT FROM sumholdingtypecursor INTO @scriptopqty, @scrptoprate, @scrptopamount, @scrptpurchqty, @scrptpurchrate, @scrptpurchamount, @scrptsoldqty, @scrptsoldrate, @scrptsoldamount, @scrptgnloss, @scrptshortterm, @scrptlongterm, @scrptspec, @scrptlossspec, @scrptgainspec, @scrptclosingqty, @scrptclosingrate, @scrptclosingamount

      IF @@FETCH_STATUS = 0
      BEGIN

        INSERT INTO #tmptable3 (srno, Script_Name, Holding_Type, Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, Gain_Loss, short_term, long_term, speculation, loss_speculation, gain_speculation, closing_qty, closing_rate, closing_value, flag)
          VALUES (@srno, '', 'Total for ' + @holdtypename, '', @scriptopqty, @scrptoprate, @scrptopamount, '', '', @scrptpurchqty, @scrptpurchrate, @scrptpurchamount, '', '', @scrptsoldqty, @scrptsoldrate, @scrptsoldamount, @scrptgnloss, @scrptshortterm, @scrptlongterm, @scrptspec, @scrptlossspec, @scrptgainspec, @scrptclosingqty, CASE WHEN @scrptclosingqty > 0 THEN @scrptclosingamount / @scrptclosingqty ELSE 0 END, @scrptclosingamount, CASE WHEN @forholdingtype = 1 THEN 1 ELSE 2 END);

      END


      CLOSE sumholdingtypecursor
      DEALLOCATE sumholdingtypecursor
    END

    /* for script total*/
    IF EXISTS (SELECT
        *
      FROM #tmptable3
      WHERE Script_Name = @scriptname)
    BEGIN


      DECLARE sumsciptpecursor CURSOR READ_ONLY FOR
      SELECT
			SUM(CONVERT(float, Opening_Qty)),SUM(CONVERT(float, Opening_Rate)),SUM(CONVERT(float, Opening_Amount)),SUM(CONVERT(float, Purchase_Qty)),
			SUM(CONVERT(float, Purchase_Rate)),SUM(CONVERT(float, Purchase_Amount)),SUM(CONVERT(float, Sold_Qty)),SUM(CONVERT(float, Sold_Rate)),
			SUM(CONVERT(float, Sold_Amount)),SUM(CONVERT(float, Gain_Loss)),SUM(CONVERT(float, short_term)),SUM(CONVERT(float, long_term)),
			SUM(CONVERT(float, speculation)),SUM(CONVERT(float, loss_speculation)),SUM(CONVERT(float, gain_speculation)),SUM(CONVERT(float, closing_qty)),
			SUM(CONVERT(float, closing_rate)),SUM(CONVERT(float, closing_value))
      FROM #tmptable3
      WHERE Script_Name = @scriptname;
      OPEN sumsciptpecursor


      FETCH NEXT FROM sumsciptpecursor INTO @scriptopqty, @scrptoprate, @scrptopamount, @scrptpurchqty, @scrptpurchrate, @scrptpurchamount, @scrptsoldqty, @scrptsoldrate, @scrptsoldamount, @scrptgnloss, @scrptshortterm, @scrptlongterm, @scrptspec, @scrptlossspec, @scrptgainspec, @scrptclosingqty, @scrptclosingrate, @scrptclosingamount

      IF @@FETCH_STATUS = 0
      BEGIN

        INSERT INTO #tmptable3 (srno, Script_Name, Holding_Type, Opening_Date, Opening_Qty, Opening_Rate, Opening_Amount, Purchase_Date, Purchase_Bill_No, Purchase_Qty, Purchase_Rate, Purchase_Amount, Sold_Date, Sold_Bill_No, Sold_Qty, Sold_Rate, Sold_Amount, Gain_Loss, short_term, long_term, speculation, loss_speculation, gain_speculation, closing_qty, closing_rate, closing_value, flag)
          VALUES (@srno, 'Total for ' + @scriptname, '', '', @scriptopqty, @scrptoprate, @scrptopamount, '', '', @scrptpurchqty, @scrptpurchrate, @scrptpurchamount, '', '', @scrptsoldqty, @scrptsoldrate, @scrptsoldamount, @scrptgnloss, @scrptshortterm, @scrptlongterm, @scrptspec, @scrptlossspec, @scrptgainspec, @scrptclosingqty, CASE WHEN @scrptclosingqty > 0 THEN @scrptclosingamount / @scrptclosingqty ELSE 0 END, @scrptclosingamount, 3);

      END


      CLOSE sumsciptpecursor
      DEALLOCATE sumsciptpecursor
    END
    /************ script total end***************************************/


    UPDATE #tmptable3
    SET Script_Code = @scriptcd;

    FETCH NEXT FROM scriptcodecursor INTO @scriptcd
  END /* Script loop ends here */

  CLOSE scriptcodecursor
  DEALLOCATE scriptcodecursor


  DECLARE fncursor CURSOR READ_ONLY FOR
  SELECT DISTINCT
    (Script_Code),
    Script_Name
  FROM #tmptable3
  WHERE flag = 0;
  OPEN fncursor
  FETCH NEXT FROM fncursor INTO @scriptcd, @totscrpname
  WHILE @@FETCH_STATUS = 0
  BEGIN

    PRINT 'kk' + @scriptcd;

    DECLARE @clqty float;
    SET @clqty = 0;
    DECLARE fncursor1 CURSOR READ_ONLY FOR
    SELECT
      SUM(CONVERT(float, closing_qty))
    FROM #tmptable3
    WHERE Script_Code = @scriptcd
    AND flag = 0;
    OPEN fncursor1
    FETCH NEXT FROM fncursor1 INTO @clqty;
    IF @@FETCH_STATUS = 0

    BEGIN


      IF (@clqty >= 0)
      BEGIN
        INSERT INTO #tmptable4 (Script_Name, Script_Code, closing_qty,Consultant_Code)
          VALUES (@totscrpname, @scriptcd, @clqty,@consultantcode);
      END


    END

    CLOSE fncursor1
    DEALLOCATE fncursor1


    FETCH NEXT FROM fncursor INTO @scriptcd, @totscrpname



  END
  CLOSE fncursor
  DEALLOCATE fncursor

  SELECT *   FROM #tmptable4
END /* Procedure ends here */






















GO
/****** Object:  StoredProcedure [dbo].[tmpupdateholdings]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tmpupdateholdings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[tmpupdateholdings] AS' 
END
GO
ALTER proc [dbo].[tmpupdateholdings]
as
begin
	select * from tmpholding where buysell='b';
	

	UPDATE  t1 
	  SET t1.currentqty = (select sum(qty) from tmpholding)-(case when t2.buysell ='b' then t2.qty else -1*t2.qty end)
  FROM tmpholding AS t1
  INNER JOIN tmpholding AS t2
  ON t1.stockname = t2.stockname
 -- WHERE t1.buysell='b' and t2.buysell='s'   group by t1.stockid
  /*
  update tmpholding set currentqty = (select sum(qty) from tmpholding group by stockname) - (select case when t2.buysell ='b' then t2.qty else -1*t2.qty end qty from tmpholding t2)
exec tmpupdateholdings
  */
end
























GO
/****** Object:  StoredProcedure [dbo].[UpdateData_withTaxAmount_INNetAmount]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateData_withTaxAmount_INNetAmount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[UpdateData_withTaxAmount_INNetAmount] AS' 
END
GO
ALTER Procedure [dbo].[UpdateData_withTaxAmount_INNetAmount]
(
@Membercode Varchar(Max),
@Yearcode Varchar(200),
@InvestmentType int

)
As
if(@InvestmentType='0')
Begin
SET NOCOUNT ON;
 --Select Sum(Amount)As 'Amount',BrokerBill_Trans.Bill_no,BrokerBill_Trans.isFNOBill from BrokerBill_Trans where  isFNOBill='0'
 --Group by BrokerBill_Trans.Bill_no,BrokerBill_Trans.isFNOBill
 Select  BBT.Trans_No ,
(Select Sum(BBT1.Amount) from BrokerBill_Trans BBT1 where BBT1.Trans_No=BBT.Trans_No) As 'Turnover Amount',
( Select SUM(AC1.Amount) from AC_Trans AC1 where AC1.Trans_No=BBT.Trans_No) as'Ac_trans Amount',
(Select (BB1.Amount) from  BrokerBill BB1 where BB1.Trans_no=BBT.Trans_no) as 'BrokerBill Amount',
(( Select SUM(AC1.Amount) from AC_Trans AC1 where AC1.Trans_No=BBT.Trans_No)-(Select (BB1.Amount) from  BrokerBill BB1 where BB1.Trans_no=BBT.Trans_no)) as'Expense Amount'
from BrokerBill_Trans BBT
Inner Join AC_Trans as Ac On
(BBT.Trans_No=Ac.Trans_No)
inner join BrokerBill as BB on
(BBT.Trans_No=BB.Trans_no)
where BBT.Member_code='A0001' and BBT.YearCode='1120172018' and BBT.isFNOBill='0'
Group By BBT.Trans_No

End























GO
/****** Object:  StoredProcedure [dbo].[UpdateScriptMaster]    Script Date: 01/11/2019 12:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateScriptMaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[UpdateScriptMaster] AS' 
END
GO
ALTER PROCEDURE [dbo].[UpdateScriptMaster] 
	@InvestmentType int
AS
BEGIN
	SET NOCOUNT ON;
	Truncate table Mst_Script_Temp_BKP

	-- MST SCRIPT BACK UP
	INSERT INTO Mst_Script_Temp_BKP
	SELECT * FROM MST_SCRIPT

	-- NOW Trncate andf insert data into mst script
	Truncate table Mst_Script

	-- MST SCRIPT BACK UP
	INSERT INTO MST_SCRIPT
	SELECT * FROM Mst_Script_Temp

	-- Now remove data from temp table
	Truncate table Mst_Script_Temp

	IF(@InvestmentType = 0)
		BEGIN
	-------------------------------------------------------------------Industry Master-------------------------------------------
			Truncate table Mst_Industry_Temp_BKP

			-- MST SCRIPT BACK UP
			INSERT INTO Mst_Industry_Temp_BKP
			SELECT * FROM MST_Industry

			-- NOW Trncate andf insert data into mst script
			Truncate table MST_Industry

			-- MST SCRIPT BACK UP
			INSERT INTO MST_Industry
			SELECT * FROM Mst_Industry_temp

			-- Now remove data from temp table
			Truncate table Mst_Industry_temp
		END

	ELSE IF(@InvestmentType = 2)
		BEGIN
	-------------------------------------------------------------------Industry Master-------------------------------------------
			Truncate table Mst_MF_Family_Temp_BKP

			-- MST SCRIPT BACK UP
			INSERT INTO Mst_MF_Family_Temp_BKP
			SELECT * FROM mst_MF_Family

			-- NOW Trncate andf insert data into mst script
			Truncate table mst_MF_Family

			-- MST SCRIPT BACK UP
			INSERT INTO mst_MF_Family
			SELECT * FROM Mst_MF_Family_Temp

			-- Now remove data from temp table
			Truncate table Mst_MF_Family_Temp
		END

	

END






GO
