Compartir a través de


Crear, modificar y eliminar los procedimientos almacenados

En los objetos de administración de SQL Server (SMO), el objeto StoredProcedure representa los procedimientos almacenados.

Para crear un objeto StoredProcedure en SMO, se requiere establecer la propiedad TextBody en el script Transact-SQL que define el procedimiento almacenado. Los parámetros requieren el prefijo @ y se deben crear individualmente utilizando los objetos StoredProcedureParameter y agregando a la colección StoredProcedureParameter del objeto StoredProcedure.

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 eliminar un procedimiento almacenado en Visual Basic

En este ejemplo de código se muestra cómo crear un procedimiento almacenado para la base de datos AdventureWorks2012. El ejemplo devuelve el apellido de un empleado cuando se proporciona el número de identificador del empleado. El procedimiento almacenado requiere un parámetro de entrada que especifique el número de identificador del empleado y un parámetro de salida para devolver el apellido del empleado.

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Reference the AdventureWorks2012 2008R2 database.
Dim db As Database
db = srv.Databases("AdventureWorks2012")
'Define a StoredProcedure object variable by supplying the parent database and name arguments in the constructor.
Dim sp As StoredProcedure
sp = New StoredProcedure(db, "GetLastNameByEmployeeID")
'Set the TextMode property to false and then set the other object properties.
sp.TextMode = False
sp.AnsiNullsStatus = False
sp.QuotedIdentifierStatus = False
'Add two parameters.
Dim param As StoredProcedureParameter
param = New StoredProcedureParameter(sp, "@empval", DataType.Int)
sp.Parameters.Add(param)
Dim param2 As StoredProcedureParameter
param2 = New StoredProcedureParameter(sp, "@retval", DataType.NVarChar(50))
param2.IsOutputParameter = True
sp.Parameters.Add(param2)
'Set the TextBody property to define the stored procedure.
Dim stmt As String
stmt = " SELECT @retval = (SELECT LastName FROM Person.Person AS p JOIN HumanResources.Employee AS e ON p.BusinessEntityID = e.BusinessEntityID AND e.BusinessEntityID = @empval )"
sp.TextBody = stmt
'Create the stored procedure on the instance of SQL Server.
sp.Create()
'Modify a property and run the Alter method to make the change on the instance of SQL Server.   
sp.QuotedIdentifierStatus = True
sp.Alter()
'Remove the stored procedure.
sp.Drop()

Crear, modificar y eliminar un procedimiento almacenado en Visual C#

En este ejemplo de código se muestra cómo crear un procedimiento almacenado para la base de datos AdventureWorks2012. El ejemplo devuelve el apellido de un empleado cuando se proporciona el número de identificador del empleado (BusinessEntityID). El procedimiento almacenado requiere un parámetro de entrada que especifique el número de identificador del empleado y un parámetro de salida para devolver el apellido del empleado.

{
            //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 StoredProcedure object variable by supplying the parent database and name arguments in the constructor. 
            StoredProcedure sp;
            sp = new StoredProcedure(db, "GetLastNameByBusinessEntityID");
            //Set the TextMode property to false and then set the other object properties. 
            sp.TextMode = false;
            sp.AnsiNullsStatus = false;
            sp.QuotedIdentifierStatus = false;
            //Add two parameters. 
            StoredProcedureParameter param;
            param = new StoredProcedureParameter(sp, "@empval", DataType.Int);
            sp.Parameters.Add(param);
            StoredProcedureParameter param2;
            param2 = new StoredProcedureParameter(sp, "@retval", DataType.NVarChar(50));
            param2.IsOutputParameter = true;
            sp.Parameters.Add(param2);
            //Set the TextBody property to define the stored procedure. 
            string stmt;
            stmt = " SELECT @retval = (SELECT LastName FROM Person.Person,HumanResources.Employee WHERE Person.Person.BusinessEntityID = HumanResources.Employee.BusinessentityID AND HumanResources.Employee.BusinessEntityID = @empval )";
            sp.TextBody = stmt;
            //Create the stored procedure on the instance of SQL Server. 
            sp.Create();
            //Modify a property and run the Alter method to make the change on the instance of SQL Server. 
            sp.QuotedIdentifierStatus = true;
            sp.Alter();
            //Remove the stored procedure. 
            sp.Drop();
        }

Crear, modificar y eliminar un procedimiento almacenado en PowerShell

En este ejemplo de código se muestra cómo crear un procedimiento almacenado para la base de datos AdventureWorks2012. El ejemplo devuelve el apellido de un empleado cuando se proporciona el número de identificador del empleado (BusinessEntityID). El procedimiento almacenado requiere un parámetro de entrada que especifique el número de identificador del empleado y un parámetro de salida para devolver el apellido del empleado.

# 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 StoredProcedure object variable by supplying the parent database and name arguments in the constructor. 
$sp  = New-Object -TypeName Microsoft.SqlServer.Management.SMO.StoredProcedure `
-argumentlist $db, "GetLastNameByBusinessEntityID"

#Set the TextMode property to false and then set the other object properties. 
$sp.TextMode = $false
$sp.AnsiNullsStatus = $false
$sp.QuotedIdentifierStatus = $false

# Add two parameters
$type = [Microsoft.SqlServer.Management.SMO.Datatype]::Int
$param  = New-Object -TypeName Microsoft.SqlServer.Management.SMO.StoredProcedureParameter `
-argumentlist $sp,"@empval",$type
$sp.Parameters.Add($param)

$type = [Microsoft.SqlServer.Management.SMO.DataType]::NVarChar(50)
$param2  = New-Object -TypeName Microsoft.SqlServer.Management.SMO.StoredProcedureParameter `
-argumentlist $sp,"@retval",$type
$param2.IsOutputParameter = $true
$sp.Parameters.Add($param2)

#Set the TextBody property to define the stored procedure. 
$sp.TextBody =  " SELECT @retval = (SELECT LastName FROM Person.Person,HumanResources.Employee WHERE Person.Person.BusinessEntityID = HumanResources.Employee.BusinessentityID AND HumanResources.Employee.BusinessEntityID = @empval )"
            
# Create the stored procedure on the instance of SQL Server. 
$sp.Create()

# Modify a property and run the Alter method to make the change on the instance of SQL Server. 
$sp.QuotedIdentifierStatus = $true
$sp.Alter()

#Remove the stored procedure. 
$sp.Drop()

Vea también

Referencia

StoredProcedure