现在的位置: 首页 > 综合 > 正文

有趣的自定义类型:表

2014年07月28日 ⁄ 综合 ⁄ 共 744字 ⁄ 字号 评论关闭

--创建自定义类型,这里的自定义类型是表,可存储记录
CREATE TYPE LocationTableType AS TABLE 
    ( LocationName VARCHAR(50)
    , CostRate INT )
GO
 

declare @t LocationTableType

/*
--通过表变量来中转
declare @tt table 
( LocationName VARCHAR(50),CostRate INT )

insert into @tt
select '123',1

insert into @t
select * from @tt
*/

--可以直接把数据添加到LocationTableType类型中 
--可以存储多条记录
insert into @t
select '123',1
union all
select 'abc',2

select *
from @t

用于存储过程中:

--创建自定义类型,这里的自定义类型是表,可存储记录
CREATE TYPE MyTable AS TABLE 
    ( a VARCHAR(50),
      b INT )
GO


--drop proc proc_table


--创建存储过程,传入参数为自定义表
CREATE Procedure dbo.proc_table  
(@ManyRows as MyTable readonly  
)  
as

select * from @manyrows
go

 


declare @t MyTABLE


--可以直接把数据添加到LocationTableType类型中 
--可以存储多条记录
insert into @t
select '123',1
union all
select 'abc',2


exec proc_table @t
/*
a                                                  b
-------------------------------------------------- -----------
123                                                1
abc                                                2

(2 行受影响)
*/

抱歉!评论已关闭.