Search code examples
sql-serveruser-defined-types

top 1 row from User Defined Table Type


Is there a way to select top 1 row from 'User Defined Table Type' which is passed as a parameter to Stored Procedure?

CREATE TYPE t1 as TABLE
(
   id INT,
   name VARCHAR(100)
)

SP

CREATE STORED PROCEDURE sp1
(
    @type dbo.t1 as READONLY
)
BEGIN
   SELECT TOP 1 name FROM @type
END

Any Ideas?


Solution

  • Look at below working example, which give detail idea about how to CREATE/PASS/CALL user defined Table Type from SP.

    User Defined Table Type Creation Script:

    CREATE TYPE [dbo].[IdCenterIdList] AS TABLE(
        [Id] [varchar](36) NOT NULL,
        [CenterId] [varchar](36) NOT NULL
    )
    

    SP Creation:

    CREATE PROCEDURE TestType
        @IdCenterIdList AS IdCenterIdList ReadOnly
    AS
    BEGIN
        SELECT 
            TOP(1) * 
        FROM @IdCenterIdList
    END
    GO
    

    SP Execute Statement:

    DECLARE @tblTestType IdCenterIdList 
    
    INSERT INTO @tblTestType VALUES('11','1111')
    ,('22','222')
    ,('33','333')
    
    EXEC TestType @tblTestType
    

    Output:

    enter image description here