1. 程式人生 > >MSSQL 臨時表學習

MSSQL 臨時表學習

execute 獲取 mssql 創建 結果 dex isnull () output

在家學習下MSSQL的零食表玩法 通過一個存儲過程 因為不知道怎麽怎麽在存儲過程裏動態調用SQL 所以不得不想另想辦法 所以想到了臨時表的辦法 其關鍵點就是在得到的條數數據儲存到臨時表中然後再讀取臨時表 從而達到獲取全部條數的目的 其中也學到了不少新東西

1.臨時表的判斷存在的寫法 (臨時表表名 #tt)

if(exists(select * from tempdb..sysobjects where id = OBJECT_ID(‘tempdb..#tt‘) ) )

2.臨時表的概念

可以創建本地和全局臨時表。本地臨時表僅在當前會話中可見;全局臨時表在所有會話中都可見。
本地臨時表的名稱前面有一個編號符 (#table_name),而全局臨時表的名稱前面有兩個編號符 (##table_name)。

一般都是用本地臨時的(#) 其他人看不到 創建方法和創建表一樣只是表名前面有個#

3.存儲過程中動態執行SQL的函數 sp_executesql 記得動態SQL的變量類型不能為varchar 必須是N開頭的 例如nvarchar

exec sp_executesql @sqllen, [email protected] int output‘,@TotleCount output

原版用臨時表實現的結果

if(exists(select * from sysobjects where id= OBJECT_ID(‘procTest‘) ))
begin

drop proc procTest
end

go
create proc procTest
@FeeID varchar(100),
@Money varchar(100),
@Index int,
@Size int,
@TotleCount int output
as
if(exists(select * from tempdb..sysobjects where id = OBJECT_ID(‘tempdb..#tt‘) ) )
begin
truncate table #tt
end
else
begin
create table #tt
(
tLen int
)
end
declare @sql varchar(max)

declare @sqllen varchar(max)
set @sql=‘select ROW_NUMBER() over(order by main_time) as rowIndex ,* from main where 1=1 ‘
if(ISNULL( @FeeID,‘‘)!=‘‘)
begin
set @sql+= ‘ and [email protected]
end
if(ISNULL( @Money,‘‘)!=‘‘)
begin
set @sql+= ‘ and [email protected]
end
declare @start int
declare @end int
set @start= (@Index-1)[email protected]+1
set @[email protected][email protected]
set @sqllen=‘ insert into #tt select count(1) from ([email protected]+‘) t ‘
--print(@sqllen)
exec(@sqllen)
select @TotleCount=tLen from #tt
set @sql= ‘select * from ( [email protected]+‘) t where rowIndex between ‘+ CONVERT(varchar(10), @start) +‘ and ‘+ CONVERT(varchar(10), @end)
exec(@sql)

改寫後的結果

if(exists(select * from sysobjects where id= OBJECT_ID(‘procTest‘) ))
begin
drop proc procTest
end

go
create proc procTest
@FeeID varchar(100),
@Money varchar(100),
@Index int,
@Size int,
@TotleCount int output
as

declare @sql varchar(max)
declare @sqllen nvarchar(max)
set @sql=‘select ROW_NUMBER() over(order by main_time) as rowIndex ,* from main where 1=1 ‘
if(ISNULL( @FeeID,‘‘)!=‘‘)
begin
set @sql+= ‘ and [email protected]
end
if(ISNULL( @Money,‘‘)!=‘‘)
begin
set @sql+= ‘ and [email protected]
end
declare @start int
declare @end int
set @start= (@Index-1)[email protected]+1
set @[email protected][email protected]

set @sqllen=‘ select @TotleCount= count(1) from ([email protected]+‘) t ‘
exec sp_executesql @sqllen, [email protected] int output‘,@TotleCount output

set @sql= ‘select * from ( [email protected]+‘) t where rowIndex between ‘+ CONVERT(varchar(10), @start) +‘ and ‘+ CONVERT(varchar(10), @end)
exec(@sql)

調用

declare @aa int
exec procTest ‘7‘,‘‘,1,40, @aa output
select @aa

MSSQL 臨時表學習