--查询数据库中所有记录总数不为0的数据表名称
--声明变量
declare @TableName nvarchar(250)
--声明一个游标mycursor,select语句中参数的个数必须要和从游标取出的变量名相同
declare mycursor cursor for select name from sys.tables order by name
--打开游标
open mycursor
--从游标里取出数据赋值到我们刚才声明的变量中
fetch next from mycursor into @TableName
--判断游标的状态
--0 fetch语句成功
---1 fetch语句失败或此行不在结果集中
---2被提取的行不存在
declare @TableNameList nvarchar(4000)
set @TableNameList=''
while (@@fetch_status=0)
begin
--显示出我们每次用游标取出的值
--print '游标成功取出一条数据'
DECLARE @sql AS NVARCHAR(500),@i AS INT;
SET @sql = N' SELECT @p=ISNULL(COUNT(1),0) FROM '+@TableName+'';
EXEC sp_executesql @sql, N'@p AS INT OUTPUT',@p = @i OUTPUT
--输出所有记录不为0的表名称
IF @i>0
BEGIN
if(@TableNameList='')
set @TableNameList=@TableName
else
set @TableNameList=@TableNameList+','+@TableName
PRINT 'SELECT * FROM '+@TableName+';'
END
--用游标去取下一条记录
fetch next from mycursor into @TableName
end
--关闭游标
close mycursor
--撤销游标
deallocate mycursor
select @TableNameList