随笔 - 139, 文章 - 5, 评论 - 39, 阅读 - 16万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

sql 创建表变量,临时表

Posted on   小飞龙(Jack)  阅读(3550)  评论(1编辑  收藏  举报

基本原则:能用表变量就用表变量.实在不行才使用临时表
表变量主要是开销系统的内存,而临时表则使用tempdb.对于小数据量的中间数据存储,可以使用表变量,而当需要临时保存的数据很大时,建议使用临时表.
declare @tb table(id int,name varchar(50),age int--创建表变量

insert @tb select 1,'nn',14
select * from @tb


create table #t(id int,name varchar(50),years int,nums int)--创建临时表

insert #t select 1,'nn',14,15
union all select 1,'nn',14,15
insert into #t  exec sp_gets  --可以用于存储过程或动态SQL结合

select * from #t
drop table #t --删除临时表


实例

------------------------------------------------------------------ ----------------------------

declare @tab table
(
    id int,
    name nvarchar(50)
)
insert into @tab(id,name)
select person_id,1 from personinfo
select * from @tab
------------------------------------------------------------------ ----------------------------


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:    <Jack zhang>
-- Create date: <2007-08-04>
-- Description:   <获取家庭吸烟总量(创建表变量)>
-- =============================================

ALTER PROCEDURE [dbo].[Family_SmokeTotal]
(@Family_ID int)
AS
declare @tab table(Person_ID int)
insert into @tab(Person_ID)
select Person_ID from PersonInfo where Family_ID=@Family_ID
select Sum(SmokeCount) '家庭吸烟总数' from PersonActionInfo where Person_id  in (select Person_id from @tab)

//临时表
CREATE TABLE #tmp
(
 rq NVARCHAR(10),
 shengfu NVARCHAR(1)
)
INSERT into #tmp select'2005-05-09','胜'
Insert into #tmp select'2005-05-09','胜'
insert into #tmp select'2005-05-09','负'
insert into #tmp select'2005-05-09','负'
insert into #tmp select'2005-05-10','胜'
insert into #tmp select'2005-05-10','负'
insert into #tmp select'2005-05-10','负'

SELECT rq,sum(case when shengfu='胜' then 1 else 0 end)'胜',sum(case when shengfu='负' then 1 else 0 end)'负'
from
#tmp
group by rq

drop table #tmp

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示