当前位置: 代码迷 >> Sql Server >> 写句sql解决方法
  详细解决方案

写句sql解决方法

热度:83   发布时间:2016-04-27 15:57:11.0
写句sql
本人使用游标实现一次就查询出一个数据库内所有用户表的前两条记录

只是想问有没有办法不用游标就实现这种功能?
use   [db_test]
declare   @sql   varchar(1000)
declare   @tbl   varchar(200)
declare   hyc   cursor
local
for   select   name   from   sysobjects   where   objectproperty(object_id(name), 'IsUserTable ')=1
open   hyc
while   @@fetch_status=0
begin
fetch   next   from   hyc   into   @tbl
set   @sql= 'select   top   2   *   from   '   +   @tbl
exec(@sql)
end
close   hyc
deallocate   hyc
go

------解决方案--------------------
sp_msforeachtable 'SELECT TOP 2 * FROM ? '

---------------------
sp_msforeachtable这个存储过程是微软没有公布的,好像就是为你这个需求而生的.

  相关解决方案