Converting a cursor/while loop into a set based approach - sql

I am very new to SQL and I am trying to update a stored procedure that has a cursor in it. I had never seen a cursor prior to this one. The cursor's select statement has an inner join, but returns only a single column of IDs. The cursor calculates the number of deleted accounts for every ID, on a row by row basis.
At the end of the stored procedure, the number of deletion variables are inserted into a table
I was hoping someone that understands more about cursors/while loops would be able to suggest the best way to convert the code above into an efficient set based approach.

This is a set based way:
;WITH IDS AS
(
SELECT DISTINCT c.p_id
FROM dbo.deletion_h dh
INNER JOIN dbo.Child c
ON dh.C_id = c.c_id
WHERE CONVERT(CHAR(25),dh.delete_date,101) = #ReportDate
AND c.isT = 1
AND c.p_id NOT IN (SELECT p_id FROM dbo.Parent WHERE support = 'Y')
), Data AS
(
SELECT p_id,
COUNT(*) ActiveChild,
SUM(CASE WHEN isT = 1 AND [level] <> 'H' THEN 1 ELSE 0 END) activePk8,
SUM(CASE WHEN isT = 1 AND [level] = 'H' THEN 1 ELSE 0 END) activeHS
FROM dbo.child c
WHERE [login] <> 'f'
AND EXISTS( SELECT 1 FROM IDS
WHERE p_id = c.p_id)
GROUP BY p_id
)
SELECT SUM(CASE WHEN ActiveChild > 0 THEN 1 ELSE 0 END) NumParentDeletions,
SUM(CASE WHEN activechildPk8 > 0 THEN 1 ELSE 0 END) NumDeletionsPk8,
SUM(CASE WHEN activeHS > 0 THEN 1 ELSE 0 END) NumDeletionsHS
FROM Data
You can modify the last SELECT to make it insert those values into your table.

Related

Oracle Stored Procedure not loading data as expected

In testing, I did the following (which worked):
create table testdata as select * from sometable;
create procedure testload as begin
delete from testdata;
insert into testdata select * from sometable;
end;
I've used the same structure for a more complex query. If I run "insert into testdata select [new query]", it will load the data into the table. However, when I created a new stored procedure using the new query, it will execute, but won't actually load data.
Note that this query was handed off to me, I didn't write it myself. The results have been validated, so while I appreciate any and all advice on how to clean up the code, I'm primarily interested in getting the stored procedure up and running with the code as close to what is below as possible.
select
CLAIM_ID
,INTERNAL_ID
,line
,VENDOR_GROUP
,case when (CLAIM_FORMAT_RULE+ POS_RULE + POS_TYPE_RULE+ POS_CODE_RULE+ MODIFIERS_RULE+ BILL_TYPE_RULE+ ATTENDING_PROV_RULE+ REFERRING_PROV_RULE) = 8 then 'Y' else 'N' end AUTH_FLAG
from
(
SELECT
AP.CLAIM_ID
,CLM1.INTERNAL_ID
, px.line
, DAT.VENDOR_GROUP
,MAX(CASE WHEN DAT.FORMAT_C IS NULL THEN 1 WHEN REPLACE(REPLACE(AP.CLAIM_FORMAT_C,1,'CMS'),2,'UB') = UPPER(DAT.FORMAT_C) THEN 1 else 0 END) AS CLAIM_FORMAT_RULE
,MAX(CASE WHEN DAT.POS_ID IS NULL THEN 1 WHEN EAF.INTERNAL_ID = DAT.POS_ID THEN 1 else 0 end ) AS POS_RULE
,MAX(CASE WHEN DAT.POS_TYPE_C IS NULL THEN 1 WHEN NVL(PX.POS_TYPE_C,0) NOT IN (20,23) THEN 1 WHEN CAST(PX.POS_TYPE_C AS VARCHAR(10)) = DAT.POS_TYPE_C THEN 1 else 0 END) AS POS_TYPE_RULE
,MAX(CASE WHEN DAT.PROC_CODE IS NULL THEN 1 WHEN DAT.PROC_CODE LIKE '%-%' AND EAP.PROC_CODE BETWEEN STRTOK(DAT.PROC_CODE,'-',1) AND STRTOK(DAT.PROC_CODE,'-',2) THEN 1 WHEN EAP.PROC_CODE = DAT.PROC_CODE THEN 1 else 0 END) AS POS_CODE_RULE
,MAX(CASE WHEN DAT.MODIFIER IS NULL THEN 1 WHEN DAT.MODIFIER = PX.MODIFIERS THEN 1 else 0 END) AS MODIFIERS_RULE
,MAX(CASE WHEN DAT.BILL_TYPE IS NULL THEN 1 WHEN DAT.BILL_TYPE LIKE '%-%' AND AP.TYPE_OF_BILL BETWEEN STRTOK(DAT.BILL_TYPE,'-',1) AND STRTOK(DAT.BILL_TYPE,'-',2) THEN 1 WHEN AP.TYPE_OF_BILL = DAT.BILL_TYPE THEN 1 else 0 END) AS BILL_TYPE_RULE
,MAX(CASE WHEN DAT.ATTENDING_PROV_NETWORK IS NULL THEN 1 WHEN DAT.ATTENDING_PROV_NETWORK = ALV.NET_AFFIL_LEVEL_C THEN 1 else 0 END) AS ATTENDING_PROV_RULE
,MAX(CASE WHEN DAT.REFERRING_PROV_NETWORK IS NULL THEN 1 WHEN DAT.REFERRING_PROV_NETWORK = RLV.NET_AFFIL_LEVEL_C THEN 1 else 0 END) AS REFERRING_PROV_RULE
FROM HCCLSC.AP_CLAIM AP
INNER JOIN HCCLSC.CLM_MAP CLM1 ON AP.CLAIM_ID=CLM1.CID --AND CLM1.INTERNAL_ID in ('363137412', '363149130')
INNER JOIN HCCLSC.CLARITY_VENDOR VEN ON AP.VENDOR_ID = VEN.VENDOR_ID
INNER JOIN HCCLSC.VENDOR_TAX_ID VTIN ON AP.VENDOR_ID = VTIN.VENDOR_ID
INNER JOIN KPBISC_GRP_NCAR.AUTH_EXCEPTIONS DAT ON VTIN.TAX_ID = DAT.VENDOR_TIN
LEFT JOIN HCCLSC.AP_CLAIM_PX PX ON AP.CLAIM_ID = PX.CLAIM_ID
LEFT JOIN HCCLSC.CLARITY_EAP EAP ON EAP.PROC_ID = PX.PROC_ID
LEFT JOIN HCCLSC.EAF_MAP EAF ON AP.LOC_ID = EAF.CID
LEFT JOIN HCCLSC.CLARITY_SER_NETAFF ALV ON AP.ATTEND_PROV_ID = ALV.PROV_ID AND ALV.LINE = 1
LEFT JOIN HCCLSC.CLARITY_SER_NETAFF RLV ON AP.REF_PROV_ID = RLV.PROV_ID AND ALV.LINE = 1
where
TRUNC(AP.DATE_RECEIVED) BETWEEN sysdate-60 AND sysdate and
COALESCE(AP.WORKFLOW_C,0)=0
and AP.STATUS_C in (2, 4, 3)
GROUP BY AP.CLAIM_ID,CLM1.INTERNAL_ID, px.line, DAT.VENDOR_GROUP
order by AP.CLAIM_ID , px.line
)
If it's not the commit problem mentioned in the other answer, try running the elect statement on it's own, but wrapping the whole statement in a select count(*) from (your_statement);
This will tell you if your query is returning zero rows.

Sum a column and perform more calculations on the result? [duplicate]

This question already has an answer here:
How to use an Alias in a Calculation for Another Field
(1 answer)
Closed 3 years ago.
In my query below I am counting occurrences in a table based on the Status column. I also want to perform calculations based on the counts I am returning. For example, let's say I want to add 100 to the Snoozed value... how do I do this? Below is what I thought would do it:
SELECT
pu.ID Id, pu.Name Name,
COUNT(*) LeadCount,
SUM(CASE WHEN Status = 'Working' THEN 1 ELSE 0 END) AS Working,
SUM(CASE WHEN Status = 'Uninterested' THEN 1 ELSE 0 END) AS Uninterested,
SUM(CASE WHEN Status = 'Converted' THEN 1 ELSE 0 END) AS Converted,
SUM(CASE WHEN SnoozedId > 0 THEN 1 ELSE 0 END) AS Snoozed,
Snoozed + 100 AS Test
FROM
Prospects p
INNER JOIN
ProspectsUsers pu on p.OwnerId = pu.SalesForceId
WHERE
p.Store = '108'
GROUP BY
pu.Name, pu.Id
ORDER BY
Name
I get this error:
Invalid column name 'Snoozed'.
How can I take the value of the previous SUM statement, add 100 to it, and return it as another column? What I was aiming for is an additional column labeled Test that has the Snooze count + 100.
You can't use one column to create another column in the same way that you are attempting. You have 2 options:
Do the full calculation (as #forpas has mentioned in the comments above)
Use a temp table or table variable to store the data, this way you can get the first 5 columns, and then you can add the last column or you can select from the temp table and do the last column calculations from there.
You can not use an alias as a column reference in the same query. The correct script is:
SELECT
pu.ID Id, pu.Name Name,
COUNT(*) LeadCount,
SUM(CASE WHEN Status = 'Working' THEN 1 ELSE 0 END) AS Working,
SUM(CASE WHEN Status = 'Uninterested' THEN 1 ELSE 0 END) AS Uninterested,
SUM(CASE WHEN Status = 'Converted' THEN 1 ELSE 0 END) AS Converted,
SUM(CASE WHEN SnoozedId > 0 THEN 1 ELSE 0 END)+100 AS Snoozed
FROM
Prospects p
INNER JOIN
ProspectsUsers pu on p.OwnerId = pu.SalesForceId
WHERE
p.Store = '108'
GROUP BY
pu.Name, pu.Id
ORDER BY
Name
MSSQL does not allow you to reference fields (or aliases) in the SELECT statement from within the same SELECT statement.
To work around this:
Use a CTE. Define the columns you want to select from in the CTE, and then select from them outside the CTE.
;WITH OurCte AS (
SELECT
5 + 5 - 3 AS OurInitialValue
)
SELECT
OurInitialValue / 2 AS OurFinalValue
FROM OurCte
Use a temp table. This is very similar in functionality to using a CTE, however, it does have different performance implications.
SELECT
5 + 5 - 3 AS OurInitialValue
INTO #OurTempTable
SELECT
OurInitialValue / 2 AS OurFinalValue
FROM #OurTempTable
Use a subquery. This tends to be more difficult to read than the above. I'm not certain what the advantage is to this - maybe someone in the comments can enlighten me.
SELECT
5 + 5 - 3 AS OurInitialValue
FROM (
SELECT
OurInitialValue / 2 AS OurFinalValue
) OurSubquery
Embed your calculations. opinion warning This is really sloppy, and not a great approach as you end up having to duplicate code, and can easily throw columns out-of-sync if you update the calculation in one location and not the other.
SELECT
5 + 5 - 3 AS OurInitialValue
, (5 + 5 - 3) / 2 AS OurFinalValue
You can't use a column alias in the same select. The column alias do not precedence / sequence; they are all created after the eval of the select result, just before group by and order by.
You must repeat code :
SELECT
pu.ID Id,pu.Name Name,
COUNT(*) LeadCount,
SUM(CASE WHEN Status = 'Working' THEN 1 ELSE 0 END) AS Working,
SUM(CASE WHEN Status = 'Uninterested' THEN 1 ELSE 0 END) AS Uninterested,
SUM(CASE WHEN Status = 'Converted' THEN 1 ELSE 0 END) AS Converted,
SUM(CASE WHEN SnoozedId > 0 THEN 1 ELSE 0 END) AS Snoozed,
SUM(CASE WHEN SnoozedId > 0 THEN 1 ELSE 0 END)+ 100 AS Test
FROM
Prospects p
INNER JOIN
ProspectsUsers pu on p.OwnerId = pu.SalesForceId
WHERE
p.Store = '108'
GROUP BY
pu.Name, pu.Id
ORDER BY
Name
If you don't want to repeat the code, use a subquery
SELECT
ID, Name, LeadCount, Working, Uninterested,Converted, Snoozed, Snoozed +100 AS test
FROM
(SELECT
pu.ID Id,pu.Name Name,
COUNT(*) LeadCount,
SUM(CASE WHEN Status = 'Working' THEN 1 ELSE 0 END) AS Working,
SUM(CASE WHEN Status = 'Uninterested' THEN 1 ELSE 0 END) AS Uninterested,
SUM(CASE WHEN Status = 'Converted' THEN 1 ELSE 0 END) AS Converted,
SUM(CASE WHEN SnoozedId > 0 THEN 1 ELSE 0 END) AS Snoozed
FROM Prospects p
INNER JOIN ProspectsUsers pu on p.OwnerId = pu.SalesForceId
WHERE p.Store = '108'
GROUP BY pu.Name, pu.Id) t
ORDER BY Name
or a view

SQL MAX value of two sub queries

I have two queries and I want to get the maximum value of the two of them.
MAX((SELECT COUNT(p.[ItemID]) FROM [dbo].[Table] p WHERE HasHuman=0),
(SELECT COUNT(p.[ItemID]) FROM [dbo].[Table] p WHERE HasHuman=1))
You can calculate both result in a single query and then apply TOP:
select top 1
HasHuman,
COUNT(p.[ItemID]) as cnt
from [dbo].[Table]
group by HasHuman
order by cnt desc
You could even do this in a single query:
SELECT
CASE WHEN SUM(CASE WHEN HasHuman=0 THEN 1 ELSE 0 END) >
SUM(CASE WHEN HasHuman=1 THEN 1 ELSE 0 END)
THEN SUM(CASE WHEN HasHuman=0 THEN 1 ELSE 0 END)
ELSE SUM(CASE WHEN HasHuman=1 THEN 1 ELSE 0 END) END
FROM [dbo].[Table]
WHERE ItemID IS NOT NULL -- you were not counting NULLs
SELECT MAX(RC)
FROM (SELECT COUNT(p.ItemID) AS RC FROM dbo.[Table]
WHERE HasHuman=0
UNION
SELECT COUNT(p.ItemID) AS RC FROM dbo.[Table]
WHERE HasHuman=1
) A

Count rows for two columns using two different clauses

I'm after a CTE which I want to return two columns, one with the total number of 1's and one with the total number of 0's. Currently I can get it to return one column with the total number of 1's using:
WITH getOnesAndZerosCTE
AS (
SELECT COUNT([message]) AS TotalNo1s
FROM dbo.post
WHERE dbo.checkletters([message]) = 1
--SELECT COUNT([message]) AS TotalNo0s
--FROM dbo.post
--WHERE dbo.checkletters([message]) = 0
)
SELECT * FROM getOnesAndZerosCTE;
How do I have a second column called TotalNo0s in the same CTE which I have commented in there to show what I mean.
Using conditional aggregation:
WITH getOnesAndZerosCTE AS(
SELECT
TotalNo1s = SUM(CASE WHEN dbo.checkletters([message]) = 1 THEN 1 ELSE 0 END),
TotalNo0s = SUM(CASE WHEN dbo.checkletters([message]) = 0 THEN 1 ELSE 0 END)
FROM post
)
SELECT * FROM getOnesAndZerosCTE;
For using COUNT() directly just be aware that it counts any NON-NULL values. You can omit the ELSE condition which implicitly returns NULL if not stated
SELECT
COUNT(CASE WHEN dbo.checkletters([message]) = 1 THEN 1 END) TotalNo1s
, COUNT(CASE WHEN dbo.checkletters([message]) = 0 THEN 1 END) TotalNo0s
FROM post
or, explicitly state NULL
SELECT
COUNT(CASE WHEN dbo.checkletters([message]) = 1 THEN 1 ELSE NULL END) TotalNo1s
, COUNT(CASE WHEN dbo.checkletters([message]) = 0 THEN 1 ELSE NULL END) TotalNo0s
FROM post
You can do it without CTE
select count(message) total,
dbo.checkletters(message) strLength
from post
group by dbo.checkletters(message)
having dbo.checkletters(message) in (1, 2) //All the messages with length 1 or 2

counting records on the same table with different values possibly none sql server 2008

I have a inventory table with a condition i.e. new, used, other, and i am query a small set of this data, and there is a possibility that all the record set contains only 1 or all the conditions. I tried using a case statement, but if one of the conditions isn't found nothing for that condition returned, and I need it to return 0
This is what I've tried so far:
select(
case
when new_used = 'N' then 'new'
when new_used = 'U' then 'used'
when new_used = 'O' then 'other'
end
)as conditions,
count(*) as count
from myDB
where something = something
group by(
case
when New_Used = 'N' then 'new'
when New_Used = 'U' then 'used'
when New_Used = 'O' then 'other'
end
)
This returns the data like:
conditions | count
------------------
new 10
used 45
I am trying to get the data to return like the following:
conditions | count
------------------
new | 10
used | 45
other | 0
Thanks in advance
;WITH constants(letter,word) AS
(
SELECT l,w FROM (VALUES('N','new'),('U','used'),('O','other')) AS x(l,w)
)
SELECT
conditions = c.word,
[count] = COUNT(x.new_used)
FROM constants AS c
LEFT OUTER JOIN dbo.myDB AS x
ON c.letter = x.new_used
AND something = something
GROUP BY c.word;
try this -
DECLARE #t TABLE (new_used CHAR(1))
INSERT INTO #t (new_used)
SELECT t = 'N'
UNION ALL
SELECT 'N'
UNION ALL
SELECT 'U'
SELECT conditions, ISNULL(r.cnt, 0) AS [count]
FROM (
VALUES('U', 'used'), ('N', 'new'), ('O', 'other')
) t(c, conditions)
LEFT JOIN (
SELECT new_used, COUNT(1) AS cnt
FROM #t
--WHERE something = something
GROUP BY new_used
) r ON r.new_used = t.c
in output -
new 2
used 1
other 0
You can do it as a cross-tab:
select
sum(case when new_used = 'N' then 1 else 0 end) as N,
sum(case when new_used = 'U' then 1 else 0 end) as U,
sum(case when new_used = 'O' then 1 else 0 end) as Other
from myDB
where something = something