日期:2014-05-18  浏览次数:20461 次

返回记录总数的存储过程
用户传来一个表名,返回这个表的记录总数,这个存储过程怎么改进呢、谢谢

alter   proc   testa(
    @stable   varchar(250),
    @recordcount   varchar(20)   output
)
as declare   @str   varchar(500)
select   @str= 'select   @recordcount=count(*)   from   '+@stable
exec(@str)

------解决方案--------------------
alter proc testa(
@stable varchar(250),
@recordcount int output
)
as declare @str nvarchar(500)
select @str= 'select @recordcount=count(*) from '+@stable
exec sp_executesql @str,N '@recordcount int output ',@recordcount output
------解决方案--------------------
alter proc testa(
@stable varchar(250),
@recordcount int output
)
as
begin
declare @str nvarchar(500)
select @str=N 'select @recordcount=count(*) from '+@stable
exec sp_executesql @str,N '@recordcount int out ', @recordcount out
return
end
go
------解决方案--------------------
alter proc testa(
@stable varchar(250),
@recordcount varchar(20) output
)
as declare @str Nvarchar(500)
select @str=N 'select @recordcount=CONVERT(varchar,count(*)) from '+@stable
exec sp_executesql @str,N '@recordcount varchar(20) output ',@recordcount output

------解决方案--------------------
--测试代码
declare @i int
exec testa 'sysobjects ',@i output
print @i
------解决方案--------------------
alter proc testa(
@stable varchar(250),
@recordcount int output
)
as declare @str nvarchar(500)
select @str=N 'select @recordcount=count(*) from '+@stable
Execute sp_executesql @str,N '@recordcount int OUTPUT ',@recordcount OUTPUT


------解决方案--------------------
use pubs
go
alter proc testa(
@stable varchar(250),
@recordcount int output
)
as
declare @str nvarchar(4000)
select @str=N 'select @recordcount=count(*) from '+@stable
exec sp_executesql @str,N '@recordcount int output ',@recordcount output

go
declare @i int
exec testa 'authors ',@i output
select @i
------解决方案--------------------
sp_executesql可以包含参数,exec不行