在写数据库脚本时,特别是在存储过程中会经常遇到使用表的场景,一般会使用临时表或表变量甚至表类型来实现。但其具体区别是什么?适用场景有哪里?jawidx根据自己经验对不同方法进行简单介绍。
工具/原料
microsoft sql server
具体用法
2
临时表,使用tempdb,涉及到物理IO读写,所有操作有日志,有锁机制,支持索引和统计数据。create table #t(id int,name varchar(50),years int,nums int)insert #t select 1,'nn',14,15union all select 1,'nn',14,15insert into #t exec sp_gets --可以用于存储过程或动态SQL结合select * from #tdrop table #t --删除临时表
3
表类型(MSSQL2008中,可通过表类型可实现向存储过程传递表值参数)create type tabletypename as table(id int,name varchar(20) null)gocreate procedure uspname(@tb tabletypename )asbegin insert into @tb(id,name) values (2,'wo')end传递表值参数有一定局限性,在传递表值变量到程序时必须使用READONLY从句,不能表格变量里的数据进行修改。(传递表值参数未试
区别及总结22
根据表变量及临时表的存储及所受支持,使用时采用以下原则:(1)对小数据量使用表变量存储,而数据量大时采用临时表。(2)对于重要数据使用临时表,以便有更完善的记录日志。(3)对于需要检索统计的数据使用临时表。
上一篇:舞台发光地砖的安装方法