遍历本地T-SQL变量的所有值

时间:2019-06-16 11:55:49

标签: sql tsql

我的目标是编写一个可重用的脚本来检查我的每个视图是否运行并包含一些记录。

我已经编写了一个核心功能,但是我的 @subquery 变量仅包含第一个视图名称。

但是如何遍历本地T-SQL变量的所有值?

数据库:Microsoft SQL Server 2014

USE TSQL2012
GO

DECLARE @subquery nvarchar (255)
DECLARE @view_name nvarchar (255)
DECLARE @main_query nvarchar (255)

SET @subquery = 'select @view_name = concat(VIEW_CATALOG, char(46), VIEW_SCHEMA, 
                 char(46), VIEW_NAME) from (
                                           select distinct VIEW_CATALOG, VIEW_SCHEMA, VIEW_NAME 
                                           from INFORMATION_SCHEMA.VIEW_TABLE_USAGE) S'

EXEC sp_executesql @subquery,
                    N'@view_name nvarchar(255) OUTPUT', 
                    @view_name = @view_name OUTPUT

-- 1 - True (the table has records), 0 - False (the table doesn't have records)
SET @main_query = 'select ' + char(39) + @view_name + char(39) + 'as [View Name], 
                   count(*) as [The view has records] from   
                   (select top(1) 1 as cnt from ' + @view_name + ') s'

EXEC sp_executesql @main_query, N'@view_name nvarchar(255)', @view_name = @view_name

1 个答案:

答案 0 :(得分:2)

我不太确定我能理解您为什么选择VIEW_TABLE_USAGE而不是VIEWS的原因,但这是一种更简单的方法来完成您想要的事情:

DECLARE @SQL nvarchar(max);

SELECT @SQL = STUFF((
SELECT  CONCAT(
        ' UNION ALL SELECT ''',
        TABLE_CATALOG, CHAR(46), TABLE_SCHEMA, CHAR(46), TABLE_NAME,
        ''' AS [View Name], COUNT(*) AS Cnt FROM ',
        TABLE_CATALOG, CHAR(46), TABLE_SCHEMA, CHAR(46), TABLE_NAME)
FROM INFORMATION_SCHEMA.VIEWS
FOR XML PATH('')
), 1, 11, 'WITH CTE AS (') + ') SELECT [View Name], Cnt FROM CTE WHERE Cnt > 0'

-- Whenever using dynamic SQL, print is your best friend.   
PRINT @SQL;

-- unremark once you've checked the printed SQL is O.k
--EXEC(@SQL)