创建、更改和删除视图

在 SQL Server 管理对象 (SMO) 中,SQL Server 视图由 View 对象表示。

View 对象的 TextBody 属性可定义视图。它与创建视图的 Transact-SQL SELECT 语句等效。

示例

若要使用所提供的任何代码示例,您必须选择创建应用程序所需的编程环境、编程模板和编程语言。有关详细信息,请参阅如何在 Visual Studio .NET 中创建 Visual Basic SMO 项目如何在 Visual Studio .NET 中创建 Visual C# SMO 项目

在 Visual Basic 中创建、更改和删除视图

此代码示例显示如何使用内部联接创建两个表的视图。该视图是使用文本模式创建的,因此必须设置 TextHeader 属性。

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Reference the AdventureWorks2008R2 database.
Dim db As Database
db = srv.Databases("AdventureWorks2008R2")
'Define a View object variable by supplying the parent database, view name and schema in the constructor.
Dim myview As View
myview = New View(db, "Test_View", "Sales")
'Set the TextHeader and TextBody property to define the view.
myview.TextHeader = "CREATE VIEW [Sales].[Test_View] AS"
myview.TextBody = "SELECT h.SalesOrderID, d.OrderQty FROM Sales.SalesOrderHeader AS h INNER JOIN Sales.SalesOrderDetail AS d ON h.SalesOrderID = d.SalesOrderID"
'Create the view on the instance of SQL Server.
myview.Create()
'Remove the view.
myview.Drop()

在 Visual C# 中创建、更改和删除视图

此代码示例显示如何使用内部联接创建两个表的视图。该视图是使用文本模式创建的,因此必须设置 TextHeader 属性。

{
        //Connect to the local, default instance of SQL Server. 
        Server srv; 
        srv = new Server(); 
        //Reference the AdventureWorks2008R2 database. 
        Database db; 
        db = srv.Databases["AdventureWorks2008R2"]; 
        //Define a View object variable by supplying the parent database, view name and schema in the constructor. 
        View myview; 
        myview = new View(db, "Test_View", "Sales"); 
        //Set the TextHeader and TextBody property to define the view. 
        myview.TextHeader = "CREATE VIEW [Sales].[Test_View] AS"; 
        myview.TextBody = "SELECT h.SalesOrderID, d.OrderQty FROM Sales.SalesOrderHeader AS h INNER JOIN Sales.SalesOrderDetail AS d ON h.SalesOrderID = d.SalesOrderID"; 
        //Create the view on the instance of SQL Server. 
        myview.Create(); 
        //Remove the view. 
        myview.Drop(); 
        }

在 PowerShell 中创建、更改和删除视图

此代码示例显示如何使用内部联接创建两个表的视图。该视图是使用文本模式创建的,因此必须设置 TextHeader 属性。

# Set the path context to the local, default instance of SQL Server and get a reference to AdventureWorks2008R2
CD \sql\localhost\default\databases
$db = get-item Adventureworks2008R2

# Define a View object variable by supplying the parent database, view name and schema in the constructor. 
$myview  = New-Object -TypeName Microsoft.SqlServer.Management.SMO.View `
-argumentlist $db, "Test_View", "Sales"
      
# Set the TextHeader and TextBody property to define the view. 
$myview.TextHeader = "CREATE VIEW [Sales].[Test_View] AS"
$myview.TextBody ="SELECT h.SalesOrderID, d.OrderQty FROM Sales.SalesOrderHeader AS h INNER JOIN Sales.SalesOrderDetail AS d ON h.SalesOrderID = d.SalesOrderID"
        
# Create the view on the instance of SQL Server. 
$myview.Create()

# Remove the view. 
$myview.Drop();

请参阅

参考