1.1 简介 sql server 中,用户定义表类型是指用户所定义的表示表结构定义的类型。您可以使用用户定义表类型为存储过程或函数声明表值参数,或者声明您要在批处理中或在存储过程或函数的主体中使用的表变量。 若要创建用户定义表类型,请使用create type语句
1.1 简介
sql server 中,,用户定义表类型是指用户所定义的表示表结构定义的类型。您可以使用用户定义表类型为存储过程或函数声明表值参数,或者声明您要在批处理中或在存储过程或函数的主体中使用的表变量。
若要创建用户定义表类型,请使用create type语句。为了确保用户定义表类型的数据满足特定要求,您可以对用户定义表类型创建唯一约束和主键。
1.2 使用例题
在创建用户定义表类型前先建立一个数据库表
use [contacting]
go
set ansi_nulls on
go
set quoted_identifier on
go
set ansi_padding on
go
create table [dbo].[contact](
[contactid] [uniqueidentifier] not null,
[firstname] [nvarchar](80) not null,
[lastname] [nvarchar](80) not null,
[email] [nvarchar](80) not null,
[phone] [varchar](25) null,
[created] [datetime] not null,
primary key clustered
(
[contactid] asc
)with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary]
) on [primary]
go
set ansi_padding off
go
alter table [dbo].[contact] add default (getdate()) for [created]
go
然后创建一个用户定义表类型 insertcontacts
use [contacting]
go
create type [dbo].[contactstruct] as table(
[contactid] [uniqueidentifier] not null,
[firstname] [nvarchar](80) not null,
[lastname] [nvarchar](80) not null,
[email] [nvarchar](80) not null,
[phone] [varchar](25) not null,
primary key clustered
(
[contactid] asc
)with (ignore_dup_key = off)
)
go
sql server management studio看到的结果如下:
现在我们开始使用用户定义表类型 编写存储过程
use [contacting]
go
create procedure [dbo].[insertcontacts]
@contacts as contactstruct readonly
as
insert into contact(contactid, firstname, lastname, email, phone)
select contactid, firstname, lastname, email, phone from @contacts;
return 0
1.3 使用限制(很遗憾无法在表值参数中返回数据。 表值参数是只可输入的参数;不支持 output 关键字。)
请注意,用户定义表类型使用有以下限制:
1.在创建用户定义表类型定义后不能对其进行修改。(没搞懂为什么不可以修改)
2.不能在用户定义表类型的计算列的定义中调用用户定义函数。
3.无法对用户定义表类型创建非聚集索引,除非该索引是对用户定义表类型创建primary key 或unique约束的结果。
4.用户定义表类型不能用作表中的列或结构化用户定义类型中的字段。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!