SQL Server Management Studio té la utilitat de poder extreure scipts d'objectes.
La manera d'extreure el codi no és a través de t-sql sinó a través de programació amb la SDK d'SQL Server. En l'exemple he utilitzar codi C#, però també es pot fer en VB.net o Powershell. Ho he fet en C# per poder-ho integrar més fàcilment a en una Script Task d'SSIS.
En l'exemple veurem com extreure el codi de jobs de l'agent d'SQL Server. Per a la resta d'objectes el funcionament bàsic és el mateix, només canvia sobre quin objecte s'invoca la funció Script().
Abans de començar amb el codi repasarem les dependències. Les dll estan a C:\Program Files (x86)\Microsoft SQL Server\120\SDK\Assemblies (pot canviar segons la versió d'SQL Server instal·lada, en el meu cas és la 2014).
Les dll utilitzades són:
- Microsoft.SqlServer.ConnectionInfo.dll
- Microsoft.SQLServer.ManagedDTS.dll
- Microsoft.SqlServer.Management.Sdk.Sfc.dll
- Microsoft.SqlServer.Management.UtilityEnum.dll
- Microsoft.SqlServer.Smo.dll
Els namespaces que necessitem són:
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Sdk.Sfc;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo.Agent;
using System.Collections.Generic;
using System.Collections.Specialized;
Ja entrant a dins del codi,primer ens connectarem al nostre servidor:
ServerConnection sc = new ServerConnection();
sc.ConnectionString = "Data Source=.;Initial Catalog=msdb;Integrated Security=SSPI;";
Server srv = new Server(sc);
i recuperarem els jobs:
JobCollection jobs = srv.JobServer.Jobs;
Un cop tenim els jobs podem optar per recorre'ls tots:
foreach (Job job in jobs){
//TODO insert code
}
O bé seleccionar un dels jobs per nom:
Job job = jobs[jobName];
Ara crearem un objecte ScriptingOptions per dir les característiques que volem a l'script. (https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.scriptingoptions.aspx)
ScriptingOptions so = new ScriptingOptions();
//so.ScriptDrops = true;
so.FileName = "c:\\Files\\job"+jobName+"_sp.txt";
En aquest cas hem triat que ens mostri la sentència de creació (scriptDrops per defecte) i que deixi el resultat en un fitxer amb el nom FileName.
En aquest moment ja podem invocar la funció Script per extreure el codi. També es pot invocar la funció Script sense ScriptingOptions i t'executa amb les opcions per defecte.
StringCollection stc = job.Script(so);
La variable stc contindrà l'script i, a més, també tindrem l'script al fitxer que hem assignat a so.FileName.
foreach (String st in stc)
{
System.IO.File.WriteAllText(@"C:\Files\job" + jobName + ".txt", st);
}
En teoria el fitxer jom<jobName>_sp.txt i job<jobName>.txt hauríen de contenir el mateix, però hi ha 1 diferència important: el fitxer generat per la funció Script acaba en GO, el generat a partir dels Strings no acaba en GO.
Aquesta diferència és molt important si després volem executar el codi a través del procedure sp_executesql ja que aquest procedure no accepta el GO i ens donaria error.
Això és tot per avui. Us copio tot el codi sencer per poder-lo utilitzar dins d'una Script Task al SSDT.
Avui veurem com poder extreure aquests scripts per codi i així poder-los reaprofitar.
La manera d'extreure el codi no és a través de t-sql sinó a través de programació amb la SDK d'SQL Server. En l'exemple he utilitzar codi C#, però també es pot fer en VB.net o Powershell. Ho he fet en C# per poder-ho integrar més fàcilment a en una Script Task d'SSIS.
En l'exemple veurem com extreure el codi de jobs de l'agent d'SQL Server. Per a la resta d'objectes el funcionament bàsic és el mateix, només canvia sobre quin objecte s'invoca la funció Script().
Abans de començar amb el codi repasarem les dependències. Les dll estan a C:\Program Files (x86)\Microsoft SQL Server\120\SDK\Assemblies (pot canviar segons la versió d'SQL Server instal·lada, en el meu cas és la 2014).
Les dll utilitzades són:
- Microsoft.SqlServer.ConnectionInfo.dll
- Microsoft.SQLServer.ManagedDTS.dll
- Microsoft.SqlServer.Management.Sdk.Sfc.dll
- Microsoft.SqlServer.Management.UtilityEnum.dll
- Microsoft.SqlServer.Smo.dll
Els namespaces que necessitem són:
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Sdk.Sfc;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo.Agent;
using System.Collections.Generic;
using System.Collections.Specialized;
Ja entrant a dins del codi,primer ens connectarem al nostre servidor:
ServerConnection sc = new ServerConnection();
sc.ConnectionString = "Data Source=.;Initial Catalog=msdb;Integrated Security=SSPI;";
Server srv = new Server(sc);
i recuperarem els jobs:
JobCollection jobs = srv.JobServer.Jobs;
Un cop tenim els jobs podem optar per recorre'ls tots:
foreach (Job job in jobs){
//TODO insert code
}
O bé seleccionar un dels jobs per nom:
Job job = jobs[jobName];
Ara crearem un objecte ScriptingOptions per dir les característiques que volem a l'script. (https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.scriptingoptions.aspx)
ScriptingOptions so = new ScriptingOptions();
//so.ScriptDrops = true;
so.FileName = "c:\\Files\\job"+jobName+"_sp.txt";
En aquest cas hem triat que ens mostri la sentència de creació (scriptDrops per defecte) i que deixi el resultat en un fitxer amb el nom FileName.
En aquest moment ja podem invocar la funció Script per extreure el codi. També es pot invocar la funció Script sense ScriptingOptions i t'executa amb les opcions per defecte.
StringCollection stc = job.Script(so);
La variable stc contindrà l'script i, a més, també tindrem l'script al fitxer que hem assignat a so.FileName.
foreach (String st in stc)
{
System.IO.File.WriteAllText(@"C:\Files\job" + jobName + ".txt", st);
}
En teoria el fitxer jom<jobName>_sp.txt i job<jobName>.txt hauríen de contenir el mateix, però hi ha 1 diferència important: el fitxer generat per la funció Script acaba en GO, el generat a partir dels Strings no acaba en GO.
Aquesta diferència és molt important si després volem executar el codi a través del procedure sp_executesql ja que aquest procedure no accepta el GO i ens donaria error.
Això és tot per avui. Us copio tot el codi sencer per poder-lo utilitzar dins d'una Script Task al SSDT.
#region Help: Introduction to the script task
/* The Script Task allows you to perform virtually any operation that can be accomplished in
* a .Net application within the context of an Integration Services control flow.
*
* Expand the other regions which have "Help" prefixes for examples of specific ways to use
* Integration Services features within this script task. */
#endregion
#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Sdk.Sfc;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo.Agent;
using System.Collections.Generic;
using System.Collections.Specialized;
#endregion
namespace ST_c8347870d5494946bafacf702fb334f7
{
///
/// ScriptMain is the entry point class of the script. Do not change the name, attributes,
/// or parent of this class.
///
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region Help: Using Integration Services variables and parameters in a script
/* To use a variable in this script, first ensure that the variable has been added to
* either the list contained in the ReadOnlyVariables property or the list contained in
* the ReadWriteVariables property of this script task, according to whether or not your
* code needs to write to the variable. To add the variable, save this script, close this instance of
* Visual Studio, and update the ReadOnlyVariables and
* ReadWriteVariables properties in the Script Transformation Editor window.
* To use a parameter in this script, follow the same steps. Parameters are always read-only.
*
* Example of reading from a variable:
* DateTime startTime = (DateTime) Dts.Variables["System::StartTime"].Value;
*
* Example of writing to a variable:
* Dts.Variables["User::myStringVariable"].Value = "new value";
*
* Example of reading from a package parameter:
* int batchId = (int) Dts.Variables["$Package::batchId"].Value;
*
* Example of reading from a project parameter:
* int batchId = (int) Dts.Variables["$Project::batchId"].Value;
*
* Example of reading from a sensitive project parameter:
* int batchId = (int) Dts.Variables["$Project::batchId"].GetSensitiveValue();
* */
#endregion
#region Help: Firing Integration Services events from a script
/* This script task can fire events for logging purposes.
*
* Example of firing an error event:
* Dts.Events.FireError(18, "Process Values", "Bad value", "", 0);
*
* Example of firing an information event:
* Dts.Events.FireInformation(3, "Process Values", "Processing has started", "", 0, ref fireAgain)
*
* Example of firing a warning event:
* Dts.Events.FireWarning(14, "Process Values", "No values received for input", "", 0);
* */
#endregion
#region Help: Using Integration Services connection managers in a script
/* Some types of connection managers can be used in this script task. See the topic
* "Working with Connection Managers Programatically" for details.
*
* Example of using an ADO.Net connection manager:
* object rawConnection = Dts.Connections["Sales DB"].AcquireConnection(Dts.Transaction);
* SqlConnection myADONETConnection = (SqlConnection)rawConnection;
* //Use the connection in some code here, then release the connection
* Dts.Connections["Sales DB"].ReleaseConnection(rawConnection);
*
* Example of using a File connection manager
* object rawConnection = Dts.Connections["Prices.zip"].AcquireConnection(Dts.Transaction);
* string filePath = (string)rawConnection;
* //Use the connection in some code here, then release the connection
* Dts.Connections["Prices.zip"].ReleaseConnection(rawConnection);
* */
#endregion
///
/// This method is called when this script task executes in the control flow.
/// Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
/// To open Help, press F1.
///
public void Main()
{
try
{
String jobName = (String)Dts.Variables["name"].Value;
ServerConnection sc = new ServerConnection();
sc.ConnectionString = "Data Source=.;Initial Catalog=msdb;Integrated Security=SSPI;";
// Connect to the local, default instance of SQL Server.
Server srv = new Server(sc);
JobCollection jobs = srv.JobServer.Jobs;
Job job = jobs[jobName];
ScriptingOptions so = new ScriptingOptions();
so.Default = true;
//so.ScriptDrops = true;
so.FileName = "c:\\Files\\job"+jobName+"_sp.txt";
StringCollection stc = job.Script(so);
foreach (String st in stc)
{
String[] lines = new String[2];
String final= st.Substring(0, st.Length );
lines.SetValue("IF EXISTS (SELECT job_id FROM msdb.dbo.sysjobs WHERE name = N'"+jobName+"') EXEC msdb.dbo.sp_delete_job @job_name=N'" + jobName + "', @delete_unused_schedule=1", 0);
lines.SetValue(final, 1);
System.IO.File.WriteAllLines(@"C:\Files\job" + jobName + ".txt", lines);
MessageBox.Show(final);
}
/*foreach (Job job in jobs)
{
MessageBox.Show(job.Name);
}*/
}
catch(Exception e){
MessageBox.Show(e.Message);
}
Dts.TaskResult = (int)ScriptResults.Success;
}
#region ScriptResults declaration
///
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
///
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}