我正在尝试创建一个可以传递一个列表的过程,该过程将输出中位数。现在,我有一个确定中值的程序;但是,我收到以下错误消息:我的@table表变量尚未声明,并且找不到存储过程。
我的中位手术程序:
CREATE OR ALTER PROCEDURE dbo.median
(@table NUMERIC,
@median FLOAT OUTPUT)
AS
DECLARE @size AS NUMERIC
SET @size = (SELECT COUNT(*) FROM @table)
SET @median = (SELECT AVG(1) FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY 1) AS ROW FROM @table) AS subquery
WHERE subquery.ROW = ROUND(@size / 2, 0) OR subquery.ROW = ROUND(@size / 2, 0, 1))
RETURN
GO
调用过程:
DECLARE @Arsenic TABLE(Ar FLOAT)
INSERT INTO @Arsenic SELECT Arsenic from dbo.HubspotWaterTestAverages
EXEC dbo.median (SELECT Arsenic FROM dbo.HubspotWaterTestAverages)
注意:砷表示水测试中的砷水平,值范围从零到10
预计该工作过程将仅返回该列的中间值,稍后我计划将其交叉连接到主表。谢谢您的帮助!
答案 0 :(得分:1)
这可能会有所帮助。除了表变量必须使用表类型。
CREATE TABLE Employee
(
EmpId int NOT NULL,
EmployeeName nvarchar(MAX),
)
GO
CREATE TYPE EmployeeType AS TABLE
(
EmpId int NOT NULL,
EmployeeName nvarchar(MAX)
)
GO
CREATE PROCEDURE PassTableTypeIntoProcedure(@EmployeeType EmployeeType READONLY)
AS
BEGIN
INSERT INTO Employee
SELECT * FROM @EmployeeType
END
GO
DECLARE @EmployeeTypeVariable AS EmployeeType
INSERT INTO @EmployeeTypeVariable VALUES
(1,'A'),
( 2,'B')
EXEC PassTableTypeIntoProcedure @EmployeeTypeVariable
GO
SELECT * FROM Employee