Compartilhar via


Criando, alterando e removendo regras

No SMO, as regras são representadas pelo objeto Rule. A regra é definida pela propriedade TextBody, que é uma cadeia de caracteres de texto contendo uma expressão de condição que usa operadores ou predicados, tais como IN, LIKE ou BETWEEN. Uma regra não pode fazer referência a colunas ou a outros objetos de banco de dados. É possível incluir funções internas que não fazem referência a objetos de banco de dados.

A definição na propriedade TextBody deve conter uma variável relativa ao valor de dados digitados. Qualquer nome ou símbolo pode ser usado para representar o valor durante a criação da regra. No entanto, o primeiro caractere precisa ser o símbolo @.

Exemplo

Para usar qualquer exemplo de código fornecido, será necessário escolher o ambiente de programação, o modelo de programação e a linguagem de programação para criar o seu aplicativo. Para obter mais informações, consulte Como criar um projeto SMO do Visual Basic no Visual Studio .NET ou Como criar um projeto SMO do Visual C# no Visual Studio .NET.

Criando, alterando e removendo uma regra no Visual Basic

Este exemplo de código mostra como criar uma regra, anexá-la a uma coluna, modificar propriedades do objeto Rule, desanexá-la da coluna e, em seguida, descartá-la.

A instrução Dim do objeto Rule é especificada com o caminho completo do assembly para evitar ambigüidade com um objeto Rule no assembly System.Data.

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Reference the AdventureWorks database.
Dim db As Database
db = srv.Databases("AdventureWorks")
'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()

Criando, alterando e removendo uma regra no Visual C#

Este exemplo de código mostra como criar uma regra, anexá-la a uma coluna, modificar propriedades do objeto Rule, desanexá-la da coluna e, em seguida, descartá-la.

A instrução Dim do objeto Rule é especificada com o caminho completo do assembly para evitar ambigüidades com um objeto Rule no assembly System.Data.

{ 
//Connect to the local, default instance of SQL Server. 
Server srv; 
srv = new Server(); 
//Reference the AdventureWorks database. 
Database db; 
db = srv.Databases("AdventureWorks"); 
//Declare a Table object variable and reference the Product table. 
Table tb; 
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. 
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();
}

Consulte também

Referência