我有一个存储过程,如:
create procedure [dbo].[Mark]
SELECT
NAME, TOT1, TOT2, TOT3, (TOT1+TOT2+TOT3)/3 AS Average
FROM
(SELECT
NAME,
ISNULL([1],0) AS TOT1,
ISNULL([2],0) AS TOT2,
ISNULL([3],0) AS TOT3
FROM
(SELECT
ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY NAME) RN,
NAME,
TOT
FROM
T) S
PIVOT (MAX(TOT) FOR RN IN ([1],[2],[3])) AS PVT
) T
此存储过程的输出为:
name Tot1 Tot2 Tot3 Avg
-------------------------------
a 50 30 45 42
b 30 0 0 10
从这个存储过程中,我想创建另一个存储过程来记录20-50之间的平均值。如何获得?我尝试使用临时表。但我无法访问临时表到另一个存储过程
我的输出必须是
name Tot1 Tot2 Tot3 Avg
---------------------------------
a 50 30 45 42
答案 0 :(得分:2)
DECLARE @MyTableVar TABLE(
name VARCHAR(20),
Tot1 [decimal](15, 6),
Tot2 [decimal](15, 6),
Tot3 [decimal](15, 6),
Avg [decimal](15, 6))
INSERT INTO @MyTableVar EXECUTE sp_executesql [Mark]
SELECT * FROM @MyTableVar WHERE Avg BETWEEN 20 AND 50
只需将临时表@MyTableVar
替换为您需要的数据类型即可。我还没有对此进行测试,但我非常确定sp_executesql
正是您所寻找的。 p>
修改强> 为您更新数据类型。
答案 1 :(得分:0)
只需更新您的程序以接受可选参数:
ALTER PROCEDURE Mark
-- Add the parameters for the stored procedure here
@RANGE_START INT = NULL, @RANGE_END INT = NULL
AS
BEGIN
SELECT *
FROM (
SELECT
NAME, TOT1, TOT2, TOT3, (TOT1+TOT2+TOT3)/3 AS Average
FROM
(SELECT
NAME,
ISNULL([1],0) AS TOT1,
ISNULL([2],0) AS TOT2,
ISNULL([3],0) AS TOT3
FROM
(SELECT
ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY NAME) RN,
NAME,
TOT
FROM
T) S
PIVOT (MAX(TOT) FOR RN IN ([1],[2],[3])) AS PVT
) T
) R
WHERE (@RANGE_START IS NULL OR R.Average >= @RANGE_START)
AND( @RANGE_END IS NULL OR R.Average <= @RANGE_END)
END
GO
用法(新参数):
EXEC dbo.Mark 20, 41
<强>结果:强>
NAME TOT1 TOT2 TOT3 Average
a 50 30 45 41
用法(与之前相同):
EXEC dbo.Mark
<强>结果:强>
NAME TOT1 TOT2 TOT3 Average
a 50 30 45 41
b 30 0 0 10
如果你真的想创建一个新程序并使用Temp表,那么:
更新初始值
ALTER PROCEDURE Mark
-- Add the parameters for the stored procedure here
AS
BEGIN
SELECT
NAME, TOT1, TOT2, TOT3, (TOT1+TOT2+TOT3)/3 AS Average INTO ##TEMP
FROM
(SELECT
NAME,
ISNULL([1],0) AS TOT1,
ISNULL([2],0) AS TOT2,
ISNULL([3],0) AS TOT3
FROM
(SELECT
ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY NAME) RN,
NAME,
TOT
FROM
T) S
PIVOT (MAX(TOT) FOR RN IN ([1],[2],[3])) AS PVT
) T
SELECT * FROM ##TEMP
END
GO
创建新的
CREATE PROCEDURE Mark2
@RANGE_START INT = NULL, @RANGE_END INT = NULL
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
EXEC dbo.Mark
SELECT * FROM ##TEMP
WHERE Average BETWEEN @RANGE_START AND @RANGE_END
DROP TABLE ##TEMP
END
GO
<强>用法:强>
EXEC Mark2 20, 50
答案 2 :(得分:0)
最简单的处理方法是不使用存储过程。如果您改为创建表值函数,则可以轻松地针对它编写其他查询/存储过程。