woo*_*gie 2 sql t-sql sql-server stored-procedures
我有一个存储过程,它为优势比创建一个2x2表.基本比值比表如下所示:

编辑 - 这个查询最终完成,它确实在两分钟后回复了正确的答案,并且对该函数进行了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
Run Code Online (Sandbox Code Playgroud)
表中的所有单元格都是代表一群人的整数.
我试图学习一些新的语法,并决定使用intersect和except.我想创建thing 1和thing 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
Run Code Online (Sandbox Code Playgroud)
ICDCLM 是一个像结构的表 patid=int, icd=varchar(5)
有大约一百万行ICDCLM.当我运行此查询而不使其成为存储过程时,它会在几秒钟内运行.如果我试着exec FindsOddsRation 'thing1%','thing2%'.它运行并运行,但从不返回任何东西(> 2分钟).存储过程花了这么长时间的差异是什么?SQL Server 2008 R2 在这里搞砸了