Stored procedure passing like statement in case - sql

ALTER PROCEDURE [dbo].[ViewSo]
#Dt1 as datetime,
#Dt2 as datetime,
#CusName as nvarchar,
#so_no as nvarchar
AS
BEGIN
SET NOCOUNT ON;
SELECT *
FROM
(SELECT
0 as stat,
m.id, f.id as fg_id, f.fg_des, m.so_no,
Replace(CONVERT(NVARCHAR, CAST(m.so_date AS DATE) , 106),' ','-') AS so_date,
Convert(NVARCHAR,CAST(m.so_date AS DATE),101) AS so_date1,
m.cus_name, m.so_cus_id, m.doc_no, m.sale_person, m.so_rem,
f.fg_des AS eXP1, f.fg_qty,
CONVERT(VARCHAR(10), CAST(f.req_date AS DATE), 101) AS req_date,
CASE
WHEN COALESCE (q.tot_req_qty, 0) < f.fg_qty
THEN 'Not Updated'
ELSE 'Updated'
END AS req_qty_stat,
'SO No :' + CONVERT(varchar(15), m.so_no) + '/SO Date :' + CONVERT(varchar(15), REPLACE(CONVERT(NVARCHAR, CAST(m.so_date AS DATE), 106), ' ', '-')) + '/Cus Name :' + CONVERT(varchar(15), m.cus_name) + '/Sales Prsn :' + CONVERT(varchar(15), m.sale_person) AS filter ,
f.fg_no,m.so_stat,
m.del_flag, m.st_stat, m.st_rem
FROM
so_mas AS m
INNER JOIN
so_fg AS f ON m.id = f.so_id
LEFT OUTER JOIN
(SELECT
fg_id, SUM(req_qty) AS tot_req_qty
FROM
fg_qty
WHERE
(del_flag = 0)
GROUP BY fg_id) AS q ON q.fg_id = f.id
WHERE
m.del_flag = 0) AS S
WHERE
CONVERT(datetime, s.so_date) BETWEEN #Dt1 AND #Dt2
AND S.cus_name LIKE
CASE WHEN #CusName = '' THEN S.cus_name
ELSE +'%' + #CusName + '%'
END
ORDER BY
s.so_date;
END
This is my stored procedure passing like statement in case. If run as query it works fine. If I used as stored produce leads to wrong result.
Please help me to solve.

Replace this part of WHERE
AND S.cus_name LIKE
CASE WHEN #CusName = '' THEN S.cus_name
ELSE +'%' + #CusName + '%'
END
With
AND S.cus_name LIKE
CASE WHEN #CusName = '' THEN S.cus_name
ELSE '%' + #CusName + '%'
END

Related

The multi-part identifier could not be bound in SQL Server 2012

I am trying to use resource attributes table in IF block. Error is in second if block:
Multi-part identifier 'ra.Start_dt' could not be bound
I have used the alias name i.e. ra, even then I get this error. Can someone help me out with this code?
IF (#toyear - #fromyear = 0)
BEGIN
SET #vacsql = 'SELECT DISTINCT
a.resourceID, r.EnterpriseID, r.FullName,
dbo.fnGetWorkOrdersByResourceID(a.resourceID,' +
CAST(#tomonth AS VARCHAR(2)) + ',' +
CAST(#toyear AS VARCHAR(4)) + ') AS WorkOrder,
dbo.fnGetDomainsByResourceID(a.resourceID,' +
CAST(#tomonth AS VARCHAR(2)) + ',' +
CAST(#toyear AS VARCHAR(4)) + ') AS Domain,
l.Offshore_Ind,
SUM(ISNULL(a.Totals, 0)) AS TOTALHOURS
FROM
[Actuals] AS a
JOIN
[Resources] AS r ON a.ResourceID = r.ResourceID
JOIN
Resource_Attributes AS ra ON r.ResourceID = ra.ResourceID
JOIN
Location_LU AS l ON ra.LocationID = l.LocationID
JOIN
Roll_On_Off AS ro ON r.ResourceID = ro.ResourceID
WHERE
(a.TaskName = ''Leave'')
AND a.CalYear = ' + CAST(#toyear AS VARCHAR(10)) +
' AND CalMonthNum <= ' + CAST(#tomonth AS VARCHAR(10)) +
' AND CalMonthNum >= ' + CAST(#frommonth AS VARCHAR(10)) +
'AND (CONVERT(datetime, ro.End_Dt)) > (CONVERT(datetime, '''+cast(concat(#frommonth,'/01/',#toyear) as varchar(10))+'''))
(CONVERT(datetime,ra.Start_dt))<=(CONVERT(datetime,#StartDate)) AND (CONVERT(datetime,ra.End_dt))>=(CONVERT(datetime,#EndDate))
GROUP BY ra.AttributeID,a.ResourceID,r.EnterpriseID,r.FullName,l.offshore_Ind'
if((CONVERT(datetime,ra.Start_dt))<=(CONVERT(datetime,#StartDate)) AND (CONVERT(datetime,ra.End_dt))>=(CONVERT(datetime,#EndDate)) AND CONVERT(datetime,ra.Start_dt) between (CONVERT(datetime,#StartDate)) AND (CONVERT(datetime,#EndDate)))
BEGIN
INSERT INTO #vacTable EXECUTE sp_executesql #vacsql,
N'#StartDate varchar(25), #EndDate varchar(25)',
#StartDate,
#EndDate;
END
try this!
if (#toyear-#fromyear=0)
BEGIN
Set #vacsql = 'SELECT DISTINCT a.resourceID,r.EnterpriseID,r.FullName, dbo.fnGetWorkOrdersByResourceID(a.resourceID,'+ CAST(#tomonth AS VARCHAR(2))+','+CAST(#toyear AS VARCHAR(4)) +') as WorkOrder,
dbo.fnGetDomainsByResourceID(a.resourceID,'+ CAST(#tomonth AS VARCHAR(2))+','+CAST(#toyear AS VARCHAR(4)) +') as Domain, l.Offshore_Ind,SUM(ISNULL(a.Totals,0)) AS TOTALHOURS
FROM [Actuals] AS a join [Resources] AS r on a.ResourceID=r.ResourceID
join Resource_Attributes as ra on r.ResourceID=ra.ResourceID
join Location_LU as l on ra.LocationID=l.LocationID
join Roll_On_Off as ro on r.ResourceID=ro.ResourceID
WHERE (a.TaskName=''Leave'') AND a.CalYear='+CAST(#toyear as varchar(10))+' AND CalMonthNum <='+CAST(#tomonth as varchar(10))+' AND CalMonthNum >='+CAST(#frommonth as varchar(10))+'
AND (CONVERT(datetime,ro.End_Dt))>(CONVERT(datetime,'''+cast(concat(#frommonth,'/01/',#toyear) as varchar(10))+'''))
(CONVERT(datetime,ra.Start_dt))<=(CONVERT(datetime,#StartDate)) AND (CONVERT(datetime,ra.End_dt))>=(CONVERT(datetime,#EndDate))
GROUP BY ra.AttributeID,a.ResourceID,r.EnterpriseID,r.FullName,l.offshore_Ind'
if exists (select 1 from Resource_Attributes ra where (CONVERT(datetime,ra.Start_dt))<=(CONVERT(datetime,#StartDate)) AND (CONVERT(datetime,ra.End_dt))>=(CONVERT(datetime,#EndDate)) AND CONVERT(datetime,ra.Start_dt) between (CONVERT(datetime,#StartDate)) AND (CONVERT(datetime,#EndDate)))
BEGIN
INSERT INTO #vacTable EXECUTE sp_executesql #vacsql,
N'#StartDate varchar(25), #EndDate varchar(25)',
#StartDate,
#EndDate;
END
END

Move aggregate logic to separate function in SQL Server 2008 R2

Please correct me if I'm using the wrong terminology or description, but I have business logic within an aggregate function (MIN and MAX). I wish to move to the logic to it's own function. I wish to do this so I don't have to make multiple changes in different locations when the client requests. I have the following
SELECT DISTINCT
DATA_MONTH,
DATA_DATE,
CASE
WHEN MIN(DATA_YEAR) = MAX(DATA_YEAR)
AND MIN(DATA_YEAR) = #BEGIN_YR THEN 'Started'
WHEN MIN(DATA_YEAR) = MAX(DATA_YEAR)
AND MIN(DATA_YEAR) <> #CURRENTFY THEN
CAST((MIN(DATA_YEAR) %100)-1 AS VARCHAR)
+ '/'
+ CAST(MIN(DATA_YEAR)%100 AS VARCHAR)
WHEN MIN(DATA_YEAR) <> MAX(DATA_YEAR)
AND MIN(DATA_YEAR) = #BEGIN_YR THEN
'Started' + ' from '
+ CAST((MAX(DATA_YEAR) %100)-1 AS VARCHAR)
+ '/'
+ CAST(MAX(DATA_YEAR)%100 AS VARCHAR)
ELSE CAST((MIN(DATA_YEAR) %100)-1 AS VARCHAR)
+ '/'
+ CAST((MIN(DATA_YEAR) %100) AS VARCHAR)
+ ' through '
+ CAST((MAX(DATA_YEAR) %100)-1 AS VARCHAR)
+ '/'
+ CAST(MAX(DATA_YEAR)%100 AS VARCHAR)
END AS [STATUS]
FROM TABLE_A
WHERE DATA_MONTH IN ('03', '04')
AND DATA_DATE = '01'
GROUP BY DATA_MONTH,
DATA_DATE
Which I would like to change it to this:
SELECT DISTINCT
DATA_MONTH,
DATA_DATE,
dbo.getStatus(DATA_YEAR) AS [STATUS]
FROM TABLE_A
WHERE DATA_MONTH IN ('03', '04')
AND DATA_DATE = '01'
GROUP BY DATA_MONTH,
DATA_DATE
The logic for getStatus() has the case statements and can output:
NULL
Started
15/16
Started from 15/16
15/16 through 16/17
My question is how can I restructure my logic to make this possible as I have a GROUP BY clause?
You can create a scalar user defined function and use it in the SELECT. Since it needs to be aggregated, you should be able to throw a MAX around it.
Although, I'd be interested to see if this works.
Nicarus is probably right and that you need a user defined aggregate function.
USE [AdventureWorks2012]
GO
/****** Object: Table [dbo].[TABLE_A] Script Date: 7/20/2016 3:23:39 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TABLE_A](
[DATA_DATE] [date] NULL,
[DATA_MONTH] [int] NOT NULL,
[DATA_YEAR] [int] NOT NULL
) ON [PRIMARY]
GO
INSERT INTO TABLE_A SELECT CAST ('2016-03-02' as DATE) AS DATA_DATE, 3 as DATA_MONTH, 2016 AS DATA_YEAR
CREATE FUNCTION dbo.getStatus(#MAXYR int, #MINYR int, #BEGIN_YR int ,#CURRENTFY int)
RETURNS varchar(30)
AS
BEGIN
DECLARE #ret varchar(30);
SELECT #ret = CASE
WHEN #MINYR = #MAXYR
AND #MINYR = #BEGIN_YR THEN 'Started'
WHEN #MINYR = #MAXYR
AND #MINYR <> #CURRENTFY THEN
CAST((#MINYR %100)-1 AS VARCHAR)
+ '/'
+ CAST(#MINYR%100 AS VARCHAR)
WHEN #MINYR <> #MAXYR
AND #MINYR = #BEGIN_YR THEN
'Started' + ' from '
+ CAST((#MAXYR %100)-1 AS VARCHAR)
+ '/'
+ CAST(#MAXYR%100 AS VARCHAR)
ELSE CAST((#MINYR %100)-1 AS VARCHAR)
+ '/'
+ CAST((#MINYR %100) AS VARCHAR)
+ ' through '
+ CAST((#MAXYR %100)-1 AS VARCHAR)
+ '/'
+ CAST(#MAXYR%100 AS VARCHAR)
END
RETURN #ret;
END;
DECLARE #BEGIN_YR INT = 2;
DECLARE #CURRENTFY int = 2016;
SELECT DISTINCT
DATA_MONTH,
DATA_DATE,
dbo.getStatus(MAX(DATA_YEAR), MIN(DATA_YEAR), #BEGIN_YR, #CURRENTFY) as STATUS
FROM TABLE_A
GROUP BY DATA_MONTH, DATA_DATE

SQL OpenQuery - Escaping Quotes

Been trying for some hours to convert this to a query I can use with OPENQUERY in SQL Server 2014 (to use with Progress OpenEdge 10.2B via ODBC). Can't seem to get the escaping of the quote right. Can anyone offer some assistance? Is there a tool to do it?
(There's a SQL table called #tAPBatches that is used in this, but I omitted it from this code)
DECLARE
#NoDays AS INT = 30
,#Prefix AS VARCHAR(5) = 'M_AP_'
SELECT
#Prefix + LTRIM(CAST(gh.[Batch-Number] AS VARCHAR(20))) AS BatchNo
,gh.[Batch-Number] AS BatchNo8
, aph.[Reference-number] AS InvoiceNo
,aph.[Voucher-Number] AS VoucherNo
,aph.[Amount] AS InvoiceTotal
,gh.[Journal-Number] AS JournalNo
,4 AS FacilityID
,CASE aph.[voucher-type]
WHEN 'DM' THEN 5
ELSE 1
END AS DocType
,apb.[Batch-Desc] AS BatchDesc
,apb.[Posting-Date] AS PostingDate
,apb.[Posting-Period]
,apb.[Posting-Fiscal-Year]
,apb.[Batch-Status]
,apb.[Expected-Count]
,apb.[Expected-Amount]
,apb.[Posted-To-GL-By]
,'Broadview' AS FacilityName
,apb.[Date-Closed] AS BatchDate
,gh.[Posted-by] AS PostUser
,gh.[Posted-Date] AS PostDT
,gh.[Created-Date] AS CreateDT
,gh.[Created-By] AS CreateUser
,aph.[Supplier-Key] AS VendorID
,sn.[Supplier-Name]
,aph.[Invoice-Date] AS InvoiceDate
,-1 AS Total
,-1 AS Discount
,gh.[Posted-by] AS Username
,CASE gt.[Credit-Debit]
WHEN 'CR' THEN LEFT(CAST(gacr.[GL-Acct] AS VARCHAR(20)), 2) + '.' + SUBSTRING(CAST(gacr.[GL-Acct] AS VARCHAR(20)), 3, 6) + '.'
+ RIGHT(CAST(gacr.[GL-Acct] AS VARCHAR(20)), 3)
ELSE NULL
END AS GLCreditAcct
,CASE gt.[Credit-Debit]
WHEN 'DR' THEN LEFT(CAST(gacr.[GL-Acct] AS VARCHAR(20)), 2) + '.' + SUBSTRING(CAST(gacr.[GL-Acct] AS VARCHAR(20)), 3, 6) + '.'
+ RIGHT(CAST(gacr.[GL-Acct] AS VARCHAR(20)), 3)
ELSE NULL
END AS GLDebitAcct
,CASE gt.[Credit-Debit]
WHEN 'CR' THEN gacr.[Report-Label]
ELSE NULL
END AS GLCreditDesc
,CASE gt.[Credit-Debit]
WHEN 'DR' THEN gacr.[Report-Label]
ELSE NULL
END AS GLDebitDesc
,'D' AS [Status]
,aph.[PO-Number] AS PoNo
,aph.[Terms-Code] AS TermsCode
,aph.[Due-Date] AS DueDate
,'' AS Comments
,aph.[Discount-Date] AS DiscountDate
,aph.[Discount-Amount] AS DiscountAmount
,aph.[Discount-Taken] AS DiscountTaken
,aph.[Amount] AS APAmount
,gt.[Amount]
,'BA REGULAR ' AS CheckBookID --ToDO
,0 AS Transferred
,aph.[voucher-type] AS VoucherType
,gt.[Credit-Debit]
,gacr.[Account-type]
,aph.[Freight-Ref-Num]
FROM
[Progress].[GAMS1].pub.[GL-Entry-Header] gh
INNER JOIN [Progress].[GAMS1].pub.[gl-entry-trailer] gt ON gt.[System-ID] = gh.[System-ID] AND gt.[Origin] = gh.[Origin] AND gt.[Journal-Number] = gh.[Journal-Number]
INNER JOIN [Progress].[GAMS1].pub.[apinvhdr] aph ON (gh.[Journal-Number] = aph.[Journal-Number]
OR (gh.[Journal-Num-Reversal-Of] = aph.[Journal-Number] AND aph.[Journal-Number] <> ' ' AND gh.[Journal-Num-Reversal-Of] <> ' '))
AND gh.[system-id] = aph.[system-id-gl]
AND gh.origin = 'inv'
AND gh.[system-id] = 'arcade'
INNER JOIN [Progress].[GAMS1].pub.[APInvoiceBatch] apb ON gh.[Batch-number] = apb.[Batch-number]
AND apb.[system-id] = 'lehigh'
AND apb.[Posted-To-GL] = 1
INNER JOIN [Progress].[GAMS1].pub.[GL-accts] gacr ON gacr.[system-id] = gt.[system-id]
AND gacr.[Gl-Acct-Ptr] = gt.[GL-Acct-Ptr]
INNER JOIN [Progress].[GAMS1].pub.[suppname] sn ON sn.[Supplier-Key] = aph.[Supplier-Key]
AND sn.[system-id] = 'arcade'
WHERE
gh.[Posted-Date] > CAST(DATEADD(DAY, -#NoDays, GETDATE()) AS DATE)
AND case
when CAST(gh."Posting-Period" as int) < 10 then gh."Posting-Year" + '0' + ltrim(gh."Posting-Period")
else gh."Posting-Year" + Ltrim(gh."Posting-Period")
end > '201501'
AND gh.[Batch-number] NOT IN (SELECT
BatchNo COLLATE SQL_Latin1_General_CP1_CI_AS
FROM
#tAPBatches)
TIA
MArk
Here's an example of what's giving me a syntax error. This works, but "M_AP_" is a parameter passed to SP
DECLARE
#NoDays AS INT = 5
,#Prefix AS VARCHAR(5) = 'M_AP_';
DECLARE
#InterestDate AS varchar(20)
SELECT #InterestDate = CAST(CAST(DATEADD(DAY, -#NoDays, GETDATE()) AS DATE) AS VARCHAR(20))
SELECT * FROM OPENQUERY(PROGRESS,
'SELECT TOP 100 ''M_AP_'' + LTRIM(CAST(gh."Batch-Number" AS VARCHAR(20))) AS BatchNo
, gh."Batch-Number"
This works, but when I try to swap in the variable I get Incorrect Syntax near '+'
DECLARE
#NoDays AS INT = 5
,#Prefix AS VARCHAR(5) = 'M_AP_';
DECLARE
#InterestDate AS varchar(20)
SELECT #InterestDate = CAST(CAST(DATEADD(DAY, -#NoDays, GETDATE()) AS DATE) AS VARCHAR(20))
SELECT * FROM OPENQUERY(PROGRESS,
'SELECT TOP 100 '' ' + #Prefix + ' '' + LTRIM(CAST(gh."Batch-Number" AS VARCHAR(20))) AS BatchNo
, gh."Batch-Number"
FROM
"GAMS1".pub."GL-Entry-Header" gh
OPENQUERY will only support a string literal query that is less than 8K. You might be running into that limit if you've got even more code that you're not showing here. Make sure that your query is less than 8000 bytes, or create procedures or views to reduce the size of your query.
It only accepts a single string literal... so if you are trying to concatenate strings and parameters together, it will not work. There are some ways to work around this by using dynamic SQL or creating supporting tables or views for filters.

transform sql query to oracle

i have to transform some query i´m using in SQL to Oracle code. I´m having a lot of trouble with tis. Does anyone know any Query transformer o something like that?. Can someone translate some part of this code for me?.
This is the code:
SELECT PRUEBA = CASE (SELECT TIMEATT FROM READER WHERE PANELID = DEVID AND READERID =
MACHINE) WHEN '1' THEN 'P10' ELSE 'P20' END
+ '0001'
+ CAST(YEAR(EVENT_TIME_UTC)AS VARCHAR)
+ Right('0' + Convert(VarChar(2), Month(EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DAY(EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DATEPART(HOUR,EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DATEPART(MINUTE,EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DATEPART(SECOND,EVENT_TIME_UTC)), 2)
+ CAST(YEAR(EVENT_TIME_UTC)AS VARCHAR)
+ Right('0' + Convert(VarChar(2), Month(EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DAY(EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DATEPART(HOUR,EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DATEPART(MINUTE,EVENT_TIME_UTC)), 2)
+ Right('0' + Convert(VarChar(2), DATEPART(SECOND,EVENT_TIME_UTC)), 2)
+ Right('00000000' + Convert(VarChar(8), CARDNUM), 8)
+ Right('00000000' + Convert(VarChar(8), (SELECT SSNO FROM EMP WHERE ID = EMPID)), 8),
FROM events
WHERE eventid = 0 AND eventid = 0
and machine in (11) AND DEVID IN (1,2)
and CARDNUM <> 0 AND EMPID <> 0
and EVENT_TIME_UTC between '2006-02-16' AND '2007-02-09'
Many thanks for your help, i´ll keep looking.
Try this:
SELECT CASE (SELECT timeatt FROM reader WHERE panelid = devid AND readerid =
machine)
WHEN '1' THEN 'P10'
ELSE 'P20'
END
|| '0001'
|| To_char(event_time_utc, 'RRRRMMDDHH24MISS')
|| To_char(event_time_utc, 'RRRRMMDDHH24MISS')
|| Lpad(cardnum, 8, '0')
|| Lpad((SELECT ssno
FROM emp
WHERE id = empid), 8, '0') AS prueba
FROM events
WHERE eventid = 0
AND eventid = 0
AND machine IN ( 11 )
AND devid IN ( 1, 2 )
AND cardnum <> 0
AND empid <> 0
AND event_time_utc BETWEEN TO_DATE('2006-02-16', 'RRRR-MM-DD') AND TO_DATE('2007-02-09', 'RRRR-MM-DD')
I have recently had to make the same conversion from a life in tSQL to plSQL (oracle). A couple of "gotcha's" in the code you posted:
1) In tSQL the plus sign (for concatenation)+ is replaced in plSQL with double pipe ||
2) Most of the time you need a "Reference Cursor" (REF CURSOR) declared to put your results into like
PROCEDURE DEMO_SELECT_4_SO(
//other parameters followed by//
P_RESULT OUT REF CURSOR)
IS
BEGIN
OPEN P_RESULT FOR
SELECT
//fields///
FROM
a_table
WHERE
//you want..//
OR (as with a scalar result like your query) a single parameter of the correct type, like:
PROCEDURE DEMO_SELECT_4_SO(
//other parameters followed by//
P_RESULT OUT varchar2(60))
IS
BEGIN
SELECT
//concatenated fields///
INTO
P_RESULT
FROM
a_table
WHERE
//you want..//
NOTICE That select into in plSQL assigns the selected value to the target parameter and does not create a table as it would in tSQL
3) RIGHT (or LEFT) are SUBSTR functions in plSQL
I have found a lot of utility out of this link http://www.techonthenet.com/oracle/index.php for clear explanations of plSQL.

Using Group By Clause in Stored procedure

I have a storedprocedure in which iam getting InvoiceValue as one field.I have different invoice values corresponding to 1 fileid.I want to get the sum of invoice values corresponding to each fileid.How can i use group by here?
here is my stored procedure
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[rptGGM]
(
#FromDate varchar(50),
#ToDate varchar(50),
#PartyID int,
#WID int
)
As
DECLARE #WhereStr VarChar(800)
SET #FromDate = LTRIM(RTRIM(#FromDate))
SET #ToDate = LTRIM(RTRIM(#ToDate))
SET #WhereStr =
CASE #WID
WHEN 23 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+'''))'
WHEN 7 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+''')) AND A.WorkID='+LTRIM(str(#WID))
WHEN 6 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+''')) AND A.WorkID='+LTRIM(str(#WID))
WHEN 11 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+''')) AND A.WorkID='+LTRIM(str(#WID))
WHEN 12 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+''')) AND A.WorkID='+LTRIM(str(#WID))
END
BEGIN
exec
('SELECT
A.FileNumber As [File_No],
H.IDFNumber as [IDF No],
H.IDFRegNo as [TZDAR],
F.POString As [PO_Numbers],
B.PartyName As [Exporter Name],
F.SIString As [Supplier Invoices],
C.CargoDesc As [Cargo_Description],
dbo.PackCntDetails(A.FileID) As [Pk/Cnt_Details],
D.VesselName As [Vessel Name],
D.VoyageNo As [Voyage No],
L.Amount As [Invoice Value],
convert(varchar, Dbo.ActualDate(A.ETA), 103) + '' '' + convert(varchar, Dbo.ActualDate(A.ETA), 108) As ETA,
convert(varchar,Dbo.ActualDate(D.ATASea),103) + '' '' + convert(varchar, Dbo.ActualDate(D.ATASea), 108) As ATA,
convert(varchar,Dbo.ActualDate(H.PCVRIssuedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(H.PCVRIssuedDate), 108) as [PCVR Issued Date],
convert(varchar,Dbo.ActualDate(V.VATRelDate),103) + '' '' + convert(varchar, Dbo.ActualDate(V.VATRelDate), 108) as [VR Requested],
convert(varchar,Dbo.ActualDate(V.OriginalRecdDate),103) + '' '' + convert(varchar, Dbo.ActualDate(V.OriginalRecdDate), 108) as [VR Granted],
convert(varchar,Dbo.ActualDate(H.SBECVRAppReturnedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(H.SBECVRAppReturnedDate), 108) as [SBE _VR App. ReturnedDate],
convert(varchar,Dbo.ActualDate(H.SBECVRIssuedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(H.SBECVRIssuedDate), 108) as [SBE_CVR IssuedDate],
convert(varchar,Dbo.ActualDate(I.CDFLodgedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(I.CDFLodgedDate), 108) as [CDF LodgedDate],
convert(varchar,dbo.ActualDate(I.AssessmentPaidDate), 103) + '' '' + convert(varchar,dbo.ActualDate(I.AssessmentPaidDate),108) As [DutyPaidDate],
convert(varchar,Dbo.ActualDate(I.EntryLodgedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(I.EntryLodgedDate), 108) as [Entry LodgedDate],
convert(varchar,Dbo.ActualDate(I.EntryPassedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(I.EntryPassedDate), 108) as [Custom Released],
[Actual Days from ATA to CR]=DATEDIFF(dd, Dbo.ActualDate(D.ATASea),Dbo.ActualDate(I.EntryPassedDate)),
convert(varchar,Dbo.ActualDate(K.ShippingLineReleaseDate),103) + '' '' + convert(varchar, Dbo.ActualDate(K.ShippingLineReleaseDate),108) as [ShippingLine ReleaseDate],
convert(varchar,Dbo.ActualDate(K.PortInvoicePaidDate),103) + '' '' + convert(varchar, Dbo.ActualDate(K.PortInvoicePaidDate),108) as [Port_Charges Paid_Date],
convert(varchar,Dbo.ActualDate(K.RemPortYardDateSea),103) + '' '' + convert(varchar, Dbo.ActualDate(K.RemPortYardDateSea),108) as [Rem_Sea_Port to Yard_Date],
[Actual Days From CR to RFD Dar]=DATEDIFF(dd,Dbo.ActualDate(I.EntryPassedDate), Dbo.ActualDate(K.RemPortYardDateSea)),
[Total No: of Days(ATA-RFD)]=DATEDIFF(dd,Dbo.ActualDate(D.ATASea), Dbo.ActualDate(K.RemPortYardDateSea)),
A.Remarks As [File Status]
FROM
FileMain A
INNER JOIN Party G ON G.PartyID = A.PartyID
LEFT JOIN Party B ON B.PartyID = A.ExporterID
LEFT JOIN Cargo C ON C.FileID = A.FileID
LEFT JOIN FileSea D ON D.FileID = A.FileID
LEFT JOIN SIPOString F ON F.FileID=A.FileID
LEFT JOIN IDFMain H ON H.FileID=A.FileID
LEFT JOIN Customs I ON I.FileID=A.FileID
LEFT JOIN VATRelief V ON V.FileID=A.FileID
LEFT JOIN PortAirPortOperation K ON K.FileID=A.FileID
LEFT JOIN Invoice L ON L.FileID=A.FileID and L.Incoterm=''CIF''' +#WhereStr)
END
The quickest implementation here would be to not use a GROUP BY. I would instead use a SubQuery within your SELECT to perform the SUM of the invoices.
Remove the LEFT JOIN to Invoice and then relace the L.Amount line in the SELECT with a SubQuery as follows
(SELECT SUM(Amount) FROM Invoice WHERE Invoice.FileID = A.FileID and Invoice.Incoterm = 'CIF') [Invoice Value]
If you wish to use a GROUP BY to perform the SUM then you either need to GROUP on all your other columns you SELECT, or perform the GROUP by within a VIEW (probably nested).