My questions are gradually getting more and more difficult so clearly you are teaching me well!
In this one I have a report that prints details on card confirmorisations.
All fields fill fine except when I changed the confirm request to a "turnaround Request" the field that does not show up in this case in CTYlong which just remains blank for all instances for "turnaround Requests". This is for ssrs
I'll leave it to you!
IF #MsgType = 200
BEGIN
SELECT DISTINCT MsgType = 'confirm Request' , resp.dtTimeRPO as HostTime ,
resp.sSTANExternalI as STAN ,
resp.sterminal_TerminalID as TerminalID , resp.ssell_CardAcceptorIDCode as
sellID , resp.ssell_CardAcceptorNameLoc as sellName ,
STUFF(resp.span_Pan,7,(LEN(resp.span_Pan)-10), REPLICATE('X',(LEN(resp.span_Pan)-10)))
as PAN , CAST(MONTH(resp.dtpan_ExpiryDate) as varchar(2)) + '/' +
CAST(YEAR(resp.dtpan_ExpiryDate) as char(4)) as ExpDate , CAST(resp.namounts_cAmount
as float)/100 as Amount , resp.namounts_CurrencyCodetx as CurrencyCode ,
resp.nActionCode as RC , rc.rcInfo as RCDesc , resp.sconfirmCode as confirmCode ,
ssell_CountryShort2 AS sell_Country , ctylong ,
(SELECT DATEPART(ss, resp.dtTimeRPO - req.dtTimeRQI) FROM dbo.txHistory as
req (NOLOCK)
WHERE req.sSTANExternalI = resp.sSTANExternalI
AND
req.namounts_cAmount = resp.namounts_cAmount
AND req.dtLocalDateTime = resp.dtLocalDateTime
AND RTRIM(req.sPHProfile) = #Head
AND (req.sconfirmCode = ''
AND req.nActionCode = 0)
AND req.dtTimeRQI BETWEEN DATEADD(mi, -1, #StartDate)
AND #EndDate ) as Duration
FROM dbo.txHistory as resp (NOLOCK)
INNER JOIN dbo.replyCode as rc (NOLOCK)
ON resp.nActionCode = rc.rcCode
inner join country (nolock)
on nsell_countrycode = ctycode
WHERE resp.dtTimeRPO
BETWEEN #StartDate AND #EndDate
AND
resp.eMTI = #MsgType
AND
RTRIM(resp.sPHProfile) = #Head
AND NOT (resp.sconfirmCode = '' AND resp.nActionCode = 0)
ORDER BY resp.dtTimeRPO
END
ELSE
BEGIN
SELECT DISTINCT MsgType = 'turnaround Request' , resp.dtTimeRPO as HostTime ,
resp.sSTANExternalI as STAN , resp.sterminal_TerminalID as TerminalID ,
resp.ssell_CardAcceptorIDCode as sellID , resp.ssell_CardAcceptorNameLoc
as sellName , STUFF(resp.span_Pan,7,(LEN(resp.span_Pan)-10), REPLICATE('X',
(LEN(resp.span_Pan)-10))) as PAN , CAST(MONTH(resp.dtpan_ExpiryDate) as varchar(2)) +
'/' + CAST(YEAR(resp.dtpan_ExpiryDate) as char(4)) as ExpDate ,
CAST(resp.namounts_cAmount as float)/100 as Amount ,
resp.namounts_CurrencyCodetx as CurrencyCode , resp.nActionCode as RC ,
rc.rcInfo as RCDesc , resp.sconfirmCode as confirmCode ,
(SELECT DATEPART(ss, resp.dtTimeRPO - req.dtTimeRQI)
FROM dbo.txHistory as req (NOLOCK)
WHERE req.sSTANExternalI = resp.sSTANExternalI AND req.namounts_cAmount =
resp.namounts_cAmount AND req.dtLocalDateTime = resp.dtLocalDateTime
AND
RTRIM(req.sPHProfile) = #Head
AND
(req.eMTI = 420 AND req.nActionCode = 400)
AND
req.dtTimeRQI BETWEEN DATEADD(mi, -1, #StartDate) AND #EndDate )
as Duration
FROM dbo.txHistory as resp (NOLOCK)
INNER JOIN dbo.replyCode as rc (NOLOCK) ON resp.nActionCode = rc.rcCode WHERE
resp.dtTimeRPO
BETWEEN
#StartDate
AND #EndDate AND resp.eMTI = #MsgType
AND RTRIM(resp.sPHProfile) = #Head
ORDER BY resp.dtTimeRPO END
For Reversal Requests you are not including the ctylong field. Basically your columns don't line up in your two queries. You really should format your queries better as well, that was a nightmare to read.
edit: This is how I like to format my queries
SELECT
column1,
column2,
column3
FROM
table_1 INNER JOIN
table_2 ON table_1.id = table_2.id INNER JOIN
(
SELECT
column_4
FROM
table_3
) t3 ON table_2.id = t3.id
WHERE
table_1.id = 1000 AND
table_2.id = 2000
Related
Whenever I'm executing the procedure I got performance issue, where do I need to change the procedure to increase the performance?
I have called table function in where clause I need to optimize this procedure without using string.
CREATE PROC proc_productwise_report #cmp_id VARCHAR(max), #unitcode VARCHAR(max), #gr_code VARCHAR(max), #store_code VARCHAR(max), #from_dt VARCHAR(20), #to_dt VARCHAR(20)
AS
BEGIN
SELECT sh.cmp_id, d.unitcode, d.store_code, st.item_code AS product, d.item_code, im.item_desc, SUM(charge_qty) AS challan_qty
FROM ps_invenstatic sh
INNER JOIN ps_invenstaticdet st ON sh.cmp_id = st.cmp_id
AND sh.sys_no_id = st.sys_no_id
AND sh.doc_id = st.doc_id
AND sys_doc_type = 'PSCH'
INNER JOIN ps_invenissu h ON sh.cmp_id = h.cmp_id
AND sh.doc_type = h.ref_doc_type
AND sh.doc_no = h.ref_doc_no
AND h.prod_code = st.item_code
INNER JOIN ps_invenissudet d ON h.cmp_id = d.cmp_id
AND h.sys_no_id = d.sys_no_id
AND h.doc_id = d.doc_id
INNER JOIN ps_itemmas im ON sh.cmp_id = im.cmp_id
AND im.item_code = d.item_code
WHERE sh.cmp_id IN (
SELECT *
FROM utilfn_split(#cmp_id, ',')
)
AND d.unitcode IN (
SELECT *
FROM utilfn_split(#unitcode, ',')
)
AND im.gr_code IN (
SELECT *
FROM utilfn_split(#gr_code, ',')
)
AND d.store_code IN (
SELECT *
FROM utilfn_split(#store_code, ',')
)
AND h.doc_dt BETWEEN convert(DATETIME, #from_dt, 103)
AND convert(DATETIME, #to_dt, 103)
AND sh.Stat_Code <> 'CA'
GROUP BY sh.cmp_id, d.unitcode, d.store_code, st.item_code, d.item_code, im.item_desc
END
I need to avoid function in where clause and resolve the performance issue.
You can build temporary tables in your stored procedure with the result of the SPLIT and INNER JOIN those temporary tables in your main query.
CREATE PROC proc_productwise_report #cmp_id VARCHAR(max), #unitcode VARCHAR(max),
#gr_code VARCHAR(max), #store_code VARCHAR(max), #from_dt VARCHAR(20), #to_dt VARCHAR(20)
AS
BEGIN
SELECT *
INTO #cmp_ids
FROM utilfn_split(#cmp_id, ',');
SELECT *
INTO #unitcodes
FROM utilfn_split(#unitcode, ',');
SELECT *
INTO #gr_codes
FROM utilfn_split(#gr_code, ',');
SELECT *
INTO #store_codes
FROM utilfn_split(#store_code, ',');
SELECT
sh.cmp_id
, d.unitcode
, d.store_code
, st.item_code AS product
, d.item_code
, im.item_desc
, SUM(charge_qty) AS challan_qty
FROM ps_invenstatic sh
INNER JOIN ps_invenstaticdet st
ON sh.cmp_id = st.cmp_id
AND sh.sys_no_id = st.sys_no_id
AND sh.doc_id = st.doc_id
AND sys_doc_type = 'PSCH'
INNER JOIN ps_invenissu h
ON sh.cmp_id = h.cmp_id
AND sh.doc_type = h.ref_doc_type
AND sh.doc_no = h.ref_doc_no
AND h.prod_code = st.item_code
INNER JOIN ps_invenissudet d
ON h.cmp_id = d.cmp_id
AND h.sys_no_id = d.sys_no_id
AND h.doc_id = d.doc_id
INNER JOIN ps_itemmas im
ON sh.cmp_id = im.cmp_id
AND im.item_code = d.item_code
INNER JOIN #cmp_ids tci on sh.cmp_id = tci.[value]
INNER JOIN #unitcodes tuc on d.unitcode = tuc.[value]
INNER JOIN #gr_codes tgr on im.gr_code = tgr.[value]
INNER JOIN #store_codes tsc on d.store_code = tsc.[value]
WHERE h.doc_dt BETWEEN convert(DATETIME, #from_dt, 103)
AND convert(DATETIME, #to_dt, 103)
AND sh.Stat_Code <> 'CA'
GROUP BY sh.cmp_id
, d.unitcode
, d.store_code
, st.item_code
, d.item_code
, im.item_desc
END
Use table-valued parameters instead of CSV strings. Alternatively in your proc
create temp tables (table variables) first.
declare #tunitcode table (id int); -- you type may be different
insert #tunitcode(id)
select *
from utilfn_split(#unitcode, ',');
.. AND d.unitcode IN (
SELECT * FROM #tunitcode)
..
;WITH #SearchHistory (OrderDetail_ID, RelatedOrderDetail_ID, OrigOrderDetail_ID, TimesRolled) AS
(
SELECT od.OrderDetail_ID
,od.RelatedOrderDetail_ID
,0
,0
FROM #SearchFilter f1
INNER JOIN RLHistory.dbo.TRRawDetail od (NOLOCK)
ON od.ConfirmationNo LIKE f1.OrigConfirmationNo + '%'
AND od.ConfirmationNo <> f1.ConfirmationNo
AND od.ItemType_ID IN (14,27)
UNION ALL
SELECT od.OrderDetail_ID
,od.RelatedOrderDetail_ID
,0
,0
FROM #SearchFilter f1
INNER JOIN RueschLink.dbo.ClientOrder co (NOLOCK)
ON co.ConfirmationNo LIKE f1.OrigConfirmationNo + '%'
AND co.ConfirmationNo <> f1.ConfirmationNo
INNER JOIN RueschLink.dbo.OrderDetail od (NOLOCK)
ON od.ClientOrder_ID = co.ClientOrder_ID
AND od.ItemType_ID IN (14,27)
UNION ALL
SELECT od.OrderDetail_ID
,od.RelatedOrderDetail_ID
,CASE WHEN ISNULL(f2.RelatedOrderDetail_ID, 0) = 0 THEN f2.OrderDetail_ID ELSE f2.OrigOrderDetail_ID END
,f2.TimesRolled + 1 - (CASE WHEN ItemType_ID IN (14,27) THEN 0 ELSE 1 END)
FROM #SearchHistory AS f2
INNER JOIN RueschLink.dbo.OrderDetail od (NOLOCK)
ON od.RelatedOrderDetail_ID = f2.OrderDetail_ID
AND od.ItemType_ID IN (14,27,82,83)
UNION ALL
SELECT od.OrderDetail_ID
,od.RelatedOrderDetail_ID
,CASE WHEN ISNULL(f2.RelatedOrderDetail_ID, 0) = 0 THEN f2.OrderDetail_ID ELSE f2.OrigOrderDetail_ID END
,f2.TimesRolled + 1 - (CASE WHEN ItemType_ID IN (14,27) THEN 0 ELSE 1 END)
FROM #SearchHistory AS f2
INNER JOIN RLHistory.dbo.TRRawDetail od (NOLOCK)
ON od.RelatedOrderDetail_ID = f2.OrderDetail_ID
AND od.ItemType_ID IN (14,27,82,83)
)
-- create the report list and use it to collect more details
INSERT INTO #ReportList
(OrderDetail_ID
,RelatedOrderDetail_ID
,OrigOrderDetail_ID
,ConfirmationNo
,OrigConfirmationNo
,TimesRolled
,Reissue)
SELECT f1.OrderDetail_ID
,f1.RelatedOrderDetail_ID
,MAX(f2.OrigOrderDetail_ID)
,f1.ConfirmationNo
,f1.OrigConfirmationNo
,ISNULL(MAX(f2.TimesRolled), 0)
,CASE WHEN ISNULL(MAX(f2.TimesRolled), 0) > 0 THEN 'Y' ELSE 'N' END
FROM #SearchFilter f1
LEFT JOIN #SearchHistory f2
ON f1.OrderDetail_ID = f2.OrderDetail_ID
GROUP BY f1.ConfirmationNo, f1.OrigConfirmationNo, f1.OrderDetail_ID, f1.RelatedOrderDetail_ID
ORDER BY f1.ConfirmationNo
CREATE TABLE #ReportDetails
(
ClientOrder_ID INT
,ConfirmationNo VARCHAR(17)
,ConfirmationNo1 VARCHAR(100)
,OrigConfirmationNo VARCHAR(17)
,ClientName VARCHAR(90)
,Account VARCHAR(100)
,CurrencyCode VARCHAR(17)
,Amount VARCHAR(30)
,SettlementCurrencyCode VARCHAR(17)
,SettlementAmount VARCHAR(30)
,ItemRate VARCHAR(15)
,NewValueDate DATE
,OrigValueDate DATE
,OrderDate DATE
,OrderType VARCHAR(100)
,BeneficiaryName VARCHAR(140)
,OrderSource VARCHAR(100)
,Enteredby VARCHAR(100)
,Reissue VARCHAR(3) DEFAULT 'N'
,TimesRolled INT
,NumberofDaysRolled INT
,Trader VARCHAR(90)
,Trader_ID INT
,Comment VARCHAR(100)
,OrderDetail_ID INT
,WeightedAverage CHAR(1) DEFAULT ''
,OrigOrderDetail_ID INT
,OptionID Varchar(100)
,OriginalAmount VARCHAR(30)
,NewCloseDate Date
,CompletedTenor varchar(30)
,OriginalBookingDate Date
)
--start building the report
INSERT INTO #ReportDetails
(ClientOrder_ID
,ConfirmationNo
,ConfirmationNo1
,OrigConfirmationNo
,ClientName
,Account
,CurrencyCode
,Amount
,SettlementCurrencyCode
,SettlementAmount
,ItemRate
,NewValueDate
,OrderDate
,OrderType
,BeneficiaryName
,OrderSource
,Enteredby
,Reissue
,TimesRolled
,Trader_ID
,Comment
,OrderDetail_ID
,OrigOrderDetail_ID
,OptionID
,OriginalAmount
,NewCloseDate
,CompletedTenor
,OriginalBookingDate)
SELECT
od.ClientOrder_ID
,rl.ConfirmationNo
,('6' + ',' + ltrim(rtrim(Str(ISNULL(od.OrderDetail_ID, 0)))) + ',' + ltrim(rtrim(Str(ISNULL(od.ClientOrder_ID, 0)))) + ',' + ltrim(rtrim(od.ConfirmationNo)) + ',%' + ltrim(rtrim(od.ItemNo))) --link confirmation no
,rl.OrigConfirmationNo
,c.DESCRIPTION -- ClientName
,UPPER(co.Account) -- Account
,od.CurrencyCode -- CurrencyCode
,LTRIM(STR(od.ForeignAmount, 30, ISNULL(od.ForeignAmt_NDec, 2)))-- Amount
,co.Settlement_SWIFT-- SettlementCurrencyCode
,LTRIM(STR(od.Extension, 30, ISNULL(co.SettlementAmt_NDec, 2))) --Settlement Amount
,LTRIM(STR(od.ItemRate, 15, ISNULL(od.ItemRate_NDec, 2))) -- ItemRate
,COALESCE(trdvd.RequestedValueDate, od.ReleaseDate) -- NewValueDate
,co.Ordered -- OrderDate
,ot.DESCRIPTION -- OrderType
,od.BeneName -- BeneficiaryName
,COALESCE(a.Description, a2.Description, #RepoOrderSource) -- OrderSource
,co.UserName -- Enteredby
,rl.Reissue
,rl.TimesRolled
,COALESCE(qh.updid, qh.User_ID, qh.initid, q.updid, q.User_ID, q.initid, co.initid) -- Trader_ID
,rsr.Instructions
,CASE WHEN od.FundedBy = #FundedByMultiple THEN od.OrderDetail_ID ELSE 0 END
,rl.OrigOrderDetail_ID
,(CASE WHEN co.ordertype_id in (6,45,5,11) THEN odOrg.OptionContractId ELSE NULL END) --new column added for PBR-1192
,(CASE WHEN co.ordertype_id in (6,45,5,11) THEN LTRIM(STR(odOrg.ForeignAmount, 30, ISNULL(odOrg.ForeignAmt_NDec, 2))) ELSE NULL END)--new column added for PBR-1192
,(CASE WHEN co.ordertype_id in (6,45,5,11) THEN od.ReleaseDate + od.WindowLength ELSE null END) --new column added for PBR-1192
,(CASE WHEN co.ordertype_id in (6,45,5,11) THEN DateDiff(day,coOrg.Ordered,(od.ReleaseDate + isnull(od.WindowLength,0))) ELSE NULL END) --new column added for PBR-1192
,(CASE WHEN co.ordertype_id in (6,45,5,11) THEN coOrg.Ordered ELSE NULL END) --new column added for PBR-1192
FROM #ReportList rl
INNER JOIN RLHistory.dbo.TRRawDetail od (NOLOCK) ON rl.OrderDetail_ID = od.OrderDetail_ID
INNER JOIN RLHistory.dbo.TRRawHeader co (NOLOCK) ON co.ClientOrder_ID = od.ClientOrder_ID
INNER JOIN RueschLink.dbo.Client AS c (NOLOCK) ON co.Client_ID = c.Client_ID
INNER JOIN RueschLink.dbo.OrderType AS ot (NOLOCK) ON co.OrderType_ID = ot.OrderType_ID
LEFT OUTER JOIN RueschLink.dbo.Application AS a (NOLOCK) ON (co.Application_ID = a.Application_ID AND a.Application_ID = 3)-- a.Description = #FwdOrderSource)
LEFT OUTER JOIN VMaRS.dbo.RSRepurchase AS rsr (NOLOCK) ON rsr.ClientOrder_ID = od.ClientOrder_ID
LEFT OUTER JOIN RueschLink.dbo.Application AS a2 (NOLOCK) ON a2.Application_ID = rsr.ApplicationID
LEFT OUTER JOIN crs..Quote q (NOLOCK) ON od.Quote_ID = q.Quote_ID
LEFT OUTER JOIN crs..QuoteHistory qh (NOLOCK) ON od.Quote_ID = qh.Quote_ID
LEFT OUTER JOIN RLHistory.dbo.TRRawDetailValueDate AS trdvd (NOLOCK) ON od.OrderDetail_ID = trdvd.OrderDetail_ID
LEFT JOIN RLHistory.dbo.TRRawDetail odOrg (NOLOCK) ON odOrg.OrderDetail_ID=RueschLink.dbo.ReturnParentOrderDetailID (od.RelatedOrderDetail_ID) --Join Added for PBR-1192
AND od.RelatedOrderDetail_ID>0 AND od.RelatedOrderDetail_ID IS NOT NULL
LEFT JOIN RLHistory.dbo.TRRawHeader coOrg (NOLOCK) ON coOrg.ClientOrder_ID = odOrg.ClientOrder_ID --Join Added for PBR-1192
ORDER BY co.ConfirmationNo --order the confirmation number asc
I have a query that is using a LEFT OUTER JOIN to merge 2 data sets. I know both data sets should return data because I ran the superquery and the subquery separately. For some reason, the query is returning zero results. Anyone know why?
Left data:
item FG_lots
447845 E2211
Right data:
candy_lot_check candy_item
L2211 835116
Intended result:
item FG_lots candy_lot_check candy_item
447845 E2211 null null
The result from my broken query (no results):
item FG_lots candy_lot_check candy_item
The query:
--Initialization--
DECLARE #Item NVARCHAR(30) = '447845'
DECLARE #Date datetime = '6/13/2016'
SET DATEFIRST 1;
DECLARE #client NVARCHAR(20)
SET #client = (SELECT i.Uf_ClientName FROM item AS i WHERE i.item = #Item)
DECLARE #count integer
--Query--
SET #count = (CASE
WHEN (#client = 'A' OR #client = 'B')
THEN 4
WHEN #client = 'C'
THEN 3
WHEN #client = 'D'
THEN 5
ELSE
4
END)
SELECT DISTINCT
t.item,
LEFT(t.lot,#count) AS FG_lots,
(CASE
WHEN candylot.candy_lots IS NULL
THEN 'NO MATCH'
ELSE candylot.candy_lots
END) AS candy_lot_check,
(CASE
WHEN candylot.item IS NULL
THEN 'NO MATCH'
ELSE candylot.item
END) AS candy_item
FROM
ISW_LPTrans AS t
LEFT OUTER JOIN
(
SELECT
t.item,
LEFT(t.lot,#count) AS candy_lots,
t.ref_num AS job,
t.ref_line_suf AS suffix
FROM
ISW_LPTrans AS t
INNER JOIN item AS i on i.item = t.item
WHERE
i.product_code = 'RM-Candy' AND
t.trans_date = #Date AND
t.trans_type = 'I' AND
t.ref_num IN
(
SELECT TOP 1
j.job
FROM
job AS j
WHERE
j.item = #Item AND
j.job_date = (SELECT DATEADD(DAY, 1-DATEPART(WEEKDAY, #Date), #Date))
ORDER BY
j.job
)
AND t.ref_line_suf IN
(
SELECT TOP 1
j.suffix
FROM
job AS j
WHERE
j.item = #Item AND
j.job_date = (SELECT DATEADD(DAY, 1-DATEPART(WEEKDAY, #Date), #Date))
)
GROUP BY
t.item,
t.lot,
t.ref_num,
t.ref_line_suf
) AS candylot ON LEFT(t.lot, #count) = candylot.candy_lots
WHERE
t.ref_num = candylot.job AND
t.ref_line_suf = candylot.suffix AND
t.trans_type = 'F' AND
t.item = #Item AND
t.trans_date = #Date
You've got two 't' aliases, try altering it.
It seems you could rewrite it to make it more readable (joinwise, not indentwise), it could be that something's not right in the logic as well
This question already has an answer here:
Drop temp table within IF ELSE statement
(1 answer)
Closed 7 years ago.
I have the following stored procedure, But seems like the #Temp table is creating troubles in it. I get following error
There is already an object named '#Temp' in the database.
I guess somethings wrong with my IF ELSE
Here is the stored procedure:
create procedure spGetHOSalesReport
#DateFrom datetime,#DateTo datetime,#EmbossLine varchar(20),#CountryID int,#status char(2)
AS
Set #DateTo = #DateTo +1
if(#status = 'E1')
begin
Select PT.[ID] 'TransactionID', PT.BatchNumber, PT.SequenceNumber, PT.TransactionDate,
PT.TerminalID, PT.TotalAmount, PT.TransactionTypeID, TT.TransactionType,PT.PAN 'EmbossLine',PT.PreBalanceAmount, PT.PostBalanceAmount, RefTxnID, SettlementDate,PaidCash, CreditAmount, DiscountAmount,
RefPAN, PT.Remarks, ' ' + CashierCard as 'SupervisorCard',St.StoreID
into #Temp
from TempPOS_Transactions PT inner join TransactionType TT on TT.TransactionTypeID = PT.TransactionTypeID
inner join Staff St on St.CardNumber=PT.CashierCard
where
PT.[ID] not in (Select distinct isnull(TransactionID,0) from Testcards)
and (PT.TransactionDate >= #DateFrom) and (PT.TransactionDate < #DateTo)
and (PT.TransactionTypeID = 6) and (PT.BatchNumber = 0) and (Pt.SequenceNumber =-1)
select T.*, ' '+ C.EmbossLine+' ' as 'EmbossLine', C.EmbossLine as 'EmbossLine1',
isnull(C.FirstName,'') +' '+ isnull(C.LastName,'') 'EmbossName',C.FirstName,C.LastName,City.CityName,Country.CountryName,Country.CurrencyName, PM.MerchantID, PM.MerchantName1, C.AccountNumber, C.VehicleNumber, C.ExpiryDate ,
case C.Status when 'E0' then 'Authorized' when 'E1' then 'Pending' end 'Status'
from #Temp T
inner join Card C on C.EmbossLine= T.EmbossLine
inner join Terminal on Terminal.TerminalID = T.TerminalID
inner join Merchant PM on PM.MerchantID = Terminal.MerchantID
inner join City on City.CityID = PM.CityID
inner join Country on Country.CountryID = PM.CountryID
where C.Status <>'E3'
and C.CardID not in (Select distinct isnull(CardID,0) from Testcards)
and (C.EmbossLine like '%'+#EmbossLine+'%' or #EmbossLine like '-999')
and (PM.CountryID = #CountryID or #CountryID ='-999')
and (C.Status = #status)
order by T.TransactionDate, MerchantName1, T.BatchNumber, T.SequenceNumber
End
Else
Begin
Select PT.[ID] 'TransactionID', PT.BatchNumber, PT.SequenceNumber, PT.TransactionDate,
PT.TerminalID, PT.TotalAmount, PT.TransactionTypeID, TT.TransactionType,PT.PAN 'EmbossLine',PT.PreBalanceAmount, PT.PostBalanceAmount, RefTxnID, SettlementDate,PaidCash, CreditAmount, DiscountAmount,
RefPAN, PT.Remarks, ' ' + CashierCard as 'SupervisorCard',St.StoreID
into #Temp
from POS_Transactions PT inner join TransactionType TT on TT.TransactionTypeID = PT.TransactionTypeID
inner join Staff St on St.CardNumber=PT.CashierCard
where PT.[ID] not in (Select distinct isnull(TransactionID,0) from Testcards) and (PT.TransactionDate >= #DateFrom) and (PT.TransactionDate < #DateTo)
and (PT.TransactionTypeID = 6) and (PT.BatchNumber = 0) and (Pt.SequenceNumber =-1)
select T.*, ' '+ C.EmbossLine+' ' as 'EmbossLine', C.EmbossLine as 'EmbossLine1',
isnull(C.FirstName,'') +' '+ isnull(C.LastName,'') 'EmbossName',C.FirstName,C.LastName,City.CityName,Country.CountryName,Country.CurrencyName, PM.MerchantID, PM.MerchantName1, C.AccountNumber, C.VehicleNumber, C.ExpiryDate ,
case C.Status when 'E0' then 'Authorized' when 'E1' then 'Pending' end 'Status'
from #Temp T
inner join Card C on C.EmbossLine= T.EmbossLine
inner join Terminal on Terminal.TerminalID = T.TerminalID
inner join Merchant PM on PM.MerchantID = Terminal.MerchantID
inner join City on City.CityID = PM.CityID
inner join Country on Country.CountryID = PM.CountryID
where C.Status <>'E3'
and C.CardID not in (Select distinct isnull(CardID,0) from Testcards)
and (C.EmbossLine like '%'+#EmbossLine+'%' or #EmbossLine like '-999')
and (PM.CountryID = #CountryID or #CountryID ='-999')
and (C.Status = #status)
order by T.TransactionDate, MerchantName1, T.BatchNumber, T.SequenceNumber
End
drop table #Temp
You cannot have two statements in the same procedure that creates a temp table with the same name. This is a leftover from SQL 6.5 which did not have deferred name resolution.
And in any case, it only makes sense if the tables are created exactly the same, else your procedure will behave very funky.
So instead of using SELECT INTO, use CREATE TABLE + INSERT.
UPDATE
According to the selected way from comment:
Second option: First create temp table and insert
First let's create the temp table. For that you should modify your procedure like:
create procedure spGetHOSalesReport
#DateFrom datetime,#DateTo datetime,#EmbossLine varchar(20),#CountryID int,#status char(2)
AS
BEGIN -- begin procedure
SET #DateTo = #DateTo +1
if object_id('tempdb..#Temp') is not null drop table #Temp
create table #Temp
( TransactionID int
, BatchNumber ... ( your type of field )
, SequenceNumber ...
, TransactionDate ...
, TerminalID int
, TotalAmount ...
, TransactionTypeID int
, TransactionType ...
, EmbossLine ...
, PreBalanceAmount ...
, PostBalanceAmount ...
, RefTxnID int
, SettlementDate ...
, PaidCash ...
, CreditAmount ...
, DiscountAmount ...
, RefPAN ...
, Remarks ...
, SupervisorCard ...
, StoreID int
)
if(#status = 'E1')
.......
I do not know which data type has these fields, so, you have to do yourself. Then edit insert into temp table in first case and similar in another case:
insert into #Temp
Select PT.[ID] 'TransactionID', PT.BatchNumber, PT.SequenceNumber, PT.TransactionDate,
PT.TerminalID, PT.TotalAmount, PT.TransactionTypeID, TT.TransactionType,PT.PAN 'EmbossLine',PT.PreBalanceAmount, PT.PostBalanceAmount, RefTxnID, SettlementDate,PaidCash, CreditAmount, DiscountAmount,
RefPAN, PT.Remarks, ' ' + CashierCard as 'SupervisorCard',St.StoreID
from TempPOS_Transactions PT inner join TransactionType TT on TT.TransactionTypeID = PT.TransactionTypeID
inner join Staff St on St.CardNumber=PT.CashierCard
where ...
In the end of procedure you can add:
End -- end of your if
if object_id('tempdb..#Temp') is not null drop table #Temp
END -- end of procedure
But the simplest way is create two different temp tables:
if(#status = 'E1')
begin
if object_id('tempdb..#Temp1') is not null drop table #Temp1
Select PT.[ID] 'TransactionID', PT.BatchNumber, ...
into #Temp1
from TempPOS_Transactions PT
inner join TransactionType TT on TT.TransactionTypeID = PT.TransactionTypeID
.....
end
else
begin
if object_id('tempdb..#Temp2') is not null drop table #Temp2
Select PT.[ID] 'TransactionID', PT.BatchNumber, ...
into #Temp2
from POS_Transactions PT
inner join TransactionType TT on TT.TransactionTypeID = PT.TransactionTypeID
....
end
Also, you can write just two select without creating temp table in this case
First and foremost, the SQL is handled dynamically by the server, therefore some items in my WHERE clause may look odd to you, please disregard these as they are not an issue.
Per my clients request, they needed to UNION in two other conditions to my update report (/Patients without a Patient Visit/) and (/Patients without a Appointment/). I need help adding in the patients of these two subsets into my final update query. In its present state, it's only adding in the #Temp patients and I need to incorporate the additional patients.
Any help is GREATLY appreciated.
My current SQL update -
DECLARE #Inactive INT
DECLARE #Active INT
DECLARE #PatientProfileId INT
SELECT
#Inactive = MedlistsId
FROM
Medlists
WHERE
TableName = 'PatientProfileStatus'
AND Code = 'I'
SELECT
#Active = MedlistsId
FROM
Medlists
WHERE
TableName = 'PatientProfileStatus'
AND Code = 'A'
CREATE TABLE #Temp
(
PatientName VARCHAR(120) ,
PatientProfileId INT ,
RecentId INT ,
Recent DATETIME
)
INSERT INTO #Temp
SELECT
dbo.FormatName(pp.Prefix , pp.First , pp.Middle , pp.Last , pp.Suffix) AS Name ,
pp.PatientProfileId ,
MAX(pv.PatientVisitId) AS RecentId ,
MAX(pv.Visit) AS Recent
FROM
PatientVisit pv
INNER JOIN PatientProfile pp ON pv.PatientProfileId = pp.PatientProfileId
AND pp.PatientStatusMId = #Active
WHERE
pp.PatientProfileId IN ( SELECT
a.OwnerId
FROM
Appointments a
INNER JOIN PatientProfile pp ON a.OwnerId = pp.PatientProfileId
AND a.ApptKind = 1
AND pp.PatientStatusMId = #Active
GROUP BY
a.OwnerId ,
a.ApptKind
HAVING
MAX(a.ApptStart) < '07/30/2005' )
GROUP BY
dbo.FormatName(pp.Prefix , pp.First , pp.Middle , pp.Last , pp.Suffix) ,
pp.PatientProfileId
HAVING
MAX(pv.Visit) < '07/30/2005'
/*Patients without a Appointment*/
IF 1 = 1
INSERT INTO #Temp
SELECT
dbo.FormatName(pp.Prefix , pp.First , pp.Middle , pp.Last , pp.Suffix) AS Name ,
pp.PatientProfileId ,
NULL AS RecentId ,
NULL AS Recent
FROM
PatientProfile pp
LEFT JOIN ( SELECT * FROM Medlists WHERE TableName = 'PatientProfileStatus' ) ml1 ON pp.PatientStatusMId = ml1.MedlistsId
LEFT JOIN Appointments a ON a.Ownerid = pp.PatientProfileId
AND a.ApptKind = 1
LEFT JOIN PatientVisit pv ON a.PatientVisitId = pv.PatientVisitId
WHERE
ml1.Code = 'A'
AND a.ownerid IS NULL
AND --Filter on Age
(
((
'-1' = '-1'
AND '40' = '125'
)
OR ( CAST(( DATEDIFF(DAY , pp.Birthdate , GETDATE()) / 365.25 ) AS INT) BETWEEN ( '-1' ) AND ( '40' ) ))
)
/*Patients without a Patient Visit*/
IF 0 = 1
INSERT INTO #Temp
SELECT
dbo.FormatName(pp.Prefix , pp.First , pp.Middle , pp.Last , pp.Suffix) AS Name ,
pp.PatientProfileId ,
NULL AS RecentId ,
NULL AS Recent
FROM
PatientProfile pp
LEFT JOIN PatientVisit pv ON pv.PatientProfileid = pp.PatientProfileid
LEFT JOIN ( SELECT * FROM Medlists WHERE TableName = 'PatientProfileStatus' ) ml1 ON pp.PatientStatusMId = ml1.MedlistsId
WHERE
ml1.Code = 'A'
AND pv.patientprofileid IS NULL
AND --Filter on Age
(
((
'-1' = '-1'
AND '40' = '125'
)
OR ( CAST(( DATEDIFF(DAY , pp.Birthdate , GETDATE()) / 365.25 ) AS INT) BETWEEN ( '-1' ) AND ( '40' ) ))
)
DECLARE curPatient CURSOR FORWARD_ONLY READ_ONLY LOCAL
FOR
SELECT
t.PatientProfileId
FROM
#Temp t
JOIN PatientProfile pp ON t.PatientProfileId = pp.PatientProfileId
JOIN PatientVisit pv ON pp.PatientProfileId = pv.PatientProfileId
AND pv.PatientVisitId = t.RecentId
WHERE
--Filter on Age
(
((
'-1' = '-1'
AND '40' = '125'
)
OR ( CAST(( DATEDIFF(DAY , pp.Birthdate , GETDATE()) / 365.25 ) AS INT) BETWEEN ( '-1' ) AND ( '40' ) ))
)
OPEN curPatient
FETCH NEXT FROM curPatient INTO #PatientProfileId
WHILE ##FETCH_STATUS = 0
BEGIN
UPDATE
PatientProfile
SET
PatientStatusMId = #Inactive ,
pstatus = 'I'
FROM
PatientProfile P
INNER JOIN #Temp t ON t.PatientProfileID = P.PatientProfileID
WHERE
p.PatientProfileId = #PatientProfileId
FETCH NEXT FROM curPatient INTO #PatientProfileId
END
CLOSE curPatient
DEALLOCATE curPatient
DROP TABLE #Temp
This will limit to patients WITH an appointment
LEFT JOIN Appointments a
ON a.Ownerid = pp.PatientProfileId
AND a.ApptKind = 1
This will limit to patients WITH a Visit
LEFT JOIN PatientVisit pv
ON pv.PatientProfileid = pp.PatientProfileid
Try
LEFT OUTER JOIN Appointments a
ON a.Ownerid = pp.PatientProfileId
AND a.ApptKind = 1
Where a.Ownerid is null
LEFT OUTER JOIN PatientVisit pv
ON pv.PatientProfileid = pp.PatientProfileid
Where pv.PatientProfileid is null