Search code examples
sqlsql-serveruser-defined-types

MsSQL not passing user defined table type using sp_executesql


I'm trying to pass my User Defined Table Type to a store procedure (originaly using EF). However, I'm stuck, because it looks like sp_executesql passes the parametr to the stored procedure, but its empty. Check it out, here is the type:

CREATE TYPE [dbo].[BigIntList] AS TABLE(
    [Item] [bigint] NULL
)

Here is the stored procedure:

CREATE PROCEDURE [dbo].[MyProcedure]
    @bookEntryIds [dbo].[BigIntList] READONLY
AS
BEGIN
    SET NOCOUNT ON; 
    SELECT * FROM @bookEntryIds
END

And here is what bothers me:

DECLARE @bookEntryIds [dbo].[BigIntList]
INSERT INTO @bookEntryIds VALUES (50181)
INSERT INTO @bookEntryIds VALUES (40182)

-- 1. This returns 50181 and 40182
EXEC [dbo].[MyProcedure] @bookEntryIds

-- 2. This returns empty result with column "Item"
EXEC sp_executesql N'[dbo].[MyProcedure]', N'@bookEntryIds [dbo].[BigIntList] READONLY', @bookEntryIds

The second query is used by Entity Framework, so I need it to work. Could you please tell me what is wrong with it? I checked with several guides how to do this and I see nothing wrong here.

I tried changing the type to string (VARCHAR(100)), but the result was the same. I'm running it on SQL server 2016, but the same happens on dev (hosting) machine, where is 2014 version.

Thanks for help.

Martin

EDIT - Solution by @sepupic:

If you were inspired by Pass table value type to SQL Server stored procedure via Entity Framework like me, please, make sure you are passing the parameter (!), like:

context.Database.ExecuteSqlCommand("[dbo].[MyProcedure] @bookEntryIds", parameter);

Solution

  • -- 2. This returns empty result with column "Item"
    EXEC sp_executesql N'[dbo].[MyProcedure]', N'@bookEntryIds [dbo].[BigIntList] READONLY', @bookEntryIds
    

    The result is empty because you forgot to pass in the parameter, it should look like this:

    EXEC sp_executesql N'[dbo].[MyProcedure] @bookEntryIds = @bookEntryIds', N'@bookEntryIds [dbo].[BigIntList] READONLY', @bookEntryIds