I am using SQL Sever 2016 and I have created user-defined table-type as below:
CREATE TYPE [dbo].[UDTT_Items] AS TABLE(
[ItemId] int identity(1, 1),
[ItemCode] [varchar](10) NULL,
[ItemName] [varchar](255) NULL,
[StockQty] decimal(18,3 ) NULL,
PRIMARY KEY CLUSTERED
(
[ItemId] ASC
)WITH (IGNORE_DUP_KEY = OFF)
)
GO
In my stored procedure I can create table variable like this:
declare @tblItems UDTT_Items
I can insert data in this table variable and can make select queries.
select * from @tblItems
The problem I faced when I need to put this table in dynamic sql. For example, if I try to run the above select statement from execute caluse:
EXECUTE SP_EXECUTESQL N'select * from @tblItems'
It gives me error message:
Must declare the table variable "@tblItems".
I tried to use temporary table variabe (with #) inside dynamic sql, and it works fine, but I dont know if I can create temporary table with already user-defined-table-type. I need something like this:
create #tblItems UDTT_Items
But it also does not work.
Can anybody suggest how to make any work around this issue, either by using table variable in dynamic sql, or creating temp table from user-defined-table-type?