sqlserver怎麼建臨時表?
- 2022-11-18
declare @sql varchar(2000)declare @lie varchar(2000)set @sql=‘’set @lie=‘’select @sql=@sql+‘,case when sum(case when pzmc=’‘’+pzmc+‘’‘ then sl end) is null then 0 else sum(case when pzmc=’‘’+pzmc+‘’‘ then sl end) end as [’+pzmc+‘]’from Z_YidaiZajiaozhongShengchan where nian=‘2008’ and jidu=‘春’ and shsftg=‘透過’ group by pzmcselect @lie=@lie+‘+case when sum(case when pzmc=’‘’+pzmc+‘’‘ then sl end) is null then 0 else sum(case when pzmc=’‘’+pzmc+‘’‘ then sl end) end’from Z_YidaiZajiaozhongShengchan where nian=‘2008’ and jidu=‘春’ and shsftg=‘透過’ group by pzmcexec (‘select case when (grouping(tbdw)=1) then ’‘合計’‘ else tbdw end as 場別 ’+@sql+‘,’+@lie+‘ as 合計 from Z_YidaiZajiaozhongShengchan where nian=’‘2008’‘ and jidu=’‘春’‘ and shsftg=’‘透過’‘ group by tbdw with rollup’) 我想把上面查詢出來的結果建成一個臨時表或者是檢視,應該怎麼建啊?
表名前使用一個#號,臨時表是區域性的,使用兩個#號,臨時表是全域性的,在斷開連線後sql會自動刪除臨時表
create table #a
(
id int,
name varchar(50)
)
insert into #a(id,name) values(1,‘123’)
select * from #a
drop table #a
臨時表除了名稱前多了#號外,其他操作與普通表完全一樣。
tb_Student是已建立好的表,我們透過臨時表temp把tb_Student表中的內容複製到tb_lizi表中,可以使用如下的程式碼實現:
use mcf
SELECT * INTO #temp FROM tb_Student
SELECT * INTO tb_lizi FROM #temp
執行後斷開sql連線並重新連線(也可以退出sq再l重新啟動sql),發現tb_lizi表中的內容tb_Student表中的內容完全一致,實現了複製,同時我們沒有用程式碼刪除temp表,但mcf資料庫中卻沒有temp表了,這是因為斷開連線時sql自動刪除了temp表