I’ve just begun to learn how to write stored procedures and SQL code outside of the basic DML stuff. Something that I’ve recently come across is table value parameters. I’ve found a script to make a TVP and it works just fine but there are two things that I don’t understand about it. One, when to use them. What’s a typical real world scenario when a TVP would be beneficial. Two, how come when I remove the begin and end from the following script does it work the same; what’s the difference between having those keywords and not? SQL Server 2008 R2
use [tempdb]
--this is the database table that will be populated
create table SampleTable
(
id int not null identity (1,1)
,SampleString varchar(50)
,SampleInt int null
)
go
--create the table data type
create type dbo.SampleDataType as table
(
SampleString varchar(50)
,SampleInt int
)
go
--the stored procedure takes the SampleDataType as an input parameter
create proc SampleProc
(
--accepts the TVP as the lone parameter
--make sure that the TVP is readonly
@Sample as dbo.SampleDataType readonly
)
as
begin
--we simply insert the values into the db table from the parameter
insert into SampleTable(SampleString,SampleInt)
select SampleString,SampleInt from @Sample
end
go
--this is the sample script to test that the sproc worked
declare @SampleData as dbo.SampleDataType
insert into @SampleData(SampleString,SampleInt) values ('one',1);
insert into @SampleData(SampleString,SampleInt) values ('two',2);
select * from @SampleData
One real world use is to parameterise an
inclause.Where a query has a filter on
(x, y, z, ...)you no longer have to resort to one of the methods here such as passing it in as a comma delimited list and then splitting it.The
BEGIN ... ENDmake no difference there. It defines a block. You might use that after anIFstatement for example to group multiple statements together into one logical block.