SSIS Script task not executing macro through SQL Agent (but it does through bids)
<p>Hello everyone,</p><p>I am having an issue with SQL Agent when executing a macro contained in a script task component. The script task actually opens an excel file, runs the macro, save and closes the file. </p><p>When
I execute the package via BIDS/Visual studio, it works like a charm. However, when i execute the package with SQL agent, the package runs successfully but it seems that the macro is not executed as the excel file has not been modified as it should have. Also,
the history log does not show any error messages. </p><p>Could </p>
Thanks!I did create a credential and a proxy too but still the macro is not executed.I have searched online for solutions but no one has experimented this kind of issue before it seems. Please have a look at the script task code:
Imports
Excel = Microsoft.Office.Interop.Excel
Imports
System
Imports
System.Data
Imports
System.Math
Imports
Microsoft.SqlServer.Dts.Runtime
<System.AddIn.AddIn(
"ScriptMain", Version:="1.0",
Publisher:="", Description:="")>
<System.CLSCompliantAttribute(
False)> _
Partial
Public
Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
End
Enum
Public
Sub Main()
Dim Macro_name
As
String
Dim ExcelObject
As
New Microsoft.Office.Interop.Excel.Application
Dim oBook
As Microsoft.Office.Interop.Excel.Workbook
Dim oBooks
As Microsoft.Office.Interop.Excel.Workbooks
Try
Macro_name =
"Macro001"
ExcelObject =
CType(CreateObject("Excel.Application"),
Excel.Application)
ExcelObject.Visible =
True
ExcelObject.UserControl =
False
ExcelObject.DisplayAlerts =
False
oBooks = ExcelObject.Workbooks
oBook =
CType(oBooks.Open("C\Book1.xls"),
Excel.WorkbookClass)
ExcelObject.Run(Macro_name)
Catch ex
As Exception
ExcelObject.Application.Quit()
ExcelObject.DisplayAlerts =
True
ExcelObject =
Nothing
End
Try
Dts.TaskResult = ScriptResults.Success
End
Sub
End
Class
Similar Messages
-
Term is not recognized when executing PowerShell Script through SQL Agent using CMDEXEC
I am trying to simply execute a PowerShell script that is stored in a file on a network drive through SQL Agent as a job. The script is a basic copy from one directory to another. I have run and successfully executed this from a command prompt outside
of SQL Agent. When I execute this through SQL Agent as a Operating System (CmdExec) command I am getting an error that the term is not recognized as the name of a cmdleet, function, script file or operable program. I have executed many different ways
put found an article to use double quotes in the network path which I have done with no success.
I am executing the following command as a job in SQL Agent:
PowerShell H:\"\PowerShell""\PS_Scripts\"\batchcopyFFLWithProgress.ps1 through SQL Agent job
I get the following error message:
04/21/2015 10:01:09,Copy FFL Files,Error,1,NY11266-LTW7E\JPLAPTOPSQL,Copy FFL Files,Copy FFL files,,Executed as user: NT Service\SQLAgent$JPLAPTOPSQL. H:\PowerShell\PS_Scripts\batchcopyFFLWithProgress.ps1 : The term 'H:\PowerShell\PS_Scripts\batchcopyFFLWithProgress.ps1'
is not recognized as the name of a cmdlet<c/> function<c/> script file<c/> or operable program. Check the spelling of the name<c/> or if a path was included<c/> verify that the path is correct and try again.
At line:1 char:1 + H:"\PowerShell\PS_Scripts"\batchcopyFFLWithProgress.ps1 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound:
(H:\PowerShell\P...ithProgress.p s1:String) []<c/> CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException. Process Exit Code 1. The step failed.,00:00:03,0,0,,,,0
Content of batchcopyFFLWithProgress.ps1 which has the PowerShell script:
$source=ls H:\SQLTest\Script\TestData\*.*
$i=1
$source| %{
[int]$percent = $i / $source.count * 100
Write-Progress -Activity "Copying ... ($percent %)" -status $_ -PercentComplete $percent -verbose
copy $_.fullName -Destination H:\test -Recurse
$i++
I have searched the internet and have not found any resolution to my error. If someone has experienced this error and found the resolution I would greatly appreciate your help.I have change the service account for SQL Agent to be my domain account as I have local admin rights to my laptop. I stopped and started the services for SQL Agent and than started the job to run which is copying locally to minimize any network drive
issues. I am still getting the same error message as it is showing that I am executing the job under my domain account? Any thoughts what it could be?
ErrorMsg
04/23/2015 11:21:06,Copy FFL Files,Error,1,ServerName\InstanceName,Copy FFL Files,Copy FFL files,,Executed as user: Domain\DomainAccount. \\ServerName\Test\PS_Script\batchcopyFFLWithProgress.ps1 : The term '\\ServerName\Test\PS_Script\batchcopyFFLWithProgress.ps1'
is not recognized as the name of a cmdlet<c/> function<c/> script file<c/> or operable program. Check the spelling of the name<c/> or if a path was included<c/> verify that the path is correct and try again. At
line:1 char:1 + \\ServerName\Test\PS_Script\batchcopyFFLWithProgress.ps1 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (\\ServerName...ithProgress.ps1:String)
[]<c/> CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException. Process Exit Code 1. The step failed.,00:00:02,0,0,,,,0
Script
$source=ls "\\ServerName\Test\TestData\*.*"
$i=1
$source| %{
[int]$percent = $i / $source.count * 100
Write-Progress -Activity "Copying ... ($percent %)" -status $_ -PercentComplete $percent -verbose
copy $_.fullName -Destination "\\ServerName\Test\test" -Recurse
$i++ -
Running a Select query against multiple sql servers using SSIS script task.
Hi Guys,
I need to fetch data from multiple sql servers using SSIS scirpt task inside a foreach container.
is there anyway i can build dynamic sql connections using ssis variables inside SSIS script task in each loop
Please guide me or refer any blogs so that i will try..
Thanks in advance.Your only options is using .net code, then it will be no different than using a console app in a loop.
using (SqlConnection connection = new SqlConnection(connectionString))
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
and so forth for each connection string
the connection string would come from the ForEach loop
Arthur My Blog -
NameSpace for XML But in SSIS Script Task
Hello,
I am creating an xml Document that pulls information from a staging table in sql. However the issue I am having is that i need a namespace or a start element to handle a ':' but i keep getting its not a hexadecimal blah blah.
I feel like I have tried everything for this.
So maybe someone can help me
writer.WriteStartDocument()
writer.WriteComment("edited with XMLSpy v2010 rel. 3 (http://www.altova.com) by MESMERiZE (MSM)")
writer.WriteComment("Samply XML file generated by XMLSpy v2010 rel. 3 (http://www.altova.com)")
So i have the comments show up fine but then i need it to show
<mssext:sendWarrantyContractBatch xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mssext="http://jlrint.com/mss/message/sendwarrantycontract/1" xsi:schemaLocation="http://jlrint.com/mss/message/sendwarrantycontract/1
FRS_000143-SendWarrantyContractMessages.xsd">
I can get the websites and all the xmlns to show up fine that is not the issue the issue is the mssext:sendWarrantyContractBatch
IS there any way to get the Colon to show up ??
Remember this is in a ssis script task with visual basic 2008 codecheck this link. it has a method specified in the comments section
http://blogs.lessthandot.com/index.php/datamgmt/dbprogramming/create-xml-files-out-of-sql-server-with/
Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page -
Convert ActiveX DTS script task to SSIS Script task - Please help
Hello,
I Have a ActiveX script that was used in a DTS package but I'm currently trying to convert all my DTS packages to SSIS.The script is tasked to run the package on a daily basis. Everything works fine except the ActiveX script. It gives an error on my DTSGlobalVariables.parent,
I looked up this error and changed it to "DTS.Variables("User::VariableName").Value", in
the SSIS script task (in VB) but now I'm getting error:
Microsoft.SqlServer.Dts.Runtime.DtsRuntimeException: The element cannot be found in a collection.
---> System.Runtime.InteropServices.COMException (0xC0010009): The element cannot be found in a collection.
bij Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSVariables100.get_Item(Object Index)
bij Microsoft.SqlServer.Dts.Runtime.Variables.get_Item(Object index)
--- Einde van intern uitzonderingsstackpad ---
bij Microsoft.SqlServer.Dts.Runtime.Variables.get_Item(Object index)
bij ST_f32fc12b60f34bebbbdfc0c5e5b40a96.vbproj.ScriptMain.Main()
--- Einde van intern uitzonderingsstackpad ---
bij System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
bij System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
bij System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
bij System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
bij System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
bij System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture)
I have tried to convert this ActiveX script into a SSIS script task in VB but I know hardly any VB... So I'm wondering what the best course of action for me is, should I try to convert it into the script task like I am trying now, if so, how do I make it
work?
Any help would be really really welcome.
This is the original ActiveX script that needs to be converted:
' Visual Basic ActiveX Script
Function Main()
Dim sEnvironm
Dim sServer
Dim sSourceFile
Dim sSourcePath
Dim sBackupPath
Dim sErrorPath
Dim sFileName
Dim sUDLPath
' Set vars
' First 2 are depending on the server and db
' FILL IN THE RIGHT VALUES
sEnvironm = "MON_Datamart"
sServer = "BrechtProesmans"
' --- DO NOT CHANGE ANYTHING BELOW THIS LINE ---
sSourceFile = "C:\Program Files\Microsoft SQL Server\MON_Datamart\SourceFiles\tbl_L00T1.txt"
sSourcePath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\SourceFiles\"
sBackupPath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\BackupFiles\"
sErrorPath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\ErrorFiles\"
sFileName = "tbl_L00T1.txt"
sUDLPath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\MON_Datamart.udl"
' Initial
FoundError = False
' Get a handle to the Package object.
Set oPackage = DTSGlobalVariables.Parent
' Update DTSConnections
Set oConnection = oPackage.Connections("tbl_L00T1.txt")
oConnection.DataSource = sSourceFile
Set oConnection = oPackage.Connections("Datamart")
oConnection.UDLPath = sUDLPath
Set oConnection = oPackage.Connections("Truncate")
oConnection.UDLPath = sUDLPath
' Update DTSTasks
Set oTask = oPackage.Tasks("DTSTask_DTSDataPumpTask_1").CustomTask
oTask.SourceObjectName = sSourceFile
oTask.DestinationObjectName = sEnvironm & ".dbo.stg_tbl_L00T1"
' Set Global vars
DTSGlobalVariables("SourcePath").Value = sSourceFile
DTSGlobalVariables("BackupPath").Value = sBackupPath
DTSGlobalVariables("ErrorPath").Value = sErrorPath
DTSGlobalVariables("FileName").Value = sFileName
' Clean up.
Set oTask = Nothing
Set oConnection = Nothing
Set oPackage = Nothing
Main = DTSTaskExecResult_Success
End FunctionSet a breakpoint and tell us on what line it dies, at the same time, you can inspect the variable values in the Auto window (if there are) as it merely perhaps is an issue with values not being passed in.
Arthur
MyBlog
Twitter -
How to Run SSIS Package through SQL AGENT Job
I am good with SSIS, I created a package which will load the excel files to SQL SERVER tables. To Implement this I wrote the C# code to extract the first sheet name only, and then
package will load the data present the first sheet only. The package working fine when i run this through BIDS. But the same package throwing error at C# code step when i am running this package through SQL AGENT JOB. When i searched for this, i have seen
many posts saying that, this is happening becoz of using Microsoft.interop.excel references inside the c# code. Please help me with this. Is there any alternate way in c# to extract the first sheet name(not based on ascending order) of an excel file with out
using interop. Or
How to configure SQL AGENT job to run suceessfully when using interop inside the code.
My UAT server is of 64 bit. And i have to run this in the same server.
I tried creating "Desktop" folder in "C:\Windows\System32\config\systemprofile\"
Error:Description: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object. at ST_ecfa668f250a45e18c95639c9ffd64d4.csproj.ScriptMain.Main()
--- End of inner exception stack trace --- at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr,
Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at
System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at System.Type.InvokeMember(String name, BindingFlags
invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture) at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript() End Error Error: 2015-02-27 11:24:00.23 Code: 0x00000001
Source: User Mail Description: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Data.SqlClient.SqlException: A network-related or instance-specific error
occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could
not open a connection to SQL Server) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String
host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString
connectionOptions, String newPassword, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword,
SqlConnection owningObject, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owning...
The package execution fa... The step failed
using System;
using System.Data;
using System.Diagnostics;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Data.OleDb;
using Microsoft.Office.Interop;
using System.Runtime.InteropServices;
namespace ST_ecfa668f250a45e18c95639c9ffd64d4.csproj
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
#region VSTA generated code
enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
#endregion
public void Main()
{ /*Passing the file path via User::File_Name Variable*/
string FileName = Dts.Variables["User::File_Name"].Value.ToString();
Microsoft.Office.Interop.Excel.Application xlApp = null;
Microsoft.Office.Interop.Excel.Workbook excelBook = null;
try
xlApp = new Microsoft.Office.Interop.Excel.Application();
excelBook = xlApp.Workbooks.Open(FileName, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
string[] excelSheets = new string[excelBook.Worksheets.Count];
int i = 0;
foreach (Microsoft.Office.Interop.Excel.Worksheet wSheet in excelBook.Worksheets)
excelSheets[i] = wSheet.Name;
i++;
Dts.Variables["User::WorkSheetName"].Value = excelSheets[0] + "$";
catch (Exception ex)
excelBook.Close(false, FileName, null);
Marshal.ReleaseComObject(excelBook);
string error = ex.Message;
finally
excelBook.Close(false, FileName, null);
Marshal.ReleaseComObject(excelBook);
Dts.TaskResult = (int)ScriptResults.Success;I installed office in my machine...but this doesn't solved my problem...
Finally i figured out the solution for this and it is working now, Here is the solution...!
Create the folder with name "Desktop" inside the below mentioned path
C:\Windows\SysWOW64\config\systemprofile\
But i really don't understand the logic behind this. Can someone explain it pls.... -
FormCalc script is not executed
Hi everybody,
I've developped a Pdf forms with FormCalc Script.
This script does works in the preview designer of SFP transaction but when i try to run the pdf forms through a specific program, the script is not executed.
Do you have any idea ?
The pdf is a ZCI layout.
My SAP platform is ECC 6.0Brice,
What is the type of form you are developing ? Interactive or Print.
My guess you be creating a Print form where dynamic scripting does not work.
Alternatively put following line of code in the script to see if the control is transferred to your event or not.
$host.messageBox("Inside event")
Chintan -
Hi,
we have scheduled scripts through crontab,but from few days these scripts are not executing,there is no problem with time entries in crontab because some of them are executing correctly,what can be possible reasons for the cronjobs to not to execute.we are using sun solaris sparc 64 bit.oracle 10.1.0.4I can't say without knowing what the script does. Maybe somebody changed the permissions on another directory that script needs, or maybe another file it needs is no longer available, or ???
Just suggesting a troubleshooting step. If you can run the script in a similar setup then you can eliminate the script as a likely problem. I didn't see anything on the crontab entry that looked to be a problem.
PS: "will the date change with the execution of cronjob or it remains the same."
No, the date on the cron daemon will stay the same. It just wakes up once a minute to check for things to do and kicks them off, it never restarts. -
Consuming Web Services in SSIS Script Task
Hello
Sorry for my English, I' ll try to explain my problem.
I am new to SSIS. Using this article http://blogs.msdn.com/b/dataaccesstechnologies/archive/2010/01/28/consuming-web-services-in-ssis-script-task.aspx I have tried to consume web service.
1. I have created proxy class using VS Command Prompt
2. A have added proxy class to Script Task
3. But when I want to create the instance of the proxy class, it can be accessed from the ScriptMain.cs.
I will be very pleased for the help!perhaps you missed this step:
--> Modify the code and add Credentials before calling the web method:
Public
SubMain()
Dim
ws As NewService1
ws.Credentials =
New System.Net.NetworkCredential("user name",
"password",
"domain name")
MsgBox("Square
of 2 = "& ws.Square(2))
Dts.TaskResult = Dts.Results.Success
End
Sub
Arthur
MyBlog
Twitter -
Got an (unlocked) iphone 4s from US and tried activating in India but it throws an error saying 'unable to activate bcos the activation server cannot be reached' ..I tried connecting to itunes through my laptop but it does not detect my iphone..pls help
mithaani wrote:
Got an (unlocked) iphone 4s from US
As kb1951 states, unless this phone was purchased directly from Apple, it is not officially unlocked. In the US, only Apple sells officially unlocked iPhones. The message you got generally means your phone was hacked to unlock it...jailbroken...Apple's servers have detected such & are preventing your phone from activating...there's nothing wrong with the activation servers.
You'll need a sim card from the carrier your phone is locked to in order to activate it. If you don't know what carrier, you'll have to call AppleCare in the US to determine this info. Be aware, US carriers will not authorize official unlocking unless you are a customer that used the phone on their network. Thus, there is most likely no way for you to get this phone officially unlocked.
Good luck. -
I buyed a new computer and photoshop was not working anymore, I reinstalled it but it does not accept my serial number@
What message do you get when you try to activate it?
-
SSIS ETL does not pick the file from Share point when it execute through SQL Agent job
I have created one SSIS packages, which pick the file from the Share point document library. its work successfully, once it execute through the VS project application.
But when i create a job in SQL Server Agent for this package then it does not pick the file and job getting fail.
Just for more update, SQL Server has been install in Cluster mode and using BIDS 2012 with SQl Server 2012.Hi PriyankGupta,
SQL Server Integration Services is not cluster awareness, and does not support failover from one cluster node to another. So, in your clustered environment, make sure SSIS is installed on each node in the cluster. In other word, SSIS must be installed on
the server where the SQL Server Agent job is created.
If you use any third party task/component or drivers, make sure they are installed on the SQL Server Agent job server. Besides, also pay attention to the protection level of the package as well as 32-bit or 64-bit runtime mode of the package. For more information,
please see:
http://social.technet.microsoft.com/Forums/systemcenter/en-US/e13c137c-1535-4475-8c2f-c7e6e7d125fc/how-do-i-troubleshoot-ssis-packages-failed-execution-in-a-sql-agent-job
If the issue persists, please post the error message in the job history for further analysis.
Regards,
Mike Yin
TechNet Community Support -
SQL 2008 R2 - SSIS C# Script Task - Not Setting Variable
OK... I am stumped. I am trying to set the variable "User::TicketDB_Get_SQL" from a Script Task since it is dynamic... and well it isn't working :(
I can see I am supposed to be setting the value, but when I do breaks and watch that variable the new value is not being set. Here is my C# code... Can someone look and see what the heck I might be doing wrong:
Microsoft SQL Server Integration Services Script Task
Write scripts using Microsoft Visual C# 2008.
The ScriptMain is the entry point class of the script.
using System;
using System.IO;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace ST_3542610d50a64788be84926d15e07f7b.csproj
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
#region VSTA generated code
enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
#endregion
public void Main()
//MessageBox.Show("Start VB");
//MessageBox.Show("Make ADO Connection");
SqlConnection sqlConn = new SqlConnection();
sqlConn = (SqlConnection)(Dts.Connections["ADO-DW-SSIS_Processing"].AcquireConnection(Dts.Transaction) as SqlConnection);
SqlConnection sqlTicketDBRowsConn = new SqlConnection();
sqlTicketDBRowsConn = (SqlConnection)(Dts.Connections["ADO-DW-SSIS_Processing"].AcquireConnection(Dts.Transaction) as SqlConnection);
//MessageBox.Show("Connected to ADO");
String newSelectSQL = null;
//bool fireAgain = false;
Variables vars = null;
try
Dts.VariableDispenser.LockForRead("User::Data_Warehouse_Max_Modified_Date");
Dts.VariableDispenser.LockForRead("User::Data_Warehouse_Prod_Table");
Dts.VariableDispenser.LockForRead("User::Modified_Date_Field");
Dts.VariableDispenser.LockForRead("User::TicketDB_Schema");
Dts.VariableDispenser.LockForRead("User::Table_Name");
Dts.VariableDispenser.LockForRead("User::Unique_ID_Field");
Dts.VariableDispenser.LockForRead("User::Data_Warehouse_Process_Table_Name");
Dts.VariableDispenser.LockForRead("User::Data_Warehouse_DB_Name");
Dts.VariableDispenser.LockForWrite("User::TicketDB_Get_SQL");
Dts.VariableDispenser.LockForWrite("User::Reprocess_Records");
Dts.VariableDispenser.GetVariables(ref vars);
//Dts.VariableDispenser.GetVariables(ref glvars);
String maxModDate = vars["User::Data_Warehouse_Max_Modified_Date"].Value.ToString();
String prodtable = vars["User::Data_Warehouse_Prod_Table"].Value.ToString();
String modField = vars["User::Modified_Date_Field"].Value.ToString();
String TicketDBSchema = vars["User::TicketDB_Schema"].Value.ToString();
String tablename = vars["User::Table_Name"].Value.ToString();
String uniqIDField = vars["User::Unique_ID_Field"].Value.ToString();
String procTable = vars["User::Data_Warehouse_Process_Table_Name"].Value.ToString();
String custName = vars["User::Data_Warehouse_DB_Name"].Value.ToString();
String Reprocess = "F";
String ReprocessDate = "0";
String ReprocessPrime = null;
String ReprocessVal = null;
Int16 count = 0;
#region Get List of Rows for TicketDB Query
String TicketDBRows = null;
String sqlTicketDBRowsQuery = "SELECT [TicketDB_Column_Name] " +
"FROM " + procTable + " " +
"WHERE " +
"[Import_Data_Warehouse] = 1 " +
"AND " +
"[TicketDB_Table_Name] = '" + tablename + "' " +
"ORDER BY [TicketDB_Column_Name]";
SqlCommand sqlTicketDBRowsCmd = new SqlCommand(sqlTicketDBRowsQuery, sqlTicketDBRowsConn);
SqlDataReader sqlTicketDBRowsReader = sqlTicketDBRowsCmd.ExecuteReader();
Int16 TicketDBrowcount = 0;
while (sqlTicketDBRowsReader.Read())
if (TicketDBrowcount > 0)
TicketDBRows += ", ";
TicketDBRows += " " + sqlTicketDBRowsReader.GetString(0) + " ";
TicketDBrowcount++;
#endregion
String Pattern = @"(\D)\s-\s(\d+)(\s-\s(.*)\s-\s(.*))?";
String ReProcessFile = null;
if (prodtable.Equals("Template")) {
ReProcessFile = "E:\\Templates\\Configs\\" + prodtable + "-Reprocess.txt";
else
ReProcessFile = "E:\\SSIS_Configs\\" + custName + "\\" + prodtable + "-Reprocess.txt";
#region Process Re-Process File
if (File.Exists(ReProcessFile))
//MessageBox.Show("File is found");
using (StreamReader sr = new StreamReader(ReProcessFile))
//MessageBox.Show("File has been opened");
string line;
while ((line = sr.ReadLine()) != null)
//MessageBox.Show("Found a Line: " + line);
Regex rgx = new Regex(Pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(line);
foreach (Match match in matches)
GroupCollection groups = match.Groups;
Reprocess = groups[1].Value;
ReprocessDate = groups[2].Value;
ReprocessPrime = groups[4].Value;
ReprocessVal = groups[5].Value;
//MessageBox.Show("Variables Set." + Environment.NewLine +
// "Reprocess: " + Reprocess + Environment.NewLine +
// "Reprocess Date: " + ReprocessDate + Environment.NewLine +
// "Reprocess Primary Field: " + ReprocessPrime + Environment.NewLine +
// "Reprocess Value Field: " + ReprocessVal);
//MessageBox.Show("End Processing File");
#endregion
#region Re-Proccess Rows
if (Reprocess.Equals("T"))
if (String.IsNullOrEmpty(ReprocessPrime) && String.IsNullOrEmpty(ReprocessVal))
else
//MessageBox.Show("Finished Getting Read Only Variables");
string sqlQuery = "SELECT TOP (1000) " + uniqIDField + " " +
"FROM " + prodtable + " " +
"WHERE " +
"[" + ReprocessVal + "] IS NULL " +
"AND " +
"[" + ReprocessPrime + "] IS NOT NULL " +
"ORDER BY [" + modField + "]";
//MessageBox.Show("sqlQuery: " + sqlQuery);
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
newSelectSQL = "SELECT " + TicketDBRows + " FROM " + TicketDBSchema + "." + tablename + " WHERE "; // + modField + " > '" + maxModDate + "' ";
while (sqlReader.Read())
if (count == 0)
newSelectSQL += " CASE_ID IN (";
if (count > 0)
newSelectSQL += ", ";
newSelectSQL += "'" + sqlReader.GetString(0) + "'";
count++;
newSelectSQL += ") OR " + modField + " > '" + maxModDate + "' ORDER BY " + modField + " ASC";
//sqlConn.Close();
if (count == 0)
//MessageBox.Show("Reprocess: " + Reprocess + Environment.NewLine + "Start Date: " + ReprocessDate);
newSelectSQL = "SELECT " + TicketDBRows + " FROM " + TicketDBSchema + "." + tablename + " " + "WHERE " + modField + " >= '" + ReprocessDate + "' ";
newSelectSQL += "ORDER BY " + modField + " ASC";
vars["User::Reprocess_Records"].Value = newSelectSQL.ToString();
//Dts.Variables["User::Reprocess_Records"].Value = "T";
else
//MessageBox.Show("NO Reprocess: " + Reprocess + Environment.NewLine + "Max Date: " + maxModDate);
newSelectSQL = "SELECT " + TicketDBRows + " FROM " + TicketDBSchema + "." + tablename + " " + "WHERE " + modField + " > '" + maxModDate + "' ";
newSelectSQL += "ORDER BY " + modField + " ASC";
#endregion
else
//MessageBox.Show("NO Reprocess: " + Reprocess + Environment.NewLine + "Max Date: " + maxModDate);
newSelectSQL = "SELECT " + TicketDBRows + " FROM " + TicketDBSchema + "." + tablename + " " + "WHERE " + modField + " > '" + maxModDate + "' ";
newSelectSQL += "ORDER BY " + modField + " ASC";
//MessageBox.Show("Maybe New SQL: " + newSelectSQL.ToString());
//Variables vars = null;
MessageBox.Show("Got Variable now lets set it to: " + newSelectSQL.ToString());
// Now you can use the variables
vars["User::TicketDB_Get_SQL"].Value = newSelectSQL.ToString();
MessageBox.Show("New SQL: " + vars["User::TicketDB_Get_SQL"].Value.ToString());
//vars.Unlock();
catch (Exception ex)
//MessageBox.Show("Error :(");
// Throw an exception or add some logging
//this.Dts.Events.FireInformation(1, "Something Went Wrong", newSelectSQL.ToString(), "", 0, ref fireAgain);
throw ex;
//Dts.TaskResult = (int)ScriptResults.Failure;
finally
//MessageBox.Show("Trying to UNLock Variable");
// Release the locks (even if your script task fails)
vars.Unlock();
//Dts.Variables["User::TicketDB_Get_SQL"].Value = newSelectSQL;
//MessageBox.Show("New SQL: " + Dts.Variables["User::TicketDB_Get_SQL"].Value);
Dts.TaskResult = (int)ScriptResults.Success;
So that is my code... when I run it, line # 217 shows what the new Variable should be... However when I hit line # 220 it isn't set and if I let it continue I am watching the variables and it isn't getting set. I am confused... anyone??
Billy S.Hi Billy S,
Thank you for sharing your solutions and experience here. It will be very beneficial for other community members who have similar questions.
Thanks,
Eileen
TechNet Subscriber Support
If you are
TechNet Subscription user and have any feedback on our support quality, please send your feedback
here -
I have a script task written in C# that creates an array of strings "arrayFields" after parsing a text file. It saves the array of strings in a DTS variable.
Each row in array represents a row is comma separated and is a row that must be inserted into a table. For example,
X and Z are fields in the table
X1, X2,....Xn
Z1,Z2,...Zn
I am using a Foreach Loop to grab each row and then Execute SQL Task to take each row from the array and insert each field per row in a table,
The SQL is something like,
INSERT dbo.table values(field1, field2,...fieldn) arrayFields?
What should this this INSERT look like?I guess you implemented
Shredding a Recordset
Based on what I understood (correct me if I am wrong) you have difficulties mapping the input parameters, if so here is the guide
http://www.sqlis.com/sqlis/post/The-Execute-SQL-Task.aspx
In short it might look like
INSERT dbo.table (ColumnA, ColumnB,...) VALUES (?,?...)
The syntax for the T-SQL INSERT is http://technet.microsoft.com/en-us/library/dd776381%28v=sql.105%29.aspx
Arthur
MyBlog
Twitter -
Getting Error while trying to execute SSIS package through sql agent
Hi,
I have created a package in SSIS 2008.
I have created sql Agent job which runs perfectly on my Pc.
I tried to create anew job on another pc which doesnot have SSIS.
When i tried to run the Job,
i am getting folowing error:
Executed as user: LT-MAGFIH$. tion. End Error DTExec: The package execution returned DTSER_FAILURE (1). Started: 8:51:31 PM Finished: 8:51:35 PM Elapsed: 4.024 seconds. The package execution failed. The step failed.
Please let me now how can i solve.Hi AjayChigurupati,
I would suggest you check you are install or use the dtexec utility correctly:
On a 64-bit computer, Integration Services installs a 64-bit version of the
dtexec utility (dtexec.exe). If you have to run certain packages in 32-bit mode, you will have to install the 32-bit version of the
dtexec utility. To install the 32-bit version of the
dtexec utility, you must select either Client Tools or Business Intelligence Development Studio during setup.
By default, a 64-bit computer that has both the 64-bit and 32-bit versions of an Integration Services command prompt utility installed will run the 32-bit version at the command prompt. The 32-bit version runs because the directory path for the 32-bit
version appears in the PATH environment variable before the directory path for the 64-bit version. (Typically, the 32-bit directory path is
<drive>:\Program Files(x86)\Microsoft SQL Server\100\DTS\Binn, while the 64-bit directory path is
<drive>:\Program Files\Microsoft SQL Server\100\DTS\Binn.)
For detail information, please see:
http://technet.microsoft.com/en-us/library/ms162810(v=sql.105).aspx
To using SQL Server Agent to Run a Package, please refer to the steps in th article below:
http://technet.microsoft.com/en-us/library/ms138023(v=sql.105).aspx
If you have any feedback on our support, please click
here.
Elvis Long
TechNet Community Support
Maybe you are looking for
-
Audio works screen is black model 50L5200U
We have had our 50" LED 50L5200U tv for 5 months or so. We just moved it to another room and now the screen is black. At first audio wasn't working either so we left it unplugged for one hour and when we turned it back on the audio was working but th
-
Importing digital photographs in FCP
I recently imported two series of digitalized pictures in two different FCP projects. In the first case, the MPEG2 compression gave excellent results. In the second case, the quality was not so good as in the first time.... In both cases, the size of
-
My MacBook keyboard is stuck on caps and if I press comma or full stop I get < and >. Im speaking to apple & they tellin me it has to be collected to be fixed!! Surely its a matter of just changing settings or something? Please help!!
-
Patched workspace now reports export with %20 as spaces
Fully patched our Workspace/Financial reporting. Now we notice that if we do a report export to Excel a report that use to export like this: Business Line by Product.xls now exports like this: Business%20Line%20by%20Product.xls anyone else found this
-
Variable Frame Rate on H.264 output
I am using AE CS6 (cloud version). I am trying to render compositions to 1080p mp4. Each time the comp appears to render fine. But bringing it into my NLE crashes my NLE. I brought the media into MediaInfo (app from SourceForge that shows everythi