我刚刚开始学习如何在基本的 DML 内容之外编写存储过程和 SQL 代码。我最近遇到的是表值参数。我找到了一个制作 TVP 的脚本,它工作得很好,但有两件事我不明白。一,何时使用它们。当 TVP 有益时,典型的现实世界场景是什么?二,当我从以下脚本中删除begin
and时end
,它的工作原理是一样的吗?有这些关键字和没有这些关键字有什么区别?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