declare @tablename nvarchar(20) declare @fieldname nvarchar(50) declare @SQLString nvarchar(300) DECLARE tnames_cursor CURSOR LOCAL FORWARD_ONLY READ_ONLY--声明游标 FOR select name from sysobjects where type='U';--游标需要用到的列 open tnames_cursor--打开游标 FETCH NEXT FROM tnames_cursor INTO @tablename --移动游标给变量赋值,应该与游标需要用到的列一一对应 ,顺序类型应该一致 WHILE (@@FETCH_STATUS = 0)--循环 BEGIN BEGIN set @fieldname= @tablename+'_TableCount' -- SET @SQLString = N'select cast(count(*) as char(10))+ ''' [email protected] +''' as [email protected] +' from ' [email protected] +' having count(*)>1'; SET @SQLString = N'select cast(count(*) as char(10))+ ''' [email protected] +''' as [email protected] +' from ' [email protected] +' having count(*)>1'; EXECUTE dbo.sp_executesql @SQLString END FETCH NEXT FROM tnames_cursor INTO @tablename --移动游标 给变量赋值 应该与游标需要用到的列一一对应 ,顺序类型应该一致 END CLOSE tnames_cursor--关闭游标 DEALLOCATE tnames_cursor--释放游标
declare @tablename nvarchar(20) declare @SQLString nvarchar(300) DECLARE @IntTotalCount int; DECLARE @ParmDefinition nvarchar(500); SET @ParmDefinition = N' @TotalCountOut int OUTPUT'; DECLARE tnames_cursor CURSOR LOCAL FORWARD_ONLY READ_ONLY--声明游标 FOR select name from sysobjects where type='U';--游标需要用到的列 open tnames_cursor--打开游标 FETCH NEXT FROM tnames_cursor INTO @tablename --移动游标给变量赋值,应该与游标需要用到的列一一对应 ,顺序类型应该一致 WHILE (@@FETCH_STATUS = 0)--循环 BEGIN BEGIN SET @SQLString = N'select @TotalCountOut=count(*) from ' [email protected] +' having count(*)>1'; EXECUTE dbo.sp_executesql @SQLString ,@ParmDefinition, @[email protected] OUTPUT; if(@IntTotalCount>0) begin print @tablename+' has '+cast(@IntTotalCount as char(10)) print N'select * from '+ [email protected] end END FETCH NEXT FROM tnames_cursor INTO @tablename --移动游标 给变量赋值 应该与游标需要用到的列一一对应 ,顺序类型应该一致 END CLOSE tnames_cursor--关闭游标 DEALLOCATE tnames_cursor--释放游标
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/6701.html