简体   繁体   English

将表变量传递给存储过程

[英]Passing a table variable to a stored procedure

I am seeking to create a procedure that I can pass a one column table, and the procedure will output the median.我正在寻求创建一个可以传递单列表的过程,该过程将输出中位数。 Right now I have a procedure that will determine the median;现在我有一个确定中位数的程序; however, I am getting errors that my @table table variable has not been declared and that the stored procedure could not be found.但是,我收到错误,指出我的 @table 表变量尚未声明且无法找到存储过程。

My median procedure:我的中间程序:

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

Calling the procedure:调用程序:

DECLARE @Arsenic TABLE(Ar FLOAT)
INSERT INTO @Arsenic SELECT Arsenic from dbo.HubspotWaterTestAverages

EXEC dbo.median (SELECT Arsenic FROM dbo.HubspotWaterTestAverages)

NOTE: Arsenic represents the Arsenic level results from water tests, and the values range from null to 10注:Arsenic 代表水测试结果的砷含量,数值范围从零到 10

The working procedure is expected to just return the median value for the column, and later on I am planning on cross joining that to a master table.预计工作过程只会返回列的中值,稍后我计划将其交叉连接到主表。 Thank you for any help!感谢您的任何帮助!

This may help.这可能会有所帮助。 Except table variable have to use Table Type.除了表变量必须使用表类型。

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM