Compartir a través de


Crear, modificar y quitar reglas

En SMO, el objeto Rule representa las reglas. La propiedad TextBody, que es una cadena de texto que contiene una expresión de condición que utiliza operadores o predicados, como IN, LIKE o BETWEEN, define la regla. Una regla no puede hacer referencia a columnas u otros objetos de base de datos. Se pueden incluir funciones integradas que no hagan referencia a objetos de base de datos.

La definición en la propiedad TextBody debe contener una variable que haga referencia al valor de datos escrito. Se puede utilizar cualquier nombre o símbolo para representar el valor cuando se crea la regla, pero el primer carácter debe ser la arroba (@).

Ejemplo

Para utilizar cualquier ejemplo de código que se proporcione, deberá elegir el entorno de programación, la plantilla de programación y el lenguaje de programación en los que crear su aplicación. Para obtener más información, vea Crear un proyecto de Visual Basic SMO en Visual Studio .NET o Crear un proyecto de Visual C# SMO en Visual Studio .NET.

Crear, modificar y quitar una regla en Visual Basic

En este ejemplo de código se muestra cómo crear una regla, cómo adjuntarla a una columna, cómo modificar las propiedades del objeto Rule, cómo desasociar la regla de la columna y, por último, cómo quitarla.

La instrucción Dim para el objeto Rule se especifica con la ruta completa del ensamblado para evitar la ambigüedad con un objeto Rule del ensamblado System.Data.

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Reference the AdventureWorks2012 database.
Dim db As Database
db = srv.Databases("AdventureWorks2012")
'Declare a Table object variable and reference the Product table.
Dim tb As Table
tb = db.Tables("Product", "Production")
'Define a Rule object variable by supplying the parent database, name and schema in the constructor. 
'Note that the full namespace must be given for the Rule type to differentiate it from other Rule types.
Dim ru As Microsoft.SqlServer.Management.Smo.Rule
ru = New Rule(db, "TestRule", "Production")
'Set the TextHeader and TextBody properties to define the rule.
ru.TextHeader = "CREATE RULE [Production].[TestRule] AS"
ru.TextBody = "@value BETWEEN GETDATE() AND DATEADD(year,4,GETDATE())"
'Create the rule on the instance of SQL Server.
ru.Create()
'Bind the rule to a column in the Product table by supplying the table, schema, and 
'column as arguments in the BindToColumn method.
ru.BindToColumn("Product", "SellEndDate", "Production")
'Unbind from the column before removing the rule from the database.
ru.UnbindFromColumn("Product", "SellEndDate", "Production")
ru.Drop()

Crear, modificar y quitar una regla en Visual C#

En este ejemplo de código se muestra cómo crear una regla, cómo adjuntarla a una columna, cómo modificar las propiedades del objeto Rule, cómo desasociar la regla de la columna y, por último, cómo quitarla.

La instrucción Dim para el objeto Rule se especifica con la ruta completa del ensamblado para evitar la ambigüedad con un objeto Rule en el ensamblado System.Data.

{
            //Connect to the local, default instance of SQL Server. 
            Server srv;
            srv = new Server();
            //Reference the AdventureWorks2012 database. 
            Database db;
            db = srv.Databases["AdventureWorks2012"];
        
            //Define a Rule object variable by supplying the parent database, name and schema in the constructor. 
            //Note that the full namespace must be given for the Rule type to differentiate it from other Rule types. 
            Microsoft.SqlServer.Management.Smo.Rule ru;
            ru = new Rule(db, "TestRule", "Production");
            //Set the TextHeader and TextBody properties to define the rule. 
            ru.TextHeader = "CREATE RULE [Production].[TestRule] AS";
            ru.TextBody = "@value BETWEEN GETDATE() AND DATEADD(year,4,GETDATE())";
            //Create the rule on the instance of SQL Server. 
            ru.Create();
            //Bind the rule to a column in the Product table by supplying the table, schema, and 
            //column as arguments in the BindToColumn method. 
            ru.BindToColumn("Product", "SellEndDate", "Production");
            //Unbind from the column before removing the rule from the database. 
            ru.UnbindFromColumn("Product", "SellEndDate", "Production");
            ru.Drop();


        }

Crear, modificar y quitar una regla en PowerShell

En este ejemplo de código se muestra cómo crear una regla, cómo adjuntarla a una columna, cómo modificar las propiedades del objeto Rule, cómo desasociar la regla de la columna y, por último, cómo quitarla.

La instrucción Dim para el objeto Rule se especifica con la ruta completa del ensamblado para evitar la ambigüedad con un objeto Rule en el ensamblado System.Data.

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

# Define a Rule object variable by supplying the parent database, name and schema in the constructor. 
$ru = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Rule `
-argumentlist $db, "TestRule", "Production"

#Set the TextHeader and TextBody properties to define the rule. 
$ru.TextHeader = "CREATE RULE [Production].[TestRule] AS"
$ru.TextBody = "@value BETWEEN GETDATE() AND DATEADD(year,4,GETDATE())"

#Create the rule on the instance of SQL Server. 
$ru.Create()

# Bind the rule to a column in the Product table by supplying the table, schema, and 
# column as arguments in the BindToColumn method. 
$ru.BindToColumn("Product", "SellEndDate", "Production")

#Unbind from the column before removing the rule from the database. 
$ru.UnbindFromColumn("Product", "SellEndDate", "Production")
$ru.Drop()

Vea también

Referencia

Rule