在家学习下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, N‘@TotleCount 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 main_feeId=‘[email protected]
end
if(ISNULL( @Money,‘‘)!=‘‘)
begin
set @sql+= ‘ and main_money=‘[email protected]
end
declare @start int
declare @end int
set @start= (@Index-1)*@Size+1
set @[email protected]*@Index
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 main_feeId=‘[email protected]
end
if(ISNULL( @Money,‘‘)!=‘‘)
begin
set @sql+= ‘ and main_money=‘[email protected]
end
declare @start int
declare @end int
set @start= (@Index-1)*@Size+1
set @[email protected]*@Index
set @sqllen=‘ select @TotleCount= count(1) from (‘[email protected]+‘) t ‘
exec sp_executesql @sqllen, N‘@TotleCount 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