With User Defined Table Type, we can store the structure of a table. We can use the User Defined Table Typies by defining the table-valued parameter in the Stored Procuder or Functions. We can use these structures instead of specifying the temporay table in the Stored Procedure or Function.
Below you can see the sample usage. You can find explanations in the scripts.
Create User Defined Table Type
1 2 3 4 5 6 |
USE AdventureWorks2008R2; GO CREATE TYPE LocationTableType AS TABLE ( LocationName VARCHAR(50) , CostRate INT ); GO |
Using User Defined Table Type in a Stored Procedure by using table-valued parameter
Table valued parameter in this example is @TVP
1 2 3 4 5 6 7 8 9 10 11 12 |
CREATE PROCEDURE usp_InsertProductionLocation @TVP LocationTableType READONLY AS SET NOCOUNT ON INSERT INTO [AdventureWorks2008R2].[Production].[Location] ([Name] ,[CostRate] ,[Availability] ,[ModifiedDate]) SELECT *, 0, GETDATE() FROM @TVP; GO |
Define a variable of the type of table type that we created
1 2 |
DECLARE @LocationTVP AS LocationTableType; |
Insert data to this variable
1 2 3 4 |
INSERT INTO @LocationTVP (LocationName, CostRate) SELECT [Name], 0.00 FROM [AdventureWorks2008R2].[Person].[StateProvince]; |
Execute the stored procedure by passing this variable as a parameter
1 2 |
EXEC usp_InsertProductionLocation @LocationTVP; GO |
Source <https://msdn.microsoft.com/en-us/library/bb510489(v=sql.105).aspx>