循环打印视图(学习WHILE循环)
--按变量赋值方式
DECLARE @ViewName VARCHAR(50) --视图名 DECLARE @RowCount INT = 0 --总视图数 DECLARE @i INT = 0 --循环次数 SELECT @RowCount = COUNT(NAME) FROM sysobjects WHERE xtype = 'v' WHILE @i < @RowCount BEGIN SELECT @ViewName = t1.NAME FROM(SELECT ROW_NUMBER() OVER(ORDER BY NAME) AS RowNum, NAME FROM sysobjects WHERE xtype = 'v' ) AS t1 WHERE t1.RowNum = @i PRINT @ViewName SET @i = @i + 1 END
--按拼接Sql语句方式 DECLARE @ViewName VARCHAR(50) --视图名 DECLARE @RowCount INT = 0 --总视图数 DECLARE @i INT = 0 --循环次数 DECLARE @sql VARCHAR(MAX)='' SELECT @RowCount = COUNT(NAME) FROM sysobjects WHERE xtype = 'v' WHILE @i < 10 --@RowCount BEGIN SET @sql = 'select t1.NAME FROM( SELECT ROW_NUMBER() OVER(ORDER BY NAME) AS RowNum, NAME FROM sysobjects WHERE xtype = '+ '''v'+''')t1 WHERE t1.RowNum = '+ cast(@i AS VARCHAR) EXEC (@sql) SET @i = @i + 1 END
本文来自博客园,作者:liessay,转载请注明原文链接:https://www.cnblogs.com/liessay/p/8034266.html