我是SQL新手,我正在尝试更新一个包含游标的存储过程。我之前从未见过光标。游标的select语句有一个内连接,但只返回一列ID。游标逐行计算每个ID的已删除帐户数。 在存储过程结束时,删除变量的数量将插入表
我希望有人能够更多地了解游标/ while循环能够建议将上述代码转换为基于有效集合的方法的最佳方法。
答案 0 :(得分:1)
这是一种基于集合的方式:
;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
您可以修改最后一个SELECT
,使其将这些值插入表格中。