I need to create a user defined type in dynamic way but
The exec()
way:
-- This works
DECLARE @column NVARCHAR(MAX) = 'Id INT'
EXEC ('CREATE TYPE dbo.MyDataType AS TABLE ('+ @column +')')
The sp_executesql
way:
-- This does not work
DECLARE @column NVARCHAR(MAX) = 'Id INT'
EXECUTE sp_executesql N'CREATE TYPE dbo.MyDataType AS TABLE ( @column )', @column;
Error:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'Id'.Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '@column'.
What am I missing ?
You need to use dynamic SQL even when taking the
sp_executesql
approach:You can pass parameter definitions and values into
sp_executesql
, like this:(from the MSDN page on
sp_executesql
)But I don't think this will fit your use case.