Stored procedure time stamp

I have 6 blocks of code that needs to be in a  stored procedure. Now, I need time stamps at the beginning of the stored proc and after executing every single block. I need the time stamp stored within a table.
If any of the block fails, then the failed block column should not add time to that column.
Table_To_Store_Time
Col1                                       Col2                         
Col3              Col4 (Failed)          ......
SP_Start_Time               First_Block End Time     2Block_Time            0

Something along these lines?
DECLARE @timestamp DATETIME = GETDATE(), @i INT = 0
DECLARE @tableToStoreTime TABLE (spName VARCHAR(20), blockName VARCHAR(20), startDateTime datetime, endDateTime DATETIME, failed BIT)
WHILE @i < 10000
BEGIN
SET @i = @i + 1
END
INSERT INTO @tableToStoreTime (spName, blockName, startDateTime, endDateTime,failed)
VALUES ('testProc','block1',@timestamp,GETDATE(), 0)
SET @timestamp = GETDATE()
SET @i = 0
WHILE @i < 10000
BEGIN
SET @i = @i + 1
END
INSERT INTO @tableToStoreTime (spName, blockName, startDateTime, endDateTime,failed)
VALUES ('testProc','block2',@timestamp,GETDATE(), 0)

Similar Messages

  • Date Time Stamping issue

    When I use select xyz_Date from abc table in coldfusion
    cfquery tag, the out put comes as follows:
    CF5 - '05-MON-2007'
    CF8 - '2008-01-27 00:00:00.0'
    Note: The xyz_Date is stored without time stamp in the
    database.
    both running on 10.2.0.3 Oracle version. This is creating
    problem when inserting dates when we only use xyz_date as a value
    to be inserted. It worked fine on CF5 but not on CF8 due to format
    change. Is there a way to set it to behave like CF5. It appears
    that the later is using JDBC driver.

    I assume that your oracle field is a date field and not
    varchar. Also, your xyz_date is a date object. The most important
    thing to remember is that the format does not matter.
    This will work - #xyz_date# (no quotes)
    cfqueryparam will also work and has some performance
    advantages.

  • Calling stored procedure multiple times in the JDBC receiver

    Hi,
    I am calling the stored procedure(SP) to update a DB table in the JDBC receiver.
    SP has 10 input parameters, and SP can receive one value for each parameter at a time.
    In my case, i will have multiple rows to insert using SP.i.e multiple values for each parameter.
    Its working correctly for a single value for each parameter, but when i have multiple values i want to call the SP multiples times.
    Is this possible and how?
    Thanks,
    Varghese.

    Varghese,
    I think you can have multiple statements in the JDBC Adapter's XML, as in http://help.sap.com/saphelp_nw04/helpdata/en/2e/96fd3f2d14e869e10000000a155106/content.htm.
    Here the StatementName1 node can be inserted into your JDBC XML as often as you want.
    Kind regards,
    Koen

  • Identifying which part of stored procedure is taking long time

    Hi Everyone,
    I have a stored procedure which is taking long time to execute.  I am trying to understand which part/query in the stored procedure is taking long time.
    It involves lots of table variables and n no of queries .Could anyone please help me in how to identify which query/part of the stored procedure is taking long time to execute?
    Thanks in Advance

    Hi Vivek -
    I am only familiar with running the plan visualization for a single SQL query.
    Could you please guide me how to run it for a procedure.
    Thanks in Advance.

  • Stored Procedure  is taking too long time to Execute.

    Hi all,
    I have a stored procedure which executes in 2 hr in one database, but the same stored procedure is taking more than 6 hour in the other database.
    Both the database are in oracle 11.2
    Can you please suggest what might be the reasons.
    Thanks.

    In most sites I've worked at it's almost impossible to trace sessions, because you don't have read permissions on the tracefile directory (or access to the server at all). My first check would therefore be to look in my session browser to see what the session is actually doing. What is the current SQL statement? What is the current wait event? What cursors has the session spent time on? If the procedure just slogs through one cursor or one INSERT statement etc then you have a straightforward SQL tuning problem. If it's more complex then it will help to know which part is taking the time.
    If you have a licence for the diagnostic pack you can query v$active_session_history, e.g. (developed for 10.2.0.3, could maybe do more in 11.2):
    SELECT CAST(ash.started AS DATE) started
         , ash.elapsed
         , s.sql_text
         , CASE WHEN ash.sql_id = :sql_id AND :status = 'ACTIVE' THEN 'Y' END AS executing
         , s.executions
         , CAST(NUMTODSINTERVAL(elapsed_time/NULLIF(executions,0)/1e6,'SECOND') AS INTERVAL DAY(0) TO SECOND(1)) AS avg_time
         , CAST(NUMTODSINTERVAL(elapsed_time/1e6,'SECOND') AS INTERVAL DAY(0) TO SECOND(1)) AS total_time
         , ROUND(s.parse_calls/NULLIF(s.executions,0),1) avg_parses
         , ROUND(s.fetches/NULLIF(s.executions,0),1) avg_fetches
         , ROUND(s.rows_processed/NULLIF(s.executions,0),1) avg_rows_processed
         , s.module, s.action
         , ash.sql_id
         , ash.sql_child_number
         , ash.sql_plan_hash_value
         , ash.started
    FROM   ( SELECT MIN(sample_time) AS started
                  , CAST(MAX(sample_time) - MIN(sample_time) AS INTERVAL DAY(0) TO SECOND(0)) AS elapsed
                  , sql_id
                  , sql_child_number
                  , sql_plan_hash_value
             FROM   v$active_session_history
             WHERE  session_id = :sid
             AND    session_serial# = :serial#
             GROUP BY sql_id, sql_child_number, sql_plan_hash_value ) ash
           LEFT JOIN
           ( SELECT sql_id, plan_hash_value
                  , sql_text, SUM(executions) OVER (PARTITION BY sql_id) AS executions, module, action, rows_processed, fetches, parse_calls, elapsed_time
                  , ROW_NUMBER() OVER (PARTITION BY sql_id ORDER BY last_load_time DESC) AS seq
             FROM   v$sql ) s
           ON s.sql_id = ash.sql_id AND s.plan_hash_value = ash.sql_plan_hash_value
    WHERE  s.seq = 1
    ORDER BY 1 DESC;:sid and :serial# come from v$session. In PL/SQL Developer I defined this as a tab named 'Session queries' in the session browser.
    I have another tab named 'Object wait totals this query' containing:
    SELECT LTRIM(ep.owner || '.' || ep.object_name || '.' || ep.procedure_name,'.') AS plsql_entry_procedure
         , LTRIM(cp.owner || '.' || cp.object_name || '.' || cp.procedure_name,'.') AS plsql_procedure
         , session_state
         , CASE WHEN blocking_session_status IN ('NOT IN WAIT','NO HOLDER','UNKNOWN') THEN NULL ELSE blocking_session_status END AS blocking_session_status
         , event
         , wait_class
         , ROUND(SUM(wait_time)/100,1) as wait_time_secs
         , ROUND(SUM(time_waited)/100,1) as time_waited_secs
         , LTRIM(o.owner || '.' || o.object_name,'.') AS wait_object
    FROM   v$active_session_history h
           LEFT JOIN dba_procedures ep
           ON   ep.object_id = h.plsql_entry_object_id AND ep.subprogram_id = h.plsql_entry_subprogram_id
           LEFT JOIN dba_procedures cp
           ON   cp.object_id = h.plsql_object_id AND cp.subprogram_id = h.plsql_subprogram_id
           LEFT JOIN dba_objects o ON o.object_id = h.current_obj#
    WHERE  h.session_id = :sid
    AND    h.session_serial# = :serial#
    AND    h.user_id = :user#
    AND    h.sql_id = :sql_id
    AND    h.sql_child_number = :sql_child_number
    GROUP BY
           ep.owner, ep.object_name, ep.procedure_name
         , cp.owner, cp.object_name, cp.procedure_name
         , session_state
         , CASE WHEN blocking_session_status IN ('NOT IN WAIT','NO HOLDER','UNKNOWN') THEN NULL ELSE blocking_session_status END
         , event
         , wait_class
         , o.owner
         , o.object_nameIt's not perfect and the numbers aren't reliable, but it gives me an idea where the time might be going. While I'm at it, v$session_longops is worth a look, so I also have 'Longops' as:
    SELECT sid
         , CASE WHEN l.time_remaining> 0 OR l.sofar < l.totalwork THEN 'Yes' END AS "Active?"
         , l.opname AS operation
         , l.totalwork || ' ' || l.units AS totalwork
         , NVL(l.target,l.target_desc) AS target
         , ROUND(100 * l.sofar/GREATEST(l.totalwork,1),1) AS "Complete %"
         , NULLIF(RTRIM(RTRIM(LTRIM(LTRIM(numtodsinterval(l.elapsed_seconds,'SECOND'),'+0'),' '),'0'),'.'),'00:00:00') AS elapsed
         , l.start_time
         , CASE
               WHEN  l.time_remaining = 0 THEN l.last_update_time
               ELSE SYSDATE + l.time_remaining/86400
           END AS est_completion
         , l.sql_id
         , l.sql_address
         , l.sql_hash_value
    FROM v$session_longops l
    WHERE :sid IN (sid,qcsid)
    AND  l.start_time >= TO_DATE(:logon_time,'DD/MM/YYYY HH24:MI:SS')
    ORDER BY l.start_time descand 'Longops this query' as:
    SELECT sid
         , CASE WHEN l.time_remaining> 0 OR l.sofar < l.totalwork THEN 'Yes' END AS "Active?"
         , l.opname AS operation
         , l.totalwork || ' ' || l.units AS totalwork
         , NVL(l.target,l.target_desc) AS target
         , ROUND(100 * l.sofar/GREATEST(l.totalwork,1),1) AS "Complete %"
         , NULLIF(RTRIM(RTRIM(LTRIM(LTRIM(numtodsinterval(l.elapsed_seconds,'SECOND'),'+0'),' '),'0'),'.'),'00:00:00') AS elapsed
         , l.start_time
         , CASE
               WHEN  l.time_remaining = 0 THEN l.last_update_time
               ELSE SYSDATE + l.time_remaining/86400
           END AS est_completion
         , l.sql_id
         , l.sql_address
         , l.sql_hash_value
    FROM v$session_longops l
    WHERE :sid IN (sid,qcsid)
    AND  l.start_time >= TO_DATE(:logon_time,'DD/MM/YYYY HH24:MI:SS')
    AND  l.sql_id = :sql_id
    ORDER BY l.start_time descYou can also get this sort of information out of OEM if you're lucky enough to have access to it - if not, ask for it!
    Apart from this type of monitoring, you might try using DBMS_PROFILER (point and click in most IDEs, but you can use it from the SQL*Plus prompt), and also instrument your code with calls to DBMS_APPLICATION_INFO.SET_CLIENT_INFO so you can easily tell from v$session which section of code is being executed.

  • URGENT: I want to pass a variable to a stored procedure at run time

    Post Author: aruplabs
    CA Forum: Data Connectivity and SQL
    I work for a health care provider and I have reports that pull PHI (Protected Health Information) about patients that needs to be logged according to federal HIPAA regulations. One of the pieces of information that needs to be logged is the username of the person who ran the report. Since these reports will be run from our Crystal Enterprise server I can get this from the CurrentCEUserName variable but I am looking for a way to pass this value to a stored procedure that will not only return the records for the report, but also log the disclosure in our PHI disclosure tracking table. I know you can pass a parameter to a stored procedure but I dont know how, or if it is even possible, to pass a run time variable. This is an urgent problem that I need to find a solution for. Any help would be appreciated.
    Thank you.

    Here it is. Right now, when i press te "Go" it runs for the specific time i've set and when its done the variable "Run" is set true. When i call this VI from another VI it waits for the loop to be finished before it will read the variable.
    Regards
    Viktor
    Attachments:
    Untitled 2.vi ‏26 KB

  • Multiple Stored Procedures - One at a time

    Hello everyone!
    I´m going to start an interface that requires me to call multiple Stored Procedures, but they will not be called at the same time.
    The legacy system has 3 stored procedures to be called, like this:
    1 - SP number 1: it says to the legacy system that some data is going to come up and clean the previous data
    2 - SP number 2: input data into the legacy system
    3 - SP number 3: for each line above, more lines will be inserted - sort of header/line cenario
    My question is: should I be able to achieve this goal using only PI 'normal' components or will I have to use BPM?
    Thanks!
    Ricardo Sancio Lóra
    Brazil

    Hi Ricardo,
    According to my knowledge not required to use the BPM.
    In that first stored procedure you can call the another stored procedure, internally database can take the all necessary actions.
    Check this links
    http://www.sommarskog.se/share_data.html
    http://bytes.com/topic/sql-server/answers/79780-stored-procedure-calling-another-stored-procedure_
    Regards
    Ramesh

  • To execute the same stored procedure multiple times

    Suppose I have this :
    select distinct batch_id, submit_date from batch where date > xxx;
    Gives me :
    301
    305
    306
    Currently, I have a stored procedure PROC_A that has 3 cursors all of which have a field called batch_id(which ofcourse exists in the above batch table). Hence, when I run as of today
    EXECUTE PROC_A;
    This could process an unpredictable set of batch ids. I am looking to avoid this.
    What I am trying to achieve here is :
    When I do,
    select distinct batch_id from batch where date > xxx;
    301
    305
    306
    For each of the above values, I want to call the PROC_A exclusively. In other words, by one shot, I want this procedure to be invoked 3 times, each time processing just one batch_id one after another (rather than passing those 3 values to the procedure and having it execute just once !). I also want to avoid using the batch table anywhere inside the stored procedure PROC_A.
    How do I achieve this ? If another stored procedure can call PROC_A, I am okay with including the batch table there.

    What about an executed_date field on the table and a "where rownum=1" in the cursor?
    proc_a
    begin
         begin
              select batch_id
              into b_id
              from batch ...
              where date > xxx
                   and date > last_executed
                   and rownum = 1;
         exception
              when NO_DATA_FOUND then
                   return;
         end;
         exec(b_id);
         update batch
         set last_executed = sysdate
         where bacth_id = b_id;
         return;
    end;Bye Alessandro

  • Date/Time Format Stored Procedure Calls in ADVANCE MODE in JDBC ADAPTER

    Hi Experts,
    What is significance of Date/Time Format Stored Procedure Calls in ADVANCE MODE in JDBC ADAPTER.
    Thanks,
    ABDUR

    I guess this would be applicable for the folowing formats - DATE, TIME, TIMESTAMP.
    This is the correct link
    http://help.sap.com/saphelp_nw04/helpdata/en/64/ce4e886334ec4ea7c2712e11cc567c/content.htm
    Regards,
    Prateek

  • Execution Times of Stored Procedures Called from Other Stored Procedures

    If I execute sys.dm_exec_procedure_stats, it will produce execution times of my stored procedures executed recently.
    However, stored procedures called from other stored procedures do not show up.
    Is there code that can return the execution times of stored procedures even though they are called from other stored procedures.

    Look at the example. It is counting nested execution.
    CREATE PROC z1SP AS SELECT * FROM Production.Product;
    GO
    CREATE PROC z2SP AS SELECT * FROM Production.Product WHERE Color is not null; EXEC z1SP;
    GO
    SELECT object_name(2002822197), object_name(2034822311);
    --z1SP z2SP
    EXEC z1SP; EXEC z2SP;
    GO 10
    SELECT * from sys.dm_exec_procedure_stats
    database_id object_id type type_desc cached_time last_execution_time execution_count
    16 2002822197 P SQL_STORED_PROCEDURE 2014-12-16 13:02:45.170 2014-12-16 13:02:46.717 20
    16 2034822311 P SQL_STORED_PROCEDURE 2014-12-16 13:02:45.460 2014-12-16 13:02:46.687 10
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

  • Check If Tables are being used in Stored Procedures & How many times !!

    Dear All,
    I want to make a script which can give me an answer, that If there is any table , then Whether It's using in any stored procedure or not ? If yes, then what the occurrence in procedures - means if table is "ABC" & Its being used in stored procedure
    "XYZ" then i want to know that its using 1 time, 2 time or more in particular procedure ..
    Pls Help

    just in-case if you want to get the Cross DB dependency
    i have extent Visakh16 code
    please use sql_modules to get the full definition of the DB Objects
    you can replace stg_table with your decided table, also use dbname.schemaname.tablename if you want to get  Cross DB dependency
    just came up with this from
    link
    create table #temp (
    dbname sysname,
    name sysname,
    Occurance int
    exec sp_MSforeachdb '
    use ?
    DECLARE @TableName varchar(100)
    SET @TableName = ''stg_table''
    insert into #temp
    SELECT db_name() ,name,(LEN(definition) - LEN(REPLACE(definition,'' '' + @TableName + '' '','''')))/LEN('' '' + @TableName + '' '') AS Occurance
    FROM sys.sql_modules m
    INNER JOIN sys.objects o
    ON o.object_id = m.object_id
    AND o.type = ''p''
    WHERE m.definition LIKE ''% '' + @TableName + '' %'''
    select *
    from #temp
    where dbname not in ('master','model','msdb','tempdb')
    order by 1,2
    Thanks
    Saravana Kumar C

  • "STORED" Time On Texts With One Hour Earlier Time Wedged Between The Two Eastern Time Stamps.

    The middle time stamp would coincide with Central Time, but it is not labeled as such. If that is what it represents, then it shouldn't
    be on my texts since eastern Tennessee and Georgia are in the Eastern Time Zone.

    budone wrote:
    budone,
    In the last two days there has been a change in the format of my text messages. Previously, the texts simply had a time stamp given in Eastern Time. NOW, this is followed with the date and AM or PM time, but the time is one hour earlier and NO Time Zone notation given. Then it says, 'Stored' with a time stamp matching the date and time given in the line designated as "Eastern." 
    Surely, there are others who have experienced this. I hope this clears the explanation up some. 

  • Out of memory error when calling a java stored procedure multiple times

    Trying to run a PL/SQL loop calling a java stored procedure, I get the following error:
    "ORA-04030: out of process memory when trying to allocate 262188 byte callheap,ioc_allocate free)"
    (with some other error lines).
    The stored procedure does two major things:
    1) Open a socket to communicate with a server, of which it queries some data.
    2) Use JDBC (with the default DB connection it has, as a stored procedure) to write the results to a table.
    All socket connections, statements, etc. are properly closed and all memory should be garbage collected between each call.
    Can anyone offer an explanation or additional checks to make? I'm quite sure the code isn't causing the problem, since I've tried running it as a stand alone application (outside of Oracle) and didn't have any problems.
    Thanks.

    Hi,
    Verify that the database parameters are set correctly.
    EA

  • SQL Server Agent daily job indicates completed but stored procedure and tables indicate otherwise -- 2nd time in 4 years also on Sunday?

    Hi
    We have scheduled job running a console application daily. For some reason on Sunday's only the scheduler says it ran successfully but no email confirmation, table entries and the normal processing occurs.
    This happens only on a Sunday and for no explained reason. No problem on the day before or after...
    I think this also happened with Daylight Savings adjustment. Has anyone else encountered this?
    Any ideas or suggestions
    Environment is:
    Microsoft SQL Server 2008 R2 (SP2) - 10.50.4000.0 (X64)   Jun 28 2012 08:36:30   Copyright (c) Microsoft Corporation  Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1) (Hypervisor)
    Thanks in advance
    George 

    Michelle 
    Thanks for your reply. I was out sick all last week.
    I too suspected our network and/or security features or maintenance.
    Me and my manager decided to include a text log file which we append certain key points for each iteration when the vb.net console app runs to hopefully determine what is happening sporadically. 
    I created many errors and scenarios ( DB and network connectivity, unable to send email) and they were caught and appended to the logfile so all I can do is wait to see when/if this occurs.
    Sincerely 
    George 
    NOTE:  DISREGARD THE "Failure Sending mail" exceptions they disabled it for security reasons and it only works for production jobs and special users  
    DailySerial Feed started at 11:48:34 AM
      Attempting DB Connection 11:48:34 AM
      DB Connection successful 11:48:34 AM
      completed successful 11:48:38 AM  Record count: 153 processed
    DailySerial Feed started at 11:49:37 AM
      Attempting DB Connection 11:49:37 AM
      DB Connection successful 11:49:37 AM
      completed successful 11:49:42 AM  Record count: 0 processed
      SendEmail failed 11:49:44 AM - Failure sending mail.
    DailySerial Feed started at 4:37:42 PM
      Attempting DB Connection 4:37:42 PM
      DB Connection successful 4:37:44 PM
      completed successfully 4:37:44 PM  Record count: 153 processed
      SendEmail failed 4:37:45 PM - Failure sending mail.
    System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 10.8.86.78:25
       at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
       at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
       at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
    DailySerial Feed started at Monday12:50:29 PM
      Attempting DB Connection 12:50:29 PM
      DB Connection successful 12:50:29 PM
      completed successfully 12:50:30 PM  Record count: 153 processed
      SendEmail failed Monday12:50:31 PM - Failure sending mail.
    System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 10.8.86.78:25
       at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
       at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
       at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
    DailySerial Feed started on Monday, March 23, 2015 - 2:31:40 PM
      Attempting DB Connection 2:31:40 PM
      Connection failed Monday 2:31:55 PM  for: server=ITDEVPTENSDEV\sqlserver2008r2yada;database=ICES;Trusted_Connection=True - 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
      SendEmail failed Monday 2:31:55 PM - Failure sending mail.
    System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 10.8.86.70:25
       at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
       at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
       at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
      Rollback Exception 2:31:55 PM - unable to OPEN the DB ConnectionA 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) -  - Connection established    
      SendEmail failed Monday 2:31:55 PM - Failure sending mail.
    System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 10.8.86.70:25
       at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
       at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
       at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
    DailySerial Feed started on Monday, March 23, 2015 - 2:36:38 PM
      Attempting DB Connection 2:36:38 PM
      DB Connection successful 2:36:38 PM
      DailySerial feed completed 2:36:38 PM  Record count: 0 processed
      SendEmail failed Monday 2:36:38 PM - Failure sending mail.
    System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 10.8.86.70:25
       at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
       at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
       at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
    DailySerial Feed started on Monday, March 23, 2015 - 2:37:03 PM
      Attempting DB Connection 2:37:03 PM
      DB Connection successful 2:37:03 PM
      DailySerial feed completed 2:37:03 PM  Record count: 153 processed
      SendEmail failed Monday 2:37:03 PM - Failure sending mail.
    System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 10.8.86.70:25
       at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
       at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
       at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
    Imports System.IO
    Imports System.Net
    Imports System.Text
    Imports System.Data.SqlClient
    Imports System.Data.Common
    Public Module DailySerialFeed
        Dim attempts As Integer = 0
        Dim sb As New StringBuilder
        Dim myconnection As New SqlConnection
        Dim m_SqlConnStr As String = My.Settings.SqlConnStr
        Dim strCardAFCExportBatchIDGuid As String
        Dim LogMessage As String
        Dim TotalExtracted As Integer
        Public sSource As String = "DailySerialFeed"
        Public Slog As String = "Application"
        Public sEvent As String = ""
        Public ErrText As String
        Public sMachine As String = "."
        Dim mySqlTransaction As SqlTransaction
        Dim time As DateTime = DateTime.Now
        Dim format As String = "MMM ddd d HH:mm yyyy"
        Dim LogFile As StreamWriter   '  SFTPData\AFC\DailySerialFeedLog.TXT 
        Dim ExceptionString As String
        Public Sub Main()
            Try
                LogFile = New StreamWriter(My.Settings.LogFile, FileMode.Append) ' append to file 
                LogFile.WriteLine("")    '(Environment.NewLine)
                LogFile.WriteLine("DailySerial Feed started on " & Now.ToString("D") & " - " & Now.ToLongTimeString)
                strCardAFCExportBatchIDGuid = System.Guid.NewGuid().ToString
                LogFile.WriteLine("  Attempting DB Connection " & Now.ToLongTimeString)
                OpenDBConnection()
                LogFile.WriteLine("  DB Connection successful " & Now.ToLongTimeString)
                mySqlTransaction = myconnection.BeginTransaction("OuterTransaction")
                'PadSerialNumbers()  Lewycky 7/19/13  Zero digit padding for 8 or 9 digital serial numbers  Disabled                
                'RemoveZeroSerial() ' Lewycky 11/3/11 remove zero serial numbers from being sent to AFC now in FlagSerialforExtract module
                FlagSerialforExtract()
                ExtractFlaggedSerialFile()
                mySqlTransaction.Commit()
                CloseDBConnection()
                StageforFTPAndArchive()
                sb.AppendLine("  " & "DailySerial Feed completed. Record count: " & TotalExtracted & " processed")
                LogFile.WriteLine("  DailySerial feed completed " & Now.ToLongTimeString & "  Record count: " & TotalExtracted & " processed")
            Catch ex As Exception
                If Not mySqlTransaction Is Nothing Then
                    LogFile.WriteLine("  Rollback Exception " & Now.ToLongTimeString & " - " & ex.Message)
                    mySqlTransaction.Rollback("OuterTransaction")
                End If
                sb.AppendLine("  " & "Problem encountered with DailySerialFeed extract :" & ex.Message & " - " & ErrText)
                LogFile.WriteLine("  Rollback Exception " & Now.ToLongTimeString & " - " & ex.Message & " - " & " - " & ErrText)
            Finally
                SendEmail(RTrim(sb.ToString))
                ' if dbconnection is still open during exception/error force it closed
                If myconnection.State = ConnectionState.Open Then
                    LogFile.WriteLine("  Closing DB Connection(2) " & Now.ToLongTimeString & " - ")
                    CloseDBConnection()
                End If
                LogFile.Close()
            End Try
        End Sub
        Public Sub OpenDBConnection()
            myconnection = New SqlConnection(m_SqlConnStr)
            Try
                myconnection.Open()
            Catch ex As Exception
                Dim strErr As String = ex.Message
                LogFile.WriteLine("  Connection failed " & Now.ToString("dddd ") & Now.ToLongTimeString & "  for: " & My.Settings.SqlConnStr & " - " & strErr)
                SendEmail(strErr)
                Throw New System.Exception("unable to OPEN the DB Connection" & strErr)
            Finally
                ErrText = "Connection established    "
                'sb.AppendLine("Connection established   ")
            End Try
        End Sub
        Public Sub FlagSerialforExtract()
            ' Update the batch of records in CardAFCExport table with the GUID related to that batch created earlier
            ' Now included in the same Commmand - removal of any zero digit serial numbers previously in another module 
            Dim myCommand As New SqlCommand
            Try
                ' lewycky pull serial numbers prior to midnite  1 day lag 
                ' lewycky use the GUID created in the Main() for updating in dbo.CardAFCExport indetifying qualifying serial 
                '  numbers for this daily batch to ultimately be sent to AFC and to receive back detailed metrocard data
                myCommand = New SqlCommand("DELETE from CardAFCExport  where CAST(CardSerialNumber as bigint)= 0;Update CardAFCExport Set CardAFCExportBatchID = '" & strCardAFCExportBatchIDGuid & "' where
    CardAFCExportBatchID is null and CreatedDate < DATEADD(dd,0,datediff(dd,0,getdate()))", myconnection, mySqlTransaction)
                myCommand.ExecuteNonQuery()
            Catch ex As Exception
                Dim strErr As String = ex.Message
                ErrText = "unable to update the batch with its GUID  " & strErr & "  "
                sb.AppendLine("unable to update the batch with its GUID." & "  ")
                sb.AppendLine("Error Message : " & ex.Message)
                LogFile.WriteLine("  FlagSerialforExtract failed " & Now.ToLongTimeString & " - " & strErr)
                Throw New System.Exception(strErr)
            Finally
                ErrText = "Serial numbers flagged with GUID successfully   "
                'sb.AppendLine("Serial numbers flagged with GUID successfully   ")
            End Try
        End Sub
        'Public Sub PadSerialNumbers()   7/19/13 Lewycky Disabled per Serial numbers becoming duplicated if the enter with and without zeros
        '    Dim myCommand As New SqlCommand
        '    Try
        '        myCommand = New SqlCommand("update CardAFCExport set CardSerialNumber =  '0' + CardSerialNumber where CardSerialNumber in (SELECT CardSerialNumber FROM CardAFCExport where LEN(cardserialnumber) = 9 )",
    myconnection, mySqlTransaction)
        '        myCommand.ExecuteNonQuery()
        '        myCommand = New SqlCommand("update CardAFCExport set CardSerialNumber =  '00' + CardSerialNumber where CardSerialNumber in (SELECT CardSerialNumber FROM CardAFCExport where LEN(cardserialnumber) = 8 )",
    myconnection, mySqlTransaction)
        '        myCommand.ExecuteNonQuery()
        '    Catch ex As Exception
        '        Dim strErr As String = ex.Message
        '        ErrText = "unable to pad serial serial numbers" & strErr
        '        sb.AppendLine("unable to pad serial serial numbers" & "  ")
        '        sb.AppendLine("Error Message : " & ex.Message & "  ")
        '        SendEmail(strErr)
        '        Throw New System.Exception(strErr)
        '    Finally
        '        ErrText = "Serial numbers padded successfully   "
        '        sb.AppendLine("Serial numbers padded successfully   ")
        '    End Try
        'End Sub
        'Public Sub RemoveZeroSerial()
        '    now in the FlagSerialforExtract module 
        '    '  Zero Serial number deletion still needed ( 8 & 9 digit ) otherwise 999 records will be generated on ICES when AFC returns file
        '    Dim myCommand As New SqlCommand
        '    Try
        '        myCommand = New SqlCommand("DELETE from CardAFCExport  where CAST(CardSerialNumber as bigint)= 0", myconnection, mySqlTransaction)
        '        '        myCommand = New SqlCommand("delete from CardAFCExport where CardSerialNumber = '0000000000' ", myconnection, mySqlTransaction)
        '        myCommand.ExecuteNonQuery()
        '    Catch ex As Exception
        '        Dim strErr As String = ex.Message
        '        ErrText = "unable to remove Zero Serial Numbers" & strErr
        '        sb.AppendLine("unable to remove Zero Serial Numbers.")
        '        sb.AppendLine("Error Message : " & ex.Message)
        '        SendEmail(strErr)
        '        Throw New System.Exception(strErr)
        '    Finally
        '        ErrText = "Zero serial numbers removed   "
        '        sb.AppendLine("Zero serial numbers removed successfully   ")
        '    End Try
        'End Sub
        Public Sub ExtractFlaggedSerialFile()
            ' extract metrocard serial number feed in ascending order and w/o dupes 
            Dim column1 As String
            Dim TotalRecords As Integer = 0
            Dim myCommand As New SqlCommand
            Dim objStreamWriter As StreamWriter
            Try
                ' 7/19/13 - Lewycky modification to remove duplicates and omit the same serial number entered as a 8 or 9 digit number instead of the 
                '           required 10 digit for AFC w/o extra DML updates due to Serialnumber being a Unique value per batch 
                myCommand = New SqlCommand("SELECT DISTINCT RIGHT('00' + Cardserialnumber,10) Cardserialnumber FROM CardAFCExport where CardAFCExportBatchID = '" & strCardAFCExportBatchIDGuid & "' order by
    CardSerialNumber", myconnection, mySqlTransaction)
                '  myCommand = New SqlCommand("SELECT distinct CardSerialNumber FROM CardAFCExport where CardAFCExportBatchID = '" & strCardAFCExportBatchIDGuid & "' order by CardSerialNumber", myconnection,
    mySqlTransaction)
                myCommand.CommandType = CommandType.Text
                objStreamWriter = File.CreateText(My.Settings.AFCExportInterimFile.ToString)
                Dim myreader As SqlDataReader = myCommand.ExecuteReader
                While myreader.Read
                    column1 = myreader.Item("CardSerialNumber").ToString
                    objStreamWriter.WriteLine(column1)
                    TotalExtracted = TotalExtracted + 1
                End While
                myreader.Close()
                objStreamWriter.Close()
                ' Extract file is now created
                myCommand = New SqlCommand("INSERT INTO CardAFCExportBatch (CardAFCExportBatchID, TotalRecords, ExportedDate, CreatedDate, CreatedBy) values ( '" & strCardAFCExportBatchIDGuid & "', " +
    TotalExtracted.ToString + ", GETDATE(), GETDATE(), '00000000-0000-0000-0000-000000000000')", myconnection, mySqlTransaction)
                myCommand.ExecuteNonQuery()
            Catch ex As Exception
                Dim strErr As String = ex.Message
                ErrText = "unable to create extract from CardAFCExport  last input record " & TotalRecords & "' '" & strErr
                LogFile.WriteLine("  ExtractFlaggedSerialFile failed " & Now.ToLongTimeString & " - " & ErrText)
                LogMessage = ErrText
                sb.AppendLine(ErrText)
                sb.AppendLine("Error Message : " & ex.Message)
                SendEmail(LogMessage)
                Throw New System.Exception("unable to create extract from CardAFCExport  last record " & TotalRecords)
            Finally
                ErrText = "Batch Info updated & Extract created. Rec count: " & TotalExtracted
            End Try
        End Sub
        Public Sub StageforFTPAndArchive()
            'KD - Getting file ready for AFC ftp. Also archive the file with date time stamp.        
            Try
                Dim strFileName As String = Path.GetFileNameWithoutExtension(My.Settings.AFCExportInterimFile)
                Dim strDirectory As String = Path.GetDirectoryName(My.Settings.AFCExportInterimFile)
                Dim strTimeStamp As String = Now.ToString("MMddyyyyhhmmss")
                Dim strExtension As String = Path.GetExtension(My.Settings.AFCExportInterimFile)
                'KD : copy AFCSWIPE.TXT file to outgoing folder 
                System.IO.File.Copy(My.Settings.AFCExportInterimFile, My.Settings.AFCExportFile.ToString, True)
                'KD : make  yyyyMMDD_hhmmss_ICE_SWP.TXT file to outgoing folder for MCO (Randy Steiner)            
                System.IO.File.Copy(My.Settings.AFCExportInterimFile, My.Settings.AFCExportFilePath + Now.ToString("yyyyMMdd_hhmmss") + "_ICE_SWP.TXT", True)
                'KD : Archive file in archieve folder with date time stamp            
                System.IO.File.Move(My.Settings.AFCExportInterimFile, My.Settings.AFCExportArchivePath + strFileName + "_" + strTimeStamp + strExtension)
            Catch ex As Exception
                sb.AppendLine("Error occurred in StageforFTPAndArchive." + Chr(13) + Chr(10))
                sb.AppendLine("Error Message : " & ex.Message + Chr(13) + Chr(10))
                LogFile.WriteLine("  StageforFTPAndArchive failed " & Now.ToLongTimeString & " - " & ex.Message)
                Throw ex
            End Try
        End Sub
        Sub SendEmail(ByVal msg As String)
            ' Dim myWebRequest As WebRequest
            ' Dim myStreamReader As StreamReader
            Dim strSubject, strBody As String
            Dim myMailMessage As Mail.MailMessage
            Dim mySmtpClient As Mail.SmtpClient
            strBody = msg
            ' Get subject from settings and replace placeholder with current date
            strSubject = My.Settings.EmailSubject
            strSubject = strSubject.Replace("<date>", FormatDateTime(Now(), DateFormat.ShortDate))
            Try
                myMailMessage = New Mail.MailMessage(My.Settings.EmailFrom, My.Settings.EmailTo, strSubject, strBody)
                If My.Settings.EmailCC <> "" Then myMailMessage.CC.Add(My.Settings.EmailCC)
                myMailMessage.IsBodyHtml = My.Settings.EmailHtml
                ' Send email
                mySmtpClient = New Mail.SmtpClient()
                mySmtpClient.Host = My.Settings.SmtpServer()
                mySmtpClient.Send(myMailMessage)
            Catch ex As Exception
                Console.Write("could not send Mail-" & ex.Message)
                'ExceptionString = "Exception type " & ex.GetType.ToString & Environment.NewLine & "Exception message: " & ex.Message + Environment.NewLine
                '& "Stack trace: " + ex.StackTrace + Environment.NewLine;
                'LogFile.WriteLine(ExceptionString)
                'LogFile.WriteLine("  SendEmail failed " & Now.ToLongTimeString & " - " & ex.Message.ToString & ex.InnerException.ToString)
                ' w.o stack trace ?
                LogFile.WriteLine("  SendEmail failed " & Now.ToString("dddd ") & Now.ToLongTimeString & " - " & ex.Message.ToString & Environment.NewLine & (DirectCast(ex.InnerException,
    System.Exception).InnerException.ToString))
            End Try
        End Sub
        Public Sub CloseDBConnection()
            Try
                myconnection.Close()
            Catch ex As Exception
                Dim strErr As String = ex.Message
                LogFile.WriteLine("  CloseDBConnection failed " & Now.ToString("dddd ") & Now.ToLongTimeString & " for: " & My.Settings.SqlConnStr & " - " & strErr)
                Throw New System.Exception("unable to CLOSE the DB Connection" & strErr)
            Finally
                ErrText = " DB Conn closed & Serial Feed completed normally    "
            End Try
        End Sub
    End Module

  • Table name at run time in Stored procedure

    I have a SQl statement within my stored procedure as :
    SELECT LastModifiedDate INTO v_Date FROM TABLE1 WHERE ID = v_ID;
    Can I use a variable vTableName instead of directly putting the
    value "TABLE1" (that is actual name of the table ).
    Please excuse me if the question sounds trivial.
    Cheers!!

    You need to use Dynamic Sql. In your procedure
    DECLARE
    v_sql_stmt varchar2(2000);
    v_Date       DATE ;
    begin
    v_sql_stmt :=  'SELECT LastModifiedDate FROM TABLE1 WHERE ID = :1 ' ;
    execute immediate v_sql_stmt into v_Date  using v_ID ;
    end;

Maybe you are looking for