SQL Server 2008 R2:更改视图

时间:2014-10-15 03:27:10

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

我想编写一个存储过程来通过将视图名称作为参数传递给存储过程来改变视图。

示例

我有一个名为view1的视图,它从4个名为tb1, tb2, tb3, tb4的表中进行选择,这些表已经更新了一些。

现在我希望使用更新的表最新更新视图。

尝试:

create proc alterview
   @viewname varchar(50)
AS
   Declare @query nvarchar(max)
   Declare @TableNames varchar(max)

   SET @query = 'DECLARE Cursor_Get_Tables CURSOR fast_forward for 
                    SELECT Table_Name
                    FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE
                    WHERE View_Name = ''' + @ViewName + ''''                     

   EXEC sp_executesql @query


   OPEN Cursor_Get_Tables

   FETCH NEXT FROM Cursor_Get_Tables INTO @TableNames

   WHILE(@@fetch_status = 0)
   BEGIN   
       /* STUCK here */
       SET @query = 'ALTER VIEW ' + @ViewName + ' AS SELECT * FROM ' + @TableNames+ ' 
       /* Not getting to get all tables into single alter view script here */

       EXEC(@SQL)

       FETCH NEXT FROM Cursor_Get_Tables INTO @TableNames
   END

   CLOSE Cursor_Get_Tables      
   DEALLOCATE Cursor_Get_Tables
GO  

注意:我没有得到如何将所有表格转换为单个ALTER VIEW脚本,如:

ALTER VIEW View1 AS 
   SELECT * FROM tb1 
   UNION 
   SELECT * FROM tb2 
   UNION 
   SELECT * FROM tb3 
   UNION 
   SELECT * FROM tb4 
   UNION;

2 个答案:

答案 0 :(得分:2)

此处不需要光标。尝试:

CREATE PROC alterview
    @ViewName sysname
AS

DECLARE @SQL nvarchar(MAX);

SELECT @SQL = 
    'ALTER VIEW ' + @ViewName
     + ' AS SELECT * FROM '
     + STUFF((SELECT ' UNION ALL SELECT * FROM ' + TABLE_NAME
        FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE
        WHERE VIEW_NAME = @viewname
        FOR XML PATH('')), 1, 11, '') + ';';
EXECUTE (@SQL);
GO

答案 1 :(得分:1)

您需要保持' ALTER VIEW ViewName AS'在while循环之外。然后在循环中追加带有alter view语句的select语句。最后在循环之外执行查询。

OPEN Cursor_Get_Tables

FETCH NEXT FROM Cursor_Get_Tables INTO @TableNames

SET @query = 'ALTER VIEW ' + @ViewName + ' AS '

WHILE( @@FETCH_STATUS = 0 )
  BEGIN
      SET @query += 'SELECT * FROM ' + @TableNames + ' Union '

      FETCH NEXT FROM Cursor_Get_Tables INTO @TableNames
  END

CLOSE Cursor_Get_Tables

DEALLOCATE Cursor_Get_Tables

SELECT @query = LEFT(@query, Len(@query) - 5)

EXEC(@SQL)