gpt4 book ai didi

sql - 存储过程运行速度比查询慢很多

转载 作者:行者123 更新时间:2023-12-02 22:20:39 25 4
gpt4 key购买 nike

我有一个存储过程,它为优势比创建一个 2x2 表。基本的比值比表如下所示: enter image description here

编辑 - 这个查询终于完成了,它在两分钟和 32 次单独调用函数后返回了正确的答案。我不明白为什么这是递归运行,有什么想法吗?

A - only records that satisfy both thing 1 and thing 2 go here
B - only records that satisfy thing 1 (people with thing 2 CANNOT go here)
C - only records that satisfy thing 2 (people with thing 1 CANNOT go here)
D - people with thing 1 OR thing 2 cannot go here

表格中的所有单元格都是代表人口的整数。

我试图学习一些新的语法并决定使用intersectexcept。我想制作 thing 1thing 2 变量,所以我将以下查询放入存储过程中。

CREATE PROC Findoddsratio (@diag1 NVARCHAR(5), 
@diag2 NVARCHAR(5))
AS
IF Object_id('tempdb..#temp') IS NOT NULL
DROP TABLE #temp

CREATE TABLE #temp
(
squarenumber CHAR(1),
counts FLOAT
)

INSERT INTO #temp
(squarenumber,
counts)
SELECT *
FROM (
--both +
SELECT 'a' AS squareNumber,
Cast(Count(DISTINCT x.counts)AS FLOAT) AS counts
FROM (SELECT DISTINCT ic.patid AS counts
FROM icdclm AS ic
WHERE ic.icd LIKE @diag1
INTERSECT
SELECT DISTINCT ic.patid AS counts
FROM icdclm AS ic
WHERE ic.icd LIKE @diag2)x
UNION
--only 1+
SELECT 'b',
Count(DISTINCT x.counts)
FROM (SELECT DISTINCT ic.patid AS counts
FROM icdclm AS ic
WHERE ic.icd LIKE @diag1
EXCEPT
SELECT DISTINCT ic.patid AS counts
FROM icdclm AS ic
WHERE ic.icd LIKE @diag2)AS x
UNION
--only 2+
SELECT 'c',
Count(DISTINCT x.counts)
FROM (SELECT DISTINCT ic.patid AS counts
FROM icdclm AS ic
WHERE ic.icd LIKE @diag2
EXCEPT
SELECT DISTINCT ic.patid AS counts
FROM icdclm AS ic
WHERE ic.icd LIKE @diag1)AS x
UNION
--both -
SELECT 'd',
Count(DISTINCT x.counts)
FROM (SELECT DISTINCT ic.patid AS counts
FROM icdclm AS ic
EXCEPT
SELECT DISTINCT ic.patid AS counts
FROM icdclm AS ic
WHERE ic.icd LIKE @diag2
EXCEPT
SELECT DISTINCT ic.patid AS counts
FROM icdclm AS ic
WHERE ic.icd LIKE @diag1) AS x)y

--i used a pivot table to make the math work out easier
SELECT Round(Cast(( a * d ) / ( b * c ) AS FLOAT), 2) AS OddsRatio
FROM (SELECT [a],
[b],
[c],
[d]
FROM (SELECT [squarenumber],
[counts]
FROM #temp) p
PIVOT ( Sum(counts)
FOR [squarenumber] IN ([a],
[b],
[c],
[d]) ) AS pvt)t

ICDCLM 是一个结构类似于 patid=int, icd=varchar(5)

的表

ICDCLM 中有大约一百万行。当我运行此查询而不使其成为存储过程时,它会在几秒钟内运行。如果我尝试 exec FindsOddsRation 'thing1%','thing2%'。它运行并运行,但从不返回任何内容(> 2 分钟)。存储过程花费这么长时间可能有什么不同? SQL 服务器 2008 R2 fiddle here

最佳答案

如果您正在运行与存储过程完全相同的 SQL 并且时间不同,则您的存储过程可能依赖于过时的元数据。尝试更新统计信息或重新编译存储过程。

关于sql - 存储过程运行速度比查询慢很多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13750829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com