如果视图包含多个表,则返回true,否则返回false

时间:2014-10-01 13:20:37

标签: sql-server sql-server-2008-r2

我需要通过检测包含多个表的视图,从存储过程中返回真或假的结果。

尝试:

CREATE PROC spTest
@ViewName nvarchar(max)

AS

DECLARE @SQL nvarchar(max)
DECLARE @TableName nvarchar(max)


SET @SQL = 'SELECT  @TableName = Table_Name  
                 FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE
                 WHERE View_Name = ''' + @ViewName  + ''''

EXEC sp_executesql @SQL, N'@TableName nvarchar(max) OUTPUT', @TableName output

IF (@TableName > 1)
BEGIN
    SELECT 'True'
END
ELSE
BEGIN
    SELECT 'False'
END
GO

注意:我没有了解如何将tables中的所有view插入@TableName变量并检查条件。

2 个答案:

答案 0 :(得分:2)

您可以通过此

实现目标
create PROC spTest
@ViewName nvarchar(max)

AS

DECLARE @SQL nvarchar(max)


SET @SQL = '
DECLARE @TableName table (table_name varchar(1000))
insert into @TableName 
SELECT   Table_Name  
                 FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE
                 WHERE View_Name = ''' + @ViewName  + '''


IF (select count(1) from  @TableName )> 1
BEGIN
    SELECT ''True''
END
ELSE
BEGIN
    SELECT ''False''
END'
exec (@SQL)
GO

创建程序执行程序后 spTest' pace_entity_access_view'

答案 1 :(得分:1)

CREATE PROC Sptest @ViewName NVARCHAR(max)
AS
DECLARE @cnt INT

SELECT @cnt = Count(*)
FROM   INFORMATION_SCHEMA.VIEW_TABLE_USAGE
WHERE  VIEW_NAME = @ViewName

IF ( @cnt > 1 )
  BEGIN
      SELECT 'True'
  END
ELSE
  BEGIN
      SELECT 'False'
  END