Pass value from SQL agent job step

Hi 
I have created one SSIS package and I am scheduling the same using SQL Agent job. Now I want to pass one value from SQL job agent and want to use that value in SSIS package and then run that package.  Can someone point to the solution.
Aniruddha http://aniruddhathengadi.blogspot.com/

I have created one parameter on SSIS package named strValue and assigned a empty value "". After that I have created one SQL job and step wherein I have set the value to "Nike" for parameter under Parameters tab.
Now I am expecting Nike value which I have set on SQL job step should get reflected on SSIS package when I am running my job. Am I doing anything wrong ?
Aniruddha http://aniruddhathengadi.blogspot.com/
Not sure what's going wrong but you can have quick look at below step by step tutorial:
Parameterizing Connections and Values at Runtime Using SSIS Environment Variables (via SQL Agent)
Cheers,
Vaibhav Chaudhari

Similar Messages

  • SSIS - Change Config File Path LOCATION in SQL Agent Job Step (NOT USING DTEXEC)

    SSISers;
    I am not new to ssis but am trying to deal with promoting of ssis config files differently for a specific project. We are using SQL 2008 R2.
    As a standared pattern used for years, we just use SQL Agent, build a job step for the ssis package, add the ssis package as SQL Integration Services Package type from fileshare (not using Integration Services), and add the necessary production
    config files in the configutation tab of the job step. Easy.  We do not execute our packages with DTEXEC command line.
    A new project has the developers leaving the config files in the package - not removing the config files for deployment. Is there a way to override JUST THE CONFIG FILE PATH LOCATION in the job step for ssis package? Remember, we are NOT using dtexec. 
    I was told that /SET might do it but I do not see a good example anywhere of hooking this in and how it works for a CONFIG FILE PATH LOCATION - I see variable overrides but not CONFIG FILE PATH LOCATION. The packages were written with Absolute config file
    path and not Relative path.
    Please understand that my goal is to let them leave the packages as is, we move the config files to the production sever and all we have to do is flip the location of where the config files are sitting for the ssis pacakge to look for them.  We would
    rather NOT have to use DTEXEC command  line with the job step for reasons that I do no need to get into on this forum.
    Any suggestions are appreciated.

    Hi mg30,
    There is no way to overwrite the XML configurations file just through modifying the SQL Server Agent job steps.  The Dtexec utility will apply the default package configurations for the second time after applying the options specified in the command
    lines or other package configurations configured in the job step.
    If the package is not deployed/installed, the Dtexec utility looks for the XML configurations file according to the file path defined in the Package Configurations Organizer window. In this situation, you need to either disable the package configurations
    or modify the XML file path in the BIDS.
    If the package is already deployed/installed, you need to modify the package as above or re-specify the install folder for the package configurations file. 
    Regards,
    Mike Yin
    If you have any feedback on our support, please click
    here
    Mike Yin
    TechNet Community Support

  • How to pass parameters to sql agent job run configured ssis package

    Hi all,
    I have a big problem at my small project.
    I build my SSIS package that get its variables values from a configuration file..
    and when i build a SQL agent job to run this package in a schedule i set the values of variables in it .. but in run-time the package still get its parameters from the configuration file !??
    any help please ?

    >SQL agent job to run this package in a schedule i set the values of variables in it
    One way, setup a configuration table for the package. Let the package read the values for the variables from there.
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Can't edit SQL Agent job step

    Hello. In SQL 2005 Enterprise I've added a user to SqlAgentUseRole in msdb. They can create a job but cannot later go back and edit a step; everything is grayed out. I saw this article about an error in SQL 2008 that's been fixed in 2008 CU3.
    http://support.microsoft.com/kb/2315727
    I'm not sure if this is the same issue. If it's a different issue, does anyone know if it's been addressed in SQL 2012?
    Ken

    This issue is due to limited rights on SqlAgentUseRole in msdb, user can Create/modify/delete only owned jobs
    As mentioned in below link:
    http://technet.microsoft.com/en-us/library/ms188283.aspx
    Further, provide access on some msdb procedures as discussed in below thread:
    sp_update_job
    sp_update_jobschedule
    sp_update_jobstep
    http://social.msdn.microsoft.com/Forums/en-US/c62b61a0-7f66-4cb9-a5a6-577d5f73e8aa/permissions-to-modify-sql-agent-jobs?forum=sqlsecurity
    Please click the Mark as answer button and vote as helpful if this reply solves your problem

  • SQL Agent job step - SSIS package - adding a config file - will it override the one that the package specifies?

    If I setup a job step to run a package and set the config file location on the "Configurations" tab, will that override the config file that the SSIS package is configured to use?  Or is this a "cumulative" type configuration option?
    I typically have my config file mixed in with my project files, but that path wont exist on the server.

    Hi Shiftbit,
    ETL vs ELT is right.
    In SSIS 2005, the DTExec utility loads and runs the package, events occur in the following order:
    The package file is loaded.
    The configurations specified in the package at design time are applied in the order specified in the package (except for Parent Package Variables).
    Any options specified from the command line are applied. Any configurations specified on the command line overwrite the current values; however, they do not trigger a reload of the configurations if a changed value impacts a configuration dependency. For
    example, if the connection string used for SQL Server configurations is updated from the command line at run time, the package will still retain any other values from the design-time SQL Server configuration database.
    Parent Package Variable Configurations are applied.
    The package is run.
    In SSIS 2008 and higher, utility loads and runs the package, events occur in the following order:
    The dtexec utility loads the package.
    The utility applies the configurations that were specified in the package at design time and in the order that is specified in the package. (The one exception to this is the Parent Package Variables configurations. The utility applies these configurations
    only once and later in the process.)
    The utility then applies any options that you specified on the command line.
    The utility then reloads the configurations that were specified in the package at design time and in the order specified in the package. (Again, the exception to this rule is the Parent Package Variables configurations). The utility uses any command-line
    options that were specified to reload the configurations. Therefore, different values might be reloaded from a different location.
    The utility applies the Parent Package Variable configurations.
    The utility runs the package.
    So, we can see that no matter we use SSIS 2005 which applies the Configurations once or use SSIS 2008 (or higher) which applies the configurations twice, the configurations specified in the command line will affect and not be overwritten by the configurations
    specified at design-time.
    Reference:
    http://technet.microsoft.com/en-us/library/ms141682(v=sql.110).aspx.
    Regards,
    Mike Yin
    TechNet Community Support

  • How can I pass value from sql query to unix script

    I am new to oracle/unix.
    I want to write a simple script to find max date from a table and then pass date into a variable in a korn shell script.
    sql is select max(date) from table;
    how can I pass that value in unix shell as a variable. Thanks

    I use to code like this.
    Enjoy Scripting.
    cmd.sql
    select sysdate from dual;
    exit
    db.sh
    #! /usr/bin/ksh
    . ~oracle/.orapaths
    dbdate=$(sqlplus -S user/pwd@servicename @cmd.sql)
    echo $dbdate
    Run shell scripts
    ./db.sh
    SYSDATE --------- 19-JAN-07

  • How to pass values to SQL server Agent Job which internally calls SSIS

    Hi,
    I have a requirement where i need to call remotely SSIS package from ASPX. After following MSDN form, I have creaed one SQL server agent job and calling that job from ASPX. I am ablt call SQL server agent job from ASPX. Only issue i am facing is: I need
    to pass 2 variables from ASPX to SQL Agent job so that from Job i can map the same to SSIS Package.
    I am using system SP (sp_start_job) for calling SQL server agent job as mentioned in MSDN forum.
    below is the code , which i am using to call SQL serve agent job.
    Code:
    SqlConnection
    jobConnection;
    SqlCommand jobCommand;
    SqlParameter jobReturnValue;
    SqlParameter jobParameter;
    int jobResult;
                    jobConnection =
    new
    SqlConnection("Server=ServerName;Initial
    Catalog=msdb;Integrated Security=SSPI;user id=username;Password=password");
                    jobCommand =
    new
    SqlCommand("sp_start_job",
    jobConnection);
                    jobCommand.CommandType =
    CommandType.StoredProcedure;
                    jobReturnValue =
    new
    SqlParameter("@RETURN_VALUE",
    SqlDbType.Int);
                    jobReturnValue.Direction =
    ParameterDirection.ReturnValue;
                    jobCommand.Parameters.Add(jobReturnValue);
                    jobParameter =
    new
    SqlParameter("@job_name",
    SqlDbType.VarChar);
                    jobParameter.Direction =
    ParameterDirection.Input;
                    jobCommand.Parameters.Add(jobParameter);
                    jobParameter.Value =
    "ImportCMTData";
                    jobConnection.Open();
                    jobCommand.ExecuteNonQuery();
                    jobResult = (
    Int32)jobCommand.Parameters["@RETURN_VALUE"].Value;
                    jobConnection.Close();
    switch (jobResult)
    case 0:
    Console.WriteLine("SQL
    Server Agent job, RunSISSPackage, started successfully.");
    break;
    default:
    Console.WriteLine("SQL
    Server Agent job, RunSISSPackage, failed to start.");
    break;
    Console.Read();
    Thanks
    Pankaj

    "3-4 concurrent users are calling the SSIS package from ASPX page" this is not a proper design
    If the data is being ingested than it is likely that this concurrency will lead to one of the packages die
    What you shell do is to just queue the data ingress/processing.
    In general, again, packages should not be called from ASP web pages, SSIS is ETL-server side technology there is nothing signalling back to the user whether it was successful. The proper way is to write a REST service or alike. 
    Arthur
    MyBlog
    Twitter

  • Script fails when passing values from pl/sql to unix variable

    Script fails when passing values from pl/sql to unix variable
    Dear All,
    I am Automating STATSPACK reporting by modifying the sprepins.sql script.
    Using DBMS_JOB I take the snap of the database and at the end of the day the cron job creates the statspack report and emails it to me.
    I am storing the snapshot ids in the database and when running the report picking up the recent ids(begin snap and end snap).
    From the sprepins.sql script
    variable bid number;
    variable eid number;
    begin
    select begin_snap into :bid from db_snap;
    select end_snap into :eid from db_snap;
    end;
    This fails with the following error:
    DB Name DB Id Instance Inst Num Release Cluster Host
    RDMDEVL 3576140228 RDMDEVL 1 9.2.0.4.0 NO ibm-rdm
    :ela := ;
    ERROR at line 4:
    ORA-06550: line 4, column 17:
    PLS-00103: Encountered the symbol ";" when expecting one of the following:
    ( - + case mod new not null <an identifier>
    <a double-quoted delimited-identifier> <a bind variable> avg
    count current exists max min prior sql stddev sum variance
    execute forall merge time timestamp interval date
    <a string literal with character set specification>
    <a number> <a single-quoted SQL string> pipe
    The symbol "null" was substituted for ";" to continue.
    ORA-06550: line 6, column 16:
    PLS-00103: Encountered the symbol ";" when expecting one of the following:
    ( - + case mod new not null <an identifier>
    <a double-quoted delimited-identifier> <a bind variable> avg
    count current exists max min prior sql stddev su
    But when I change the select statements below the report runs successfully.
    variable bid number;
    variable eid number;
    begin
    select '46' into :bid from db_snap;
    select '47' into :eid from db_snap;
    end;
    Even changing the select statements to:
    select TO_CHAR(begin_snap) into :bid from db_snap;
    select TO_CHAR(end_snap) into :eid from db_snap;
    Does not help.
    Please Help.
    TIA,
    Nischal

    Hi,
    could it be the begin_ and end_ Colums of your query?
    Seems SQL*PLUS hs parsing problems?
    try to fetch another column from that table
    and see if the error raises again.
    Karl

  • SQL Server Agent Job Step: Can I run in single step?

    Hi:
    I have a SSIS package that I am running from a SQL Agent job. I have to run a msdb Stored procedure first and then run the package. So I have created 2 steps. step-1, type =Tra-SQL where I am running my Stored Procedure. And then step-2, type= Integration
    Services which is running the package. I am attaching a config file here too. Is there a simple way to do these 2 steps in just 1 single step without too much complexities. 
    In the step-1 , SQl command=EXEC MySQlProcedure
    In the step-2 , by default the commandline=/SQL "MyPackage" /SERVER MySqlSer /CONFIGFILE "MyDataConfig.dtsConfig" /CHECKPOINTING OFF /REPORTING E
    Thanks.

    The stored procedure actually gives permission to any user who wants to run the job. I found only I (the creater) and DBA can run the job but other users could not. So I asked the DBA to set it up and he then created this SP. Is there any other way where
    I can give access to every user or only DBA can do it?

  • Management Studio Crashing When Adding SSIS Step to SQL Agent Job

    Hi
    I am running Windows Server 2012, SQL Server 2012 SP2 CU2, SQL Server Management Studio 2012 and Visual Studio 2012.
    I have existing SQL Agent Jobs that run SSIS packages and they all currently work. However, if I try to edit them or add a new job that uses a SSIS package Management Studio will crash.  I was having this problem a couple weeks ago when I was still
    on SQL Server 2012 SP1 CU9, so I updated to SQL Server 2012 SP2 CU2 and the problem went away for a couple weeks and I was able to add new SQL Agent jobs that run SSIS packages.  But now it issue is back and there are no new updates to try and fix it.
    Has anyone seen this before and found a reliable fix to it?
    Steps to cause crash:
    1) Open new SQL Agent Job
    2) Select Steps and add a New Step
    4) Change the job type to SQL Server Integration Services Package.
    5) SSMS Crashes
    Error Message Below:
    ===================================
    The type initializer for '<Module>' threw an exception. (SqlManagerUI)
    Program Location:
       at Microsoft.SqlServer.Management.SqlManagerUI.DTSJobSubSystemDefinition.Microsoft.SqlServer.Management.SqlManagerUI.IJobStepPropertiesControl.Load(JobStepData data)
       at Microsoft.SqlServer.Management.SqlManagerUI.JobStepProperties.UpdateJobStep()
       at Microsoft.SqlServer.Management.SqlManagerUI.JobStepProperties.typeList_SelectedIndexChanged(Object sender, EventArgs e)
       at System.Windows.Forms.ComboBox.OnSelectedIndexChanged(EventArgs e)
       at System.Windows.Forms.ComboBox.WmReflectCommand(Message& m)
       at System.Windows.Forms.ComboBox.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.Control.SendMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.Control.ReflectMessageInternal(IntPtr hWnd, Message& m)
       at System.Windows.Forms.Control.WmCommand(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ContainerControl.WndProc(Message& m)
       at System.Windows.Forms.UserControl.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
       at System.Windows.Forms.Control.DefWndProc(Message& m)
       at System.Windows.Forms.Control.WmCommand(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ComboBox.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.RunDialog(Form form)
       at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
       at System.Windows.Forms.Form.ShowDialog()
       at Microsoft.SqlServer.Management.SqlManagerUI.JobSteps.newJobStep_Click(Object sender, EventArgs e)
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.RunDialog(Form form)
       at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
       at System.Windows.Forms.Form.ShowDialog()
       at Microsoft.SqlServer.Management.SqlMgmt.RunningFormsTable.RunningFormsTableImpl.ThreadStarter.StartThread()
    ===================================
    The C++ module failed to load.
     (DTEParseMgd)
    Program Location:
       at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* )
       at .cctor()
    ===================================
    Index was outside the bounds of the array. (DTEParseMgd)
    Program Location:
       at _getFiberPtrId()
       at <CrtImplementationDetails>.LanguageSupport._Initialize(LanguageSupport* )
       at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* )
    Thanks,
    Anthony

    I ended up being able to work around this without having to recreate everything on a Windows Server 2008 R2. I did this by setting up an azure point to site VPN from
    my computer to the Windows Server 2012 hosted on azure.  I was then able to connect SSMS from my computer to the Azure VM allowing me to create and edit new SQL Agent jobs that run SSIS packages. Here are the steps to do this
    1) Connect to the VPN from another machine besides the server.
    2) Open SSMS using the runas.exe command with the Domain\User Name of a Windows account on the server.
    - Ex. Runas.exe /netonly /user:DOMAIN\USER "C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\Ssms.exe"
    2) Connect to the VM's Database Engine using its internal IP address and the port that SQL Server is listening on (default is 1433) and a SQL Login
    setup on the server.
    -Ex IP, 10.0.0.1,1433
    3) Create a new job with the type SQL Server Integration
    Services Package. Select the package source (SSIS Catalog). I could not get the server to be automatically discovered here so enter the server’s internal IP address and select the package you want to run.
    4) Right click the new SQL Agent Job and choose Script Job As, CREATE To, New Query Window. This is the script to create the
    SQL Agent Job and it needs to be edited to contain the Name of the server on the internal IP address that was used earlier.
    5) Edit the @command= line of the script to use the server name. Change the highlighted part below to the server name.
    - Ex . @command=N'/ISSERVER "\"\SSISDB\PACKAGELOCATION\"" /SERVER
    "\"10.0.0.1\"" /Par "\"$ServerOption::LOGGING_LEVEL(Int16)\"";1 /Par "\"$ServerOption::SYNCHRONIZED(Boolean)\"";True /CALLERINFO SQLAGENT /REPORTING E',
                - Change to this
                            - @command=N'/ISSERVER "\"\SSISDB\PACKAGELOCATION\""
    /SERVER SERVERNAME /Par "\"$ServerOption::LOGGING_LEVEL(Int16)\"";1 /Par "\"$ServerOption::SYNCHRONIZED(Boolean)\"";True /CALLERINFO SQLAGENT /REPORTING E',
    6) Now change the name of the package in the script and run it. Now the new package can be edited in the GUI to change things like the schedule and alerts. Also you
    can edit any existing packages.

  • 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

  • How to create a package/sql agent job to monitor a table constantly

    I have a situation like this: there is a log table. once a while, there will be a row inserted into this log table.  What i'd like to do is to create a ssis package/sql agent job, to monitor this log table.  As soon as a new row got inserted
    into the log table, do something process it (process time might be as long as a few minutes).  Timing is quite important here.  I'd like to make sure the new row get processed as soon as it got inserted into the log table (so I don't like the ideas
    to schedule the sql agent job to run every 5 minutes, or something like that).  What is the best way to achive this?  Thanks a lot in advance!
    Tim

    Hi,
    There is one System Stored Procedure: dbo.sp_Start_job
    Which excepts values are like :-
      @job_name    sysname          = NULL,
      @job_id      UNIQUEIDENTIFIER = NULL,
      @error_flag  INT              = 1,    -- Set to 0 to suppress the error from sp_sqlagent_notify if SQLServerAgent is not running
      @server_name sysname          = NULL, -- The specific target server to start the [multi-server] job on
      @step_name   sysname          = NULL, -- The name of the job step to start execution with [for use with a local job only]
      @output_flag INT              = 1     -- Set to 0 to suppress the success message
    First Create one Trigger on your table which call above Store Procedure
    Trigger is look like below:-
    ALTER TRIGGER dbo.MyTrigger
        ON  dbo.MyTable       
        AFTER INSERT     
    AS       
        BEGIN         
            SET NOCOUNT ON;
            DECLARE @MyTableTypeTVP AS MyTableType;
            INSERT INTO @MyTableTypeTVP(job_name, job_id, @error_flag ,@server_name,@step_name,@output_flag)
            SELECT 'Your JOb Name',generate UNIQUEIDENTIFIER,1,'Localhost','Any Step if',1
            EXEC [dbo].[sp_start_job] @MyTableTypeTVP;
        END
    Thanks
    Prasad

  • Using Powershell to execute DBCC CheckDB from SQL Agent.

    So, I have a weird situation that I think is tied tot he resource group and powershell, but I am having trouble determining if it is that or not. I run DBCC CheckDB using a resource pool and a secondary account. The account has permissions to do the work
    and if I log onto the server and run the procedure locally it runs fine in the resource pool configuration. However, when I kick it from the SQL Agent job using the powershell step, it only does checkDB on the first 3 system databases and then stops once it
    hits a user database. I am not seeing any errors or messages, it just stops. I ran profiler and I see it do the work, get to the first user database, issues this statement from DBCC, then just stops, and the job ends.
    SELECT @BlobEater = CheckIndex (ROWSET_COLUMN_FACT_BLOB)
    FROM { IRowset 0xD0936A7902000000 }
    GROUP BY ROWSET_COLUMN_FACT_KEY
    >> WITH ORDER BY
      ROWSET_COLUMN_FACT_KEY,
      ROWSET_COLUMN_SLOT_ID,
      ROWSET_COLUMN_COMBINED_ID,
      ROWSET_COLUMN_FACT_BLOB
    OPTION (ORDER GROUP)
     I am not doing anything special in my code that would limit which databases to process. As I said earlier, executing the call to the procedure from a query window runs as expected and processes all of the databases.
    Here is the Agent Code calling powershell:
    [string] $DayOfWeek = ""
    $DayOfWeek = (get-date).DayOfWeek.ToString()
    $DayOfWeek
    if ($DayOfWeek -eq 'Sunday')
    invoke-sqlcmd -database sysadm -serverinstance HQIOSQLDEV01\DEV01 "exec ConsistencyCheck.upConsistencyCheck NULL, 'N', 'Y', 'N', 'N', 'N'"
    else
    invoke-sqlcmd -database sysadm -serverinstance HQIOSQLDEV01\DEV01 "exec ConsistencyCheck.upConsistencyCheck NULL, 'Y', 'N', 'N', 'N', 'N'"
    John M. Couch

    There are 3 additional databases. The last known good is today as I am able to execute the procedure via query window just fine. It is only when executed from a SQL Agent job as above that it stops after only doing the System Databases. The largest database
    is 130GB in size, with the largest table being 62 GB.
    -- Create Procedures
    raiserror('Creating Procedure ''%s''', 0, 1, '[ConsistencyCheck].[upConsistencyCheck]')
    go
    /*==============================================================================
    Procedure: upConsistencyCheck
    Schema: ConsistencyCheck
    Database: SysAdm
    Owner: dbo
    Application: dbo
    Inputs: Catalogue : nvarchar(128) : NULL = All Databases
    Physical Only : nchar(1) : Y/N, NULL = N
    Data Purity : nchar(1) : Y/N, NULL = N
    No Index : nchar(1) : Y/N, NULL = N
    Extended Logical Checks : nchar(1) : Y/N, NULL = N
    Table Lock : nchar(1) : Y/N, NULL = N
    Outputs: (0 = Success, !=0 = failure)
    Result Set: N/A
    Usage: declare @ii_Rc int
    ,@invc_Catalogue nvarchar(128)
    ,@inc_PhysicalOnly nchar(1)
    ,@inc_DataPurity nchar(1)
    ,@inc_NoIndex nchar(1)
    ,@inc_ExtendedLogicalChecks nchar(1)
    ,@inc_TabLock nchar(1)
    select @invc_Catalogue = NULL
    ,@inc_PhysicalOnly = 'Y'
    ,@inc_DataPurity = 'N'
    ,@inc_NoIndex = 'N'
    ,@inc_ExtendedLogicalChecks = 'N'
    ,@inc_TabLock = 'N'
    exec @ii_Rc = ConsistencyCheck.upConsistencyCheck @invc_Catalogue
    , @inc_PhysicalOnly
    , @inc_DataPurity
    , @inc_NoIndex
    , @inc_ExtendedLogicalChecks
    , @inc_TabLock
    print 'Return Code: ' + convert(varchar, @ii_Rc)
    Description: This Procedure is used to run DBCC CheckDB on 1 or all Databases
    on the existing instance.
    Version: 1.00.00
    Compatability: SQL Server 2008 (100)
    Created By: John M. Couch
    Created On: 04-26-2012
    ================================================================================
    Notes
    1. Some logic was taken directly from Ola Hallengren's Maintenance Script.
    http://ola.hallengren.com
    ================================================================================
    History: (Format)
    When Who Version Code Tag What
    04-26-2012 John Couch 1.00.00 (None) Initial Revision
    ==============================================================================*/
    alter procedure ConsistencyCheck.upConsistencyCheck (@invc_Catalogue nvarchar(128)
    ,@inc_PhysicalOnly nchar(1)
    ,@inc_DataPurity nchar(1)
    ,@inc_NoIndex nchar(1)
    ,@inc_ExtendedLogicalChecks nchar(1)
    ,@inc_TabLock nchar(1)) as
    /*==============================================================================
    Variable Declarations & Temporary Tables
    ==============================================================================*/
    declare @li_Rc int = 0
    ,@lnvc_ExecutedBy nvarchar(128) = user_name()
    ,@ldt_ExecutedOn datetime = getdate()
    ,@lnvc_Catalogue nvarchar(128) = @invc_Catalogue
    ,@lnc_PhysicalOnly nchar(1) = coalesce(@inc_PhysicalOnly, 'N')
    ,@lnc_DataPurity nchar(1) = coalesce(@inc_DataPurity, 'N')
    ,@lnc_NoIndex nchar(1) = coalesce(@inc_NoIndex, 'N')
    ,@lnc_ExtendedLogicalChecks nchar(1) = coalesce(@inc_ExtendedLogicalChecks, 'N')
    ,@lnc_TabLock nchar(1) = coalesce(@inc_TabLock, 'N')
    ,@lnvc_Instance nvarchar(128) = cast(serverproperty('ServerName') as nvarchar)
    ,@lnvc_Version nvarchar(40) = cast(serverproperty('ProductVersion') as nvarchar)
    ,@lnvc_Edition nvarchar(40) = cast(serverproperty('Edition') as nvarchar)
    ,@li_Compatibility int
    ,@ldt_CreateDate datetime
    ,@lnvc_UserAccess nvarchar(35)
    ,@lnvc_StateDescription nvarchar(35)
    ,@lnvc_PageVerifyOption nvarchar(35)
    ,@lti_IsReadOnly tinyint
    ,@lti_IsInStandBy tinyint
    ,@lnvc_Recipients nvarchar(2000) = '[email protected]'
    ,@lnvc_Subject nvarchar(128)
    ,@lnvc_ErrorMessage nvarchar(4000)
    ,@lnvc_SQL nvarchar(max)
    ,@lnvc_ManualSQL nvarchar(max)
    ,@lnvc_Query nvarchar(2048)
    ,@li_ConsistencyCheckID int
    ,@ldt_ExecutionStart datetime
    ,@ldt_ExecutionFinish datetime
    declare @ltbl_Catalogue table (Catalogue sysname
    ,CompatibilityLevel int
    ,CreateDate datetime
    ,UserAccess nvarchar(35) -- MULTI_USER, SINGLE_USER, RESTRICTED_USER
    ,StateDescription nvarchar(35) -- ONLINE, RESTORING, RECOVERING, RECOVERY_PENDING, SUSPECT, EMERGENCY, OFFLINE
    ,PageVerifyOption nvarchar(35) -- NONE, TORN_PAGE_DETECTION, CHECKSUM
    ,IsReadOnly tinyint
    ,IsInStandBy tinyint
    ,IsAutoShrink tinyint
    ,IsAutoClose tinyint
    ,Flag bit default 0)
    create table #ltbl_Output (Error int,
    Level int,
    State int,
    MessageText nvarchar(max),
    RepairLevel nvarchar(30),
    Status int,
    DBID smallint,
    ObjectID int,
    IndexID smallint,
    PartitionID bigint,
    AllocunitID bigint,
    [File] int,
    Page int,
    Slot int,
    RefFile int,
    RefPage int,
    RefSlot int,
    Allocation int)
    /*==============================================================================
    Initialize Environment
    ==============================================================================*/
    set nocount on
    set quoted_identifier on
    /*==============================================================================
    Parameter Validation
    ==============================================================================*/
    -- Configure Alert Mail Subject Line
    set @lnvc_Subject = 'Check consistency parameter validation error occurred on ' + cast(@@servername as nvarchar)
    if @lnc_PhysicalOnly not in ('Y','N')
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_PhysicalOnly is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_DataPurity not in ('Y','N') and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_DataPurity is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_NoIndex not in ('Y','N') and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_NoIndex is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_ExtendedLogicalChecks not in ('Y','N') and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_ExtendedLogicalChecks is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_TabLock not in ('Y','N') and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_TabLock is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_ExtendedLogicalChecks = 'Y' and @lnc_PhysicalOnly = 'Y' and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'Extended Logical Checks and Physical Only cannot be used together.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_DataPurity = 'Y' and @lnc_PhysicalOnly = 'Y' and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'Physical Only and Data Purity cannot be used together.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @li_Rc != 0
    goto errlog
    /*==============================================================================
    Code Section
    ==============================================================================*/
    select @lnvc_SQL = N'select d.name, d.compatibility_level, d.create_date, d.user_access_desc, d.state_desc,
    d.page_verify_option_desc, cast(d.is_in_standby as tinyint), cast(d.is_read_only as tinyint),
    cast(databasepropertyex(quotename(d.name), ''IsAutoShrink'') as tinyint),
    cast(databasepropertyex(quotename(d.name), ''IsAutoClose'') as tinyint),
    0
    from master.sys.databases d
    where d.name = ' + case when isnull(@lnvc_Catalogue, '') = '' then ' d.name'
    else '''' + @lnvc_Catalogue + ''''
    end + '
    and d.name != ''tempdb'''
    insert into @ltbl_Catalogue (Catalogue, CompatibilityLevel, CreateDate, UserAccess,
    StateDescription, PageVerifyOption, IsReadOnly, IsInStandBy,
    IsAutoShrink, IsAutoClose, Flag)
    exec sp_executesql @lnvc_SQL
    while (select top 1 1
    from @ltbl_Catalogue c
    where c.Flag = 0) = 1
    begin
    select top 1 @lnvc_Catalogue = c.Catalogue
    ,@li_Compatibility = c.CompatibilityLevel
    ,@ldt_CreateDate = c.CreateDate
    ,@lnvc_UserAccess = c.UserAccess
    ,@lnvc_StateDescription = c.StateDescription
    ,@lnvc_PageVerifyOption = c.PageVerifyOption
    ,@lti_IsReadOnly = c.IsReadOnly
    ,@lti_IsInStandBy = c.IsInStandBy
    from @ltbl_Catalogue c
    where c.Flag = 0
    select top 1 @lnvc_Catalogue
    ,@li_Compatibility
    ,@ldt_CreateDate
    ,@lnvc_UserAccess
    ,@lnvc_StateDescription
    ,@lnvc_PageVerifyOption
    ,@lti_IsReadOnly
    ,@lti_IsInStandBy
    if @lnvc_StateDescription = 'ONLINE' and @lnvc_UserAccess != 'SINGLE_USER'
    begin
    -- Build Execution String
    select @lnvc_SQL = N'dbcc checkdb (' + quotename(@lnvc_Catalogue) + ')' + case when @lnc_NoIndex = 'Y' then ', noindex'
    else ''
    end + ' with tableresults, no_infomsgs, all_errormsgs '
    + case when @lnc_PhysicalOnly = 'Y' then ', physical_only'
    else ''
    end
    + case when @lnc_DataPurity = 'Y' then ', data_purity'
    else ''
    end
    -- Option not supported with Compatibility < 100 (SQL Server 2005 and below)
    + case when @lnc_ExtendedLogicalChecks = 'Y' then
    case when @li_Compatibility = 100 then ', extended_logical_checks'
    else ''
    end
    else ''
    end
    + case when @lnc_TabLock = 'Y' then ', tablock'
    else ''
    end
    -- Prepare Processing Environment
    truncate table #ltbl_Output
    set @ldt_ExecutionFinish = null
    set @ldt_ExecutionStart = null
    -- Capture Start Time.
    set @ldt_ExecutionStart = getdate()
    -- Execute the Command.
    insert into #ltbl_Output(Error, Level, State, MessageText, RepairLevel, Status,
    DBID, ObjectID, IndexID, PartitionID, AllocunitID,
    [File], Page, Slot, RefFile, RefPage, RefSlot, Allocation)
    exec sp_executesql @lnvc_SQL
    -- Capture Completion Time.
    set @ldt_ExecutionFinish = getdate()
    -- Add Header Record to Confirm Execution.
    insert into SysAdm.ConsistencyCheck.ExecutionLog(Instance, [Version], Edition, Catalogue, PhysicalOnly,
    NoIndex, ExtendedLogicalChecks, DataPurity, [TabLock],
    Command, ExecutionStart, ExecutionFinish,
    CreatedOn, CreatedBy)
    values(@lnvc_Instance, @lnvc_Version, @lnvc_Edition, @lnvc_Catalogue, @lnc_PhysicalOnly,
    @lnc_NoIndex, @lnc_ExtendedLogicalChecks, @lnc_DataPurity, @lnc_TabLock,
    @lnvc_SQL, @ldt_ExecutionStart, @ldt_ExecutionFinish,
    @ldt_ExecutedOn, @lnvc_ExecutedBy)
    -- Capture Header Record ID
    select @li_ConsistencyCheckID = @@IDENTITY
    -- Were there errors?
    if (select top 1 1
    from #ltbl_Output t) = 1
    begin
    select @li_ConsistencyCheckID, t.Error, t.Level, t.State, t.MessageText, t.RepairLevel,
    t.Status, t.ObjectID, t.IndexID, t.PartitionID, t.AllocunitID, t.[File], t.Page,
    t.Slot, t.RefFile, t.RefPage, t.RefSlot, t.Allocation, @ldt_ExecutedOn, @lnvc_ExecutedBy
    from #ltbl_Output t
    -- Log Failure Entries
    insert into SysAdm.ConsistencyCheck.ErrorLog (ExecutionLogID, Error, Severity, [State]
    ,ErrorMessage, RepairLevel, [Status], ObjectID
    ,IndexID, PartitionID, AllocationUnitID, FileID
    ,Page, Slot, RefFileID, RefPage, RefSlot, Allocation
    ,CreatedOn, CreatedBy)
    select @li_ConsistencyCheckID, t.Error, t.Level, t.State, t.MessageText, t.RepairLevel,
    t.Status, t.ObjectID, t.IndexID, t.PartitionID, t.AllocunitID, t.[File], t.Page,
    t.Slot, t.RefFile, t.RefPage, t.RefSlot, t.Allocation, @ldt_ExecutedOn, @lnvc_ExecutedBy
    from #ltbl_Output t
    -- Configure Alert Mail Subject Line
    set @lnvc_Subject = 'Consistency Check failure for Database ' + quotename(@lnvc_Catalogue) + ' on Instance ' + quotename(@lnvc_Instance) + ' !'
    set @lnvc_ErrorMessage = 'To view more details, logon to the Instance and execute the query: ' +
    + char(13) + char(10) + char(13) + char(10) +
    'select * from sysadm.consistencycheck.ErrorLog where ExecutionLogID = ' + cast(@li_ConsistencyCheckID as varchar) + ''
    + char(13) + char(10) + char(13) + char(10) +
    'Consistency Check Output: ' +
    + char(13) + char(10)
    select @lnvc_SQL = N'set nocount on;select ltrim(rtrim(ErrorMessage)) as Message
    from SysAdm.ConsistencyCheck.ErrorLog r
    where r.ExecutionLogID = ''' + cast(@li_ConsistencyCheckID as nvarchar(128)) + ''''
    exec msdb.dbo.sp_send_dbmail @profile_name = 'SQL Mailbox',
    @recipients = @lnvc_Recipients,
    @subject = @lnvc_Subject,
    @body = @lnvc_ErrorMessage,
    @query = @lnvc_SQL,
    @execute_query_database = @lnvc_Catalogue,
    @query_result_header = 1,
    @query_result_width = 32767,
    @query_no_truncate = 1,
    @body_format = 'TEXT',
    @importance = 'High'
    end
    end
    else
    begin
    -- If we get here, then the database was not processed due to it having a status other than ONLINE, being in SINGLE_USER mode or
    -- having a compatability level < 100
    set @lnvc_Subject = 'Unable to perform consistency checks for Database ' + quotename(@lnvc_Catalogue) + ' on ' + quotename(@lnvc_Instance) + '!'
    set @lnvc_ErrorMessage = 'One of the following conditions was not met. ' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10) +
    '* Database must be ONLINE. It''s current state is: ' + @lnvc_StateDescription + CHAR(13) + CHAR(10) +
    '* Database access level cannot be set to SINGLE_USER. It''s current access level is: ' + @lnvc_UserAccess
    exec msdb.dbo.sp_send_dbmail @profile_name = 'SQL Mailbox',
    @recipients = @lnvc_Recipients,
    @subject = @lnvc_Subject,
    @body = @lnvc_ErrorMessage,
    @body_format = 'TEXT',
    @importance = 'High'
    end
    update t
    set Flag = 1
    from @ltbl_Catalogue t
    where t.Catalogue = @lnvc_Catalogue
    end
    /*==============================================================================
    Cleanup Temp Tables
    ==============================================================================*/
    cleanup:
    if object_id('tempdb..#ltbl_Output') is not null
    drop table #ltbl_Output
    /*==============================================================================
    Exit Procedure
    ==============================================================================*/
    quit:
    return @li_Rc
    /*==============================================================================
    Error Processing
    ==============================================================================*/
    errlog:
    -- Raise Error, and write to Application Event Log
    raiserror (@lnvc_ErrorMessage, 16, 1) with log, nowait
    -- Send Email Notification of Error
    exec msdb.dbo.sp_send_dbmail @profile_name = 'Mailbox',
    @recipients = @lnvc_Recipients,
    @subject = @lnvc_Subject,
    @body = @lnvc_ErrorMessage,
    @importance = 'High'
    goto cleanup
    go
    John M. Couch

  • 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....

  • SQL Agent Job failing - not using credentials in the config file for Data source

    Hi
    We have an SSIS pkg, that is secheduled as SQL Agent job using proxy account. The pkg contanins data source for connecting different SQL servers and the proxy account do not have access to the external DBs. The data source credentials are stored in the Config
    file.
    Why the job is not using the credentials in the config file and try to use the proxy account and failing.
    Do the proxy account need access to all the external dbs in the pkg, and then what is the purpose of the config file.
    I am sorry, i am not SSIS person trying to understand. If any one can explain tha will be great!!
    Thank you!
    VR

    Please take a look at these URLs:
    Schedule a Package by using SQL Server Agent
    SSIS package does not run when called from a SQL Server Agent job step
    Cheers,
    Saeid Hasani
    Database Consultant
    Please feel free to contact me at [email protected] as well as on Twitter and Facebook.
    [My Writings on TechNet Wiki] [T-SQL Blog] [Curah!]
    [Twitter] [Facebook] [Email]

Maybe you are looking for

  • Error publishing from Cp5 to Connect v8

    Trying to publish a simple Captive v5 software demo to an Adobe Connect v8 server. If I try to publish to a 'room' (i.e. www.example.com/roomname/), I get 'the selected resource does not exist' If I try to publish direct to the Connect server name (i

  • Pixelated text and graphics in MacBook Pro Retina

    Why are text and graphics in pixelated in Numbers and iBooks applications, to name two, on the MacBook Pro Retina? All updates have been downloaded.

  • So I wasted my money?

    Been a happy user of my 2nd gen ipod touch for the last year or so, but..... Recently tried to download an app which wouldn't load as it required 4.3 - no problem I thought, just go and get the update only to discover that the 2nd gen doesn't have a

  • [Solved] Changing default file manager (with i3)

    Hi! Whenever I open whatever file in chromium it opens firefox and asks me with what I want to open it. (Not really lightweight. ) (The problem is the same with xdvi.) I'd like to let thunar manage this. Can anyone tell me how to configure this in th

  • Sending Attachments from GW-POA to engine fails..

    GroupWise Version: 8.0.2 Hotpatch 3 DataSynchronizer: 1.2.5 Build 299 Blackberry Enterprise Server: 10.1 Device: Blackberry Q5 Hey guys! Since setting up a BES10 for Blackberrys new devices, we are experiencing an odd problem: Synchronizing mails bet