SQL environment variable into a local variable in stored procedure ?

How do i set a SQL environment variable in a session ? How can i read an SQL environment variable into a local variable declared in my stored procedure ? Does any exceptions occur in the process ?
I need this very urgently, can anyone help ?
thanks
srini

You can use a pipelined table function to return it, which is covered here:
http://blog.mclaughlinsoftware.com/plsql-programming/pipelined-functions-plsql-tables/
Alternatively, you can use a SQL Object type wrapped by a collection of that SQL object type inside a TABLE call. I've blogged on that too, here:
http://blog.mclaughlinsoftware.com/2009/03/23/object-record-collections/
If you need something more, leave a comment on the blog. I'm not here on the forum too frequently. Hope that helped.

Similar Messages

  • How to store serval char variables into a string variable?

    I have serval char variables, but i don't know how to put them together (without using arrays). I am thinking to store these char variables into a string variable but i don't know how to do it. For example,
    char letter1 = 'a', letter2 = 'b', letter3 = 'c';
    String letters;
    then how can i do to make letters = "abc" from using letter1,2,3?
    I am just a beginner of Java, if anyone can help me, i will appreciate that very much!!!

    String letters=""+leter1+letter2+letter3;is fine and dandy. What it actually compiles to is
    String letters = new StringBuffer().append(letter1).append(letter2).append(letter3).toString();Which ofcourse is much more code to write, but still good to know.
    So do see the API for java.lang.StringBuffer.
    Heikki

  • Passing variable number of arguments in a stored procedure

    Hi Team,
    i am facing a problem. I have a dynamic form which contains some checkboxes. The number of checkboxes are dynamically generated on querying the database. On the form submission i want to call a stored procedure that will update the values in the database. i want to know that is there any way to handle variable number of arguments in the stored procedure or can i get the variables through some session context and use it in my stored procedure.
    Any help is greatly appreciated.
    Thanks&Regards
    Saurabh Jain

    Hi Saurabh,
    The method in which stored procedures are called on form submit is something as follows.
    Let us take your scenario of a form which has multiple checkboxes and a submit button. On clicking the submit button, this form data is submitted using either get or post. The form's submit action invokes a procedure.
    The HTML form code will look something like this..
    htp.formOpen( curl => 'URL /myProcedure',
    cmethod => 'post' );
    htp.formCheckbox( cname => 'myCheckbox'
    cvalue => 'A');
    htp.formCheckbox( cname => 'myCheckbox'
    cvalue => 'B');
    htp.formCheckbox( cname => 'myCheckbox'
    cvalue => 'C');
    htp.formSubmit( cname => 'myButton',
    cvalue => 'OK');
    Now, whenever the submit button is clicked, all these form values are passed to our stored procedure 'myProcedure'.
    "myProcedure" looks something like this.
    procedure myProcedure
    myCheckbox IN sys.owa_util.vc_arr,
    myButton IN VARCHAR2
    is
    begin
    end myProcedure;
    The point to be noted here is that the name of the variable being passed in the procedure is the same as the name of the HTML element being created in the HTML form. So, there is a direct mapping between the elements in the HTML form and the procedure parameters.
    Another noteworthy point is that since you have multiple checkboxes in your HTML form, it is impractical to name all the checkboxes differently and then pass those many parameters to your procedure (Imagine a scenario where there are a hundred check-boxes in an HTML form!). So portal allows you to give the same name (cname) to all the checkboxes in your HTML form, and if multiple checkboxes are checked, it will return all the checkbox values in an array (Note the usage of "myCheckbox IN sys.owa_util.vc_arr" in myProcedure).
    You can check out this link for more information.
    Re: retrieving data from fields
    Thanks,
    Ashish.

  • T-sql 2008 r2 place results from calling a stored procedure with parameters into a temp table

    I would like to know if the following sql can be used to obtain specific columns from calling a stored procedure with parameters:
    /* Create TempTable */
    CREATE TABLE #tempTable
    (MyDate SMALLDATETIME,
    IntValue INT)
    GO
    /* Run SP and Insert Value in TempTable */
    INSERT INTO #tempTable
    (MyDate,
    IntValue)
    EXEC TestSP @parm1, @parm2
    If the above does not work or there is a better way to accomplish this goal, please let me know how to change the sql?

    declare @result varchar(100), @dSQL nvarchar(MAX)
    set @dSQL = 'exec @res = TestSP '''+@parm1+''','' '''+@parm2+' '' '
    print @dSQL
      EXECUTE sp_executesql @dSQL, N'@res varchar(100) OUTPUT', @res = @result OUTPUT
    select @result
    A complicated way of saying
    EXEC @ret = TestSP @parm1, @parm2
    SELECT @ret
    And not only compliacated, it introduces a window for SQL injection.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Passing Variable Number of Parameters to Cobol Stored Procedure

    Hi. I have a web front end that needs to access several different tables via Cobol stored procedures. It seems simple enough to call the stored procedures straight away (DAO Pattern perhaps?) but my boss is insistent on having an intermediate Cobol program that decides which table to access. I think he at a bigger picture than I can see.
    The problem lies in the number of parameters that need to be passed to the stored procedures; some need 3, others needs 5, a few need 4. The only two solutions that I can think of are to pass EVERYTHING (we're talking 50 parameters or so) to the intermediate stored procedure and then pulling only what is needed from that data set to access the desired table. Solution number two involves passing everything to a temp table and then pulling what is needed from it. The former solution seems a little cleaner but still involves passing a lot of parameters. If Cobol could handle some sort of dynamic memory allocation (Vector) there seems to be a possible solution there. Though, as far as I know, that isn't possible.
    Any ideas are much appreciated.
    Thanks in advance,
    Chris

    Hi Saurabh,
    The method in which stored procedures are called on form submit is something as follows.
    Let us take your scenario of a form which has multiple checkboxes and a submit button. On clicking the submit button, this form data is submitted using either get or post. The form's submit action invokes a procedure.
    The HTML form code will look something like this..
    htp.formOpen( curl => 'URL /myProcedure',
    cmethod => 'post' );
    htp.formCheckbox( cname => 'myCheckbox'
    cvalue => 'A');
    htp.formCheckbox( cname => 'myCheckbox'
    cvalue => 'B');
    htp.formCheckbox( cname => 'myCheckbox'
    cvalue => 'C');
    htp.formSubmit( cname => 'myButton',
    cvalue => 'OK');
    Now, whenever the submit button is clicked, all these form values are passed to our stored procedure 'myProcedure'.
    "myProcedure" looks something like this.
    procedure myProcedure
    myCheckbox IN sys.owa_util.vc_arr,
    myButton IN VARCHAR2
    is
    begin
    end myProcedure;
    The point to be noted here is that the name of the variable being passed in the procedure is the same as the name of the HTML element being created in the HTML form. So, there is a direct mapping between the elements in the HTML form and the procedure parameters.
    Another noteworthy point is that since you have multiple checkboxes in your HTML form, it is impractical to name all the checkboxes differently and then pass those many parameters to your procedure (Imagine a scenario where there are a hundred check-boxes in an HTML form!). So portal allows you to give the same name (cname) to all the checkboxes in your HTML form, and if multiple checkboxes are checked, it will return all the checkbox values in an array (Note the usage of "myCheckbox IN sys.owa_util.vc_arr" in myProcedure).
    You can check out this link for more information.
    Re: retrieving data from fields
    Thanks,
    Ashish.

  • How do I insert multiple values into different fields in a stored procedure

    I am writing a Stored Procedure where I select data from various queries, insert the results into a variable and then I insert the variables into final target table. This works fine when the queries return only one row. However I have some queries that return multiple rows and I am trying to insert them into different fields in the target table. My query is like
    SELECT DESCRIPTION, SUM(AMOUNT)
    INTO v_description, v_amount
    FROM SOURCE_TABLE
    GROUP BY DESCRIPTION;
    This returns values like
    Value A , 100
    Value B, 200
    Value C, 300
    The Target Table has fields for each of the above types e.g.
    VALUE_A, VALUE_B, VALUE_C
    I am inserting the data from a query like
    INSERT INTO TARGET_TABLE (VALUE_A, VALUE_B, VALUE_C)
    VALUES (...)
    How do I split out the values returned by the first query to insert into the Insert Statement? Or do I need to split the data in the statement that inserts into the variables?
    Thanks
    GB

    "Some of the amounts returned are negative so the MAX in the select statement returns 0 instead of the negative value. If I use MIN instead of MAX it returns the correct negative value. However I might not know when the amount is going to be positive or negative. Do you have any suggestions on how I can resolve this?"
    Perhaps something like this could be done in combination with the pivot queries above, although it seems cumbersome.
    SQL> with data as (
      2        select  0 a, 0 b,  0 c from dual   -- So column a has values {0, 1, 4},
      3  union select  1 a, 2 b, -3 c from dual   --    column b has values {0, 2, 5},
      4  union select  4 a, 5 b, -6 c from dual ) --    column c has values {0, -3, -6}.
      5  --
      6  select  ( case when max.a > 0 then max.a else min.a end) abs_max_a
      7  ,       ( case when max.b > 0 then max.b else min.b end) abs_max_b
      8  ,       ( case when max.c > 0 then max.c else min.c end) abs_max_c
      9  from    ( select  ( select max(a) from data ) a
    10            ,       ( select max(b) from data ) b
    11            ,       ( select max(c) from data ) c
    12            from      dual ) max
    13  ,       ( select  ( select min(a) from data ) a
    14            ,       ( select min(b) from data ) b
    15            ,       ( select min(c) from data ) c
    16            from      dual ) min
    17  /
    ABS_MAX_A  ABS_MAX_B  ABS_MAX_C
             4          5         -6
    SQL>

  • MS SQL Server 7 - Performance of Prepared Statements and Stored Procedures

    Hello All,
    Our team is currently tuning an application running on WL 5.1 SP 10 with a MS
    SQL Server 7 DB that it accesses via the WebLogic jConnect drivers. The application
    uses Prepared Statements for all types of database operations (selects, updates,
    inserts, etc.) and we have noticed that a great deal of the DB host's resources
    are consumed by the parsing of these statements. Our thought was to convert many
    of these Prepared Statements to Stored Procedures with the idea that the parsing
    overhead would be eliminated. In spite of all this, I have read that because
    of the way that the jConnect drivers are implemented for MS SQL Server, Prepared
    Statments are actually SLOWER than straight SQL because of the way that parameter
    values are converted. Does this also apply to Stored Procedures??? If anyone
    can give me an answer, it would be greatly appreciated.
    Thanks in advance!

    Joseph Weinstein <[email protected]> wrote:
    >
    >
    Matt wrote:
    Hello All,
    Our team is currently tuning an application running on WL 5.1 SP 10with a MS
    SQL Server 7 DB that it accesses via the WebLogic jConnect drivers.The application
    uses Prepared Statements for all types of database operations (selects,updates,
    inserts, etc.) and we have noticed that a great deal of the DB host'sresources
    are consumed by the parsing of these statements. Our thought was toconvert many
    of these Prepared Statements to Stored Procedures with the idea thatthe parsing
    overhead would be eliminated. In spite of all this, I have read thatbecause
    of the way that the jConnect drivers are implemented for MS SQL Server,Prepared
    Statments are actually SLOWER than straight SQL because of the waythat parameter
    values are converted. Does this also apply to Stored Procedures???If anyone
    can give me an answer, it would be greatly appreciated.
    Thanks in advance!Hi. Stored procedures may help, but you can also try MS's new free type-4
    driver,
    which does use DBMS optimizations to make PreparedStatements run faster.
    Joe
    Thanks Joe! I also wanted to know if setting the statement cache (assuming that
    this feature is available in WL 5.1 SP 10) will give a boost for both Prepared Statements
    and stored procs called via Callable Statements. Pretty much all of the Prepared
    Statements that we are replacing are executed from entity bean transactions.
    Thanks again

  • Attempting to Save data from an access database file into a local variable for use.

    Hello! i'm trying to develop a small text based game in Visual Basic 2013 and I've recently decided i need to use a more sophisticated data storage system then dozens of .txt files and stream-readers. i'm using Microsoft access and i completed my database
    last night. it stores the stat and skill values of the player-character and the non-player characters. the problem is i cannot bring the data into visual basic in a usable way. using ado.net i can bring a single record into the system as a detail view and
    then read the data in from the labels but i'd far prefer to have it done purely through code. the book i purchased only covers data grid views and detail view and I've spent several hours searching for a solution online. 
    for clarification. i need to read each value in a record into a variable so i can calculate the stats for the games combat system.

    So, you want to select from MS Access?
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind_2012.mdb"
    Dim selectCommand As String
    Dim connection As New OleDbConnection(connectionString)
    selectCommand = "Select * From MyExcelTable ORDER BY ID"
    Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
    With DataGridView1
    .AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
    .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
    .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
    End With
    Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
    Dim table As New DataTable()
    table.Locale = System.Globalization.CultureInfo.InvariantCulture
    Me.dataAdapter.Fill(table)
    Me.bindingSource1.DataSource = table
    Dim data As New DataSet()
    data.Locale = System.Globalization.CultureInfo.InvariantCulture
    DataGridView1.DataSource = Me.bindingSource1
    Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
    Me.DataGridView1.AutoResizeColumns( _
    DataGridViewAutoSizeColumnsMode.AllCells)
    End Sub
    Then from DataGridView to a text file, right.
    Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim dt As DataTable = New DataTable
    Dim DBAdapter As OleDbDataAdapter = New OleDbDataAdapter
    Dim connection As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Excel\\Desktop\\Coding\\Microsoft Access\\Nor"& _
    "thwind.mdb;Jet OLEDB:System Database=system.mdw")
    Dim query As String = "SELECT * FROM Orders;"
    connection.Open
    Dim command As OleDbCommand = New OleDbCommand(query, connection)
    Dim adapter As OleDbDataAdapter = New OleDbDataAdapter(command)
    adapter.Fill(dt)
    Dim writer As StreamWriter = New StreamWriter("C:\\Users\\Excel\\Desktop\\FromAccess.txt")
    For Each Row As DataRow In dt.Rows
    For Each values As Object In Row.ItemArray
    writer.Write(values)
    Next
    Next
    writer.Close
    End Sub
    Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

  • How to define a TYPE REF TO data into my local variable/structure?

    Hello,
    I am trying to implementing a BADI, in its signature part,
    c_accit TYPE REF TO data.
    My pseudo code goes like,
    DATA: l_itm_details TYPE REF TO data.
    l_itm_details = c_accit.
    l_itm_details-koart = 'D' =====> here am getting error!
    * Do processing
    ENDIF.
    Here am getting error that, l_itm_details is not a structure! Pls. let me know how to fix it?
    Thank you

    Hello,
    c_accit TYPE REF TO data.
    C_ACCIT is a "data reference" parameter. In order to access its components you have to "de-reference" it!
    FIELD-SYMBOLS: <l_itm_details> TYPE ANY,
    <l_value> TYPE ANY.
    ASSIGN c_accit->* TO <l_itm_details>."De-reference the data reference
    ASSIGN COMPONENT 'KOART' OF STRUCTURE <l_itm_details> TO <l_value>.
    If you know the structure of the data reference variable you can define your field-symbol <l_itm_details> of that type directly, else you can define a generic type as mentioned in the code snippet.
    BR,
    Suhas

  • 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

  • How to call a session variable into sql?

    for example, I have a coldfusion session variable - session.testvar
    I am writing a Stored procedure in sql server 2000. The query within my stored procedure needs to insert a value into a table. The value needs to be my CF session variable. I have no idea how this is done, does anyone else have a hunch?
    I am using coldfusion 8 and sql server 2000.

    Pass it to the SP as a variable
    - there are examples in the cf docs

  • How do i declare a user defined table type sproc parameter as a local variable?

    I have a procedure that uses a user defined table type.
    I am trying to redeclare the @accountList parameter into a local variable but it's not working and says that i must declare the scalar variable @accountList.this is the line that is having the issue: must declare the scalar variable @accountListSET @local_accountList = @accountListALTER PROCEDURE [dbo].[sp_DynamicNumberVisits] @accountList AS integer_list_tbltype READONLY
    ,@startDate NVARCHAR(50)
    ,@endDate NVARCHAR(50)
    AS
    BEGIN
    DECLARE @local_accountList AS integer_list_tbltype
    DECLARE @local_startDate AS NVARCHAR(50)
    DECLARE @local_endDate AS NVARCHAR(50)
    SET @local_accountList = @accountList
    SET @local_startDate = @startDate
    SET @local_endDate = @endDate
    CREATE TYPE [dbo].[integer_list_tbltype] AS TABLE(
    [n] [int] NOT NULL,
    PRIMARY KEY CLUSTERED
    [n] ASC
    )WITH (IGNORE_DUP_KEY = OFF)
    GO

    Why are you asking how to be an awful SQL programmer??  Your whole approach to SQL is wrong.
    We have a DATE data type so your insanely long NVARCHAR(50) of Chinese Unicode strings is absurd. Perhaps you can post your careful research on this? Can you post one example of a fifty character date in any language? 
    The use of the "sp_" prefix has special meaning in T-SQL dialect. Good SQL programmers do not use CREATE TYPE for anything. It is dialect and useless. It is how OO programmers fake it in SQL. 
    The design flaw of using a "tbl-" prefix on town names is called "tibbling" and we laugh at it. 
    There are no lists in RDBMS; all values are shown as scalar values. First Normal Form (1NF)? This looks like a set, which would have a name. 
    In any -- repeat any -- declarative programming language, we do not use local variables. You have done nothing right at any level. You need more help than forum kludges. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Inserting in the UUT_Results table a value that we read from our data base from a local variable

    We would like to include in the UUT_Results table a value that we read from our data base into a local variable during the execution of our sequence file. We found that by modifying the configure database options we were able to add a column for this variable, but the local variable was not available to be placed into an expression for that column from the local variables or parameters. Is it possible to do this, and if so, how? Station Globals were available to be included in the expression, however the sequence file may be executed on more than one system which makes the Global unavailable on systems other than the one where the sequence file originated.

    You can use the TestStand API to programmatically create global variables at runtime, thus ensuring their existence. For example, you could call Engine.Globals.SetValString("GlobalStringVariableName", PropOption_InsertIfMissing, "variable value")
    Of course, if you need to test multiple UUTs in parallel, a single global is not sufficient. In that case you might consider adding the field you need to the UUT datatype in the process model. You could then access the field in your sequence via RunState.Root.Locals.UUT.YourNewField = YourNewValue.
    If you also want your sequence to run without using a process model, you must check for the existence of the UUT before accessing it. You could use the expression function: PropertyExists("RunState.Root.Locals.UUT.YourNewFi
    eld")

  • How do I get sdo_point into C host variables from OTT structures?

    How do I get sdo_point info into C host variables from structures generated by OTT?
    Databse Version 10.1.0
    I am using OTT to generate C structures for the Oracle Spatial datatype sdo_geometry. The file is generated as
    #ifndef GEOMETRY_ORACLE
    # define GEOMETRY_ORACLE
    #ifndef OCI_ORACLE
    # include <oci.h>
    #endif
    typedef OCIRef sdo_geometry_ref;
    typedef OCIRef sdo_point_type_ref;
    typedef OCIArray sdo_elem_info_array;
    typedef OCIArray sdo_ordinate_array;
    struct sdo_point_type
    OCINumber x;
    OCINumber y;
    OCINumber z;
    typedef struct sdo_point_type sdo_point_type;
    struct sdo_point_type_ind
    OCIInd _atomic;
    OCIInd x;
    OCIInd y;
    OCIInd z;
    typedef struct sdo_point_type_ind sdo_point_type_ind;
    struct sdo_geometry
    OCINumber sdo_gtype;
    OCINumber sdo_srid;
    struct sdo_point_type sdo_point;
    sdo_elem_info_array * sdo_elem_info;
    sdo_ordinate_array * sdo_ordinates;
    typedef struct sdo_geometry sdo_geometry;
    struct sdo_geometry_ind
    OCIInd _atomic;
    OCIInd sdo_gtype;
    OCIInd sdo_srid;
    struct sdo_point_type_ind sdo_point;
    OCIInd sdo_elem_info;
    OCIInd sdo_ordinates;
    typedef struct sdo_geometry_ind sdo_geometry_ind;
    #endif
    I can successfully access the sdo_gtype and sdo_ordinates using the following ProC code
    exec sql begin declare section;
    int sptype;
    double coord[100000];
    sdo_geometry *spgeom;
    sdo_ordinate_array *spcoords;
    exec sql end declare section;
    /* allocate memory for the geometry host variable */
    exec sql allocate :spgeom;
    select bounds into :spgeom from boundary;
    /* retrieve the geometry type from the geometry host variable into a host variable */
    exec sql object get sdo_gtype from :spgeom into :sptype;
    /* allocate memory for the sdo_ordinate_array host variable */
    exec sql allocate :spcoords;
    /* move the coordinates from the geometry host variable into the sdo_ordinate_array host variable */
    exec sql object get sdo_ordinates from :spgeom into :spcoords;
    /* determine the number of coordinates */
    exec sql collection describe :spcoords get size into :numord;
    /* move the coordinates from the sdo_ordinate_array host variable into a host array */
    exec sql for :numord collection get :spcoords into :coord;
    I cannot, however, figure out how to get point data out of the host variable spgeom. If I prepare code analagous to the other types in the geometry structure, I get an error. I can see that sdo_point is different because it is a struct within the geometry definiton of typedef OCIRef but my knowledge of C is sufficeintly weak that I cannot figure out how to get sdo_point into C host variables. Some sample code for getting the sdo_point data would be greatly appeciated.
    Thanks, Chris

    To get point data from geometry column use following
    select a.location.sdo_point.x, a.geometrycolumn.sdo_point.y
    from tablename a;
    Do not forget to alias the table.

  • How to change value of instance variable and local variable at run time?

    As we can change value at run time using debug mode of Eclipse. I want to do this by using a standalone prgram from where I can change the value of a variable at runtime.
    Suppose I have a class, say employee like -
    class employee {
    public String name;
    employee(String name){
    this.name = name;
    public int showSalary(){
    int salary = 10000;
    return salary;
    public String showName()
    return name;
    i want to change the value of instance variable "name" and local variable "salary" from a stand alone program?
    My standalone program will not use employee class; i mean not creating any instance or extending it. This is being used by any other calss in project.
    Can someone tell me how to change these value?
    Please help
    Regards,
    Sujeet Sharma

    This is the tutorial You should interest in. According to 'name' field of the class, it's value can be change with reflection. I'm not sure if local variable ('salary') can be changed - rather not.

Maybe you are looking for

  • External Hard Drive and USB Hubs

    I need some help. I have a 320GB External Hard Drive which uses 2 USB Ports. I also have an external keyboard and mouse, using USB. I first purchased a 'passive' USB hub and the Mac was unable to recognize the External Hard Drive. So, I purchased a U

  • FCP 7 crashes on XDCAM full HD edit

    Final Cut Pro 7 crashes unexpectedly while editing on Full HD (1080i50). I copied the data directly from and SXS card of AN EX3 XDCAM. I was using n AZA KONA 3 with the following system configuration- 12GB DDR2 RAM 2 X Intel Xeon Quad Core 2.6 ghz 3

  • Trying to recover from exploded 10.4.9 update

    Hi ... I'm back -- At first I just let Software Updater do its thing (without fixing permissions). Things started getting VERY goofy and especially freezes. Finally managed to download the Combo Intel updater (after fixing the permissions) after seve

  • Add a new format number for everyone in webi

    Hi, I would like to add specific format number and date in webi for all my users. I would like to add them in the window "Format number" in the custom. I know it is possible to add in a report but when you start a new report you lose it. I want persi

  • Support will not reset security questions to allow purchases on account.

    So awhile back I decided to format my pc due to installing new components into it. I logged into my itunes account after and it told me I will need to answer my security questions in order to purchase any more songs. It also gave me the option to sen