SQL server stored procedure return a table

后端 未结 9 2226
情书的邮戳
情书的邮戳 2020-12-04 19:39

I have a stored procedure that takes in two parameters. I can execute it successfully in Server Management Studio. It shows me the results which are as I expect. However it

9条回答
  •  日久生厌
    2020-12-04 20:15

    I do this frequently using Table Types to ensure more consistency and simplify code. You can't technically return "a table", but you can return a result set and using INSERT INTO .. EXEC ... syntax, you can clearly call a PROC and store the results into a table type. In the following example I'm actually passing a table into a PROC along with another param I need to add logic, then I'm effectively "returning a table" and can then work with that as a table variable.

    /****** Check if my table type and/or proc exists and drop them ******/
    IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'returnTableTypeData')
    DROP PROCEDURE returnTableTypeData
    GO
    IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'myTableType')
    DROP TYPE myTableType
    GO
    
    /****** Create the type that I'll pass into the proc and return from it ******/
    CREATE TYPE [dbo].[myTableType] AS TABLE(
        [someInt] [int] NULL,
        [somenVarChar] [nvarchar](100) NULL
    )
    GO
    
    CREATE PROC returnTableTypeData
        @someInputInt INT,
        @myInputTable myTableType READONLY --Must be readonly because
    AS
    BEGIN
    
        --Return the subset of data consistent with the type
        SELECT
            *
        FROM
            @myInputTable
        WHERE
            someInt < @someInputInt
    
    END
    GO
    
    
    DECLARE @myInputTableOrig myTableType
    DECLARE @myUpdatedTable myTableType
    
    INSERT INTO @myInputTableOrig ( someInt,somenVarChar )
    VALUES ( 0, N'Value 0' ), ( 1, N'Value 1' ), ( 2, N'Value 2' )
    
    INSERT INTO @myUpdatedTable EXEC returnTableTypeData @someInputInt=1, @myInputTable=@myInputTableOrig
    
    SELECT * FROM @myUpdatedTable
    
    
    DROP PROCEDURE returnTableTypeData
    GO
    DROP TYPE myTableType
    GO
    

提交回复
热议问题