Read a CSV file and dynamically generate the insert

I have a requirement where there are multiple csv's which needs to be exported to a sql table. So far, I am able to read the csv file and generate the insert statement dynamically for selected columns however, the insert statement when passed as a parameter
to the $cmd.CommandText
does not evaluate the values
How to evaluate the string in powershell
Import-Csv -Path $FileName.FullName | % {
# Insert statement.
$insert = "INSERT INTO $Tablename ($ReqColumns) Values ('"
$valCols='';
$DataCols='';
$lists = $ReqColumns.split(",");
foreach($l in $lists)
$valCols= $valCols + '$($_.'+$l+')'','''
#Generate the values statement
$DataCols=($DataCols+$valCols+')').replace(",')","");
$insertStr =@("INSERT INTO $Tablename ($ReqColumns) Values ('$($DataCols))")
#The above statement generate the following insert statement
#INSERT INTO TMP_APPLE_EXPORT (PRODUCT_ID,QTY_SOLD,QTY_AVAILABLE) Values (' $($_.PRODUCT_ID)','$($_.QTY_SOLD)','$($_.QTY_AVAILABLE)' )
$cmd.CommandText = $insertStr #does not evaluate the values
#If the same statement is passed as below then it execute successfully
#$cmd.CommandText = "INSERT INTO TMP_APL_EXPORT (PRODUCT_ID,QTY_SOLD,QTY_AVAILABLE) Values (' $($_.PRODUCT_ID)','$($_.QTY_SOLD)','$($_.QTY_AVAILABLE)' )"
#Execute Query
$cmd.ExecuteNonQuery() | Out-Null
jyeragi

Hi Jyeragi,
To convert the data to the SQL table format, please try this function out-sql:
out-sql Powershell function - export pipeline contents to a new SQL Server table
If I have any misunderstanding, please let me know.
If you have any feedback on our support, please click here.
Best Regards,
Anna
TechNet Community Support

Similar Messages

  • Read a csv file and read the fiscal yr in the 4th pos?

    Hello ABAP Experts,
    how to write a code for read a csv file and read the fiscal year in the 4th position.
    any suggestions or code highly appreciated.
    Thanks,
    BWer

    Hi Bwer,
    Declare table itab with the required fields...
    Use GUI UPLOAD to get the contents of the file (say abc.csv) in case if the file is on the presentation server...
    CALL FUNCTION 'GUI_DOWNLOAD'
      EXPORTING
        filename                        = 'c:\abc.csv'
       FILETYPE                        = 'ASC'
        WRITE_FIELD_SEPARATOR           = 'X'
      tables
        data_tab                        = itab
    EXCEPTIONS
       FILE_WRITE_ERROR                = 1
       NO_BATCH                        = 2
       OTHERS                          = 22
    IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
             WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    Use OPEN DATASET in case if the file is on the application server..
    After that USE SPLIT command at comma to get the contents of the 4th field...
    Regards,
    Tanveer.
    <b>Please mark helpful answers</b>

  • Read two CSV files and remove the duplicate values within them.

    Hi,
    I want to read two CSV files(which contains more than 100 rows and 100 columns) and remove the duplicate values within that two files and merge all the unique values and display it as a single file.
    Can anyone help me out.
    Thanks in advance.

    kirthi wrote:
    Can you help me....Yeah, I've just finished... Here's a skeleton of my solution.
    The first thing I think you should do is write a line-parser which splits your input data up into fields, and test it.
    Then fill out the below parse method, and test it with that debugPrint method.
    Then go to work on the print method.
    I can help a bit along the way, but if you want to do this then you have to do it yourself. I'm not going to do it for you.
    Cheers. Keith.
    package forums.kirthi;
    import java.util.*;
    import java.io.PrintStream;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import krc.utilz.io.ParseException;
    import krc.utilz.io.Filez.LineParser;
    import krc.utilz.io.Filez.CsvLineParser;
    public class DistinctColumnValuesFromCsvFiles
      public static void main(String[] args) {
        if (args.length==0) args = new String[] {"input1.csv", "input2.csv"};
        try {
          // data is a Map of ColumnNames to Sets-Of-Values
          Map<String,Set<String>> data = new HashMap<String,Set<String>>();
          // add the contents of each file to the data
          for ( String filename : args ) {
            data.putAll(parse(filename));
          // print the data to output.csv
          print(data);
        } catch (Exception e) {
          e.printStackTrace();
      private static Map<String,Set<String>> parse(String filename) throws IOException, ParseException {
        BufferedReader reader = null;
        try {
          reader = new BufferedReader(new FileReader(filename));
          CsvLineParser.squeeze = true; // field.trim().replaceAll("\\s+"," ")
          LineParser<String[]> parser = new CsvLineParser();
          int lineNumber = 1;
          // 1. read the column names (first line of file) into a List
          // 2. read the column values (subsequent lines of file) into a List of Set's of String's
          // 3. build a Map of columnName --> columnValues and return it
        } finally {
          if(reader!=null)reader.close();
      private static void debugPrint(Map<String,Set<String>> data) {
        for ( Map.Entry<String,Set<String>> entry : data.entrySet() ) {
          System.out.println("DEBUG: "+entry.getKey()+" "+Arrays.toString(entry.getValue().toArray(new String[0])));
      private static void print(Map<String,Set<String>> data) {
        // 1. get the column names from the table.
        // 2. create a List of List's of String's called matrix; logically [COL][ROW]
        // 3. print the column names and add the List<String> for this col to the matrix
        // 4. print the matrix by inerating columns and then rows
    }

  • Read from csv file and plot particular columns

    Hello,
    I`m a new user of Labview and here it comes...my first major problem.
    Maybe this has been discussed before. I’ve made a search to solve my problem first but I couldn`t find anything helpful so I `ve decided to post a new message.
    So here is my problem:
    I`m working in a small semiconductor lab where different types of nitrides are grown using proprietary reactor. The goal is to read the collected csv files from each growth in Labview and plot the acquired data in appropriate graphs.
    I have a bunch of csv files and I have to make a Labview program to read them.
    The first part of my project I`ve decided to be displaying the csv file (growth log file) under labview (which I think works fine).
    The second one is to be able to plot particular columns from the recipe in graphs in Labview (that one actually gives me a lot of trouble):
    1. Timestamp vs Temperature /columns B and D/
    2. Timestamp vs Gas flow /columns L to S/
    3. Timestamp vs Pressure /columns E,K,T,U,V/
    I`ve got one more problem. How can I convert the Timestamp shown in csv file to human readable date in labview? This actually is a big problem, because the timestamp is my x axis and I want to know at what time a particular process took place and I also want to be able to see the converted timestamp when displaying csv file at first. I`ve read a lot about time stamping in excel and timestamp in labview but I`m still confused how to convert it in my case.
    I don`t have problems displaying csv file under Labview. My problems are with the timestamp and the graphs.
    Sorry for my awful English.  I hope you can understand my problems since English is not my mother language. 
    Please find the attached files.
    If you have any ideas or suggestions I`ll be more than happy to discuss them.
    Thank you in advance.
    Have a nice day! 
    Attachments:
    growth log.csv ‏298 KB
    Read from growth log.vi ‏33 KB

    Hello again,
    I`m having problems with converting the first column in the attached above file Growth Log.csv.
    I have a code converting xl timestamp to time and using Index Array traying to grab a particular column out of it but the attached file is written in strings so I guess I have to redo it in array but I don`t know how.Would you help me with this one?
    Attachments:
    Xl Timestamp to Time.vi ‏21 KB

  • Import group members those are inactive more than 30 days to a csv file and then send the updated list by email

    Hello,
    I am very new to powershell and I have been looking for a solution where I can list all the inactive members more than 30 days from  particular groups in AD, export the updated list to a csv file and send the file by email . . Can someone help me on
    this?
    thanks

    Hi,
    Take a look at Get-ADGroupMember, Get-ADUser, Export-Csv, and Send-MailMessage:
    http://ss64.com/ps/get-adgroupmember.html
    http://ss64.com/ps/get-aduser.html
    http://ss64.com/ps/export-csv.html
    http://ss64.com/ps/send-mailmessage.html
    Let us know if you have any specific questions.
    Don't retire TechNet! -
    (Don't give up yet - 13,085+ strong and growing)

  • Reading a csv file and bind to a data grid

    hi. doing a school project and been searching. the application reads a csv file from c:\stocklist.csv, and then this in a button called btnLoadData, and now need to read in a data control called DmgDisplayData. do i put the code in the button, or in the
    data grid. been searching, but cannot seem to find any thing. so, where do i put the code, in the data control, and does any one have an example code how to read into the data fields. also need to have one field, able to edit, the other three or four fields,
    read only. can any one help me out. never covered this in the subject, but did do file streams a few years ago in vb, but usin g c#,a dn the help in visual studio, not that helpful, with a blind person using a screen reader, jaws for windows from http://www.freedomscientific.com,
    and using visual studio 2013 community edition. can any one help me out, been searching and trawling about 15 to 20 pages so far, and did try a couple of sites, but could not find, any help. thanks. the application is to read a csv file from a button, and
    load into a data grid, then have a message box, saying file load successful, then have one field, order on as edit, but the other fields, read only, so do i need the navigator buttons, for next, back, previous, etc, and how do i code that as well. not to do
    it for me, want to learn, but maybe some sample code, did do navgiator controls, years ago for a vb project, but need the c # example for that, thanks. then you have a button, Save data, that saves the csv file in the data grid. so can google for that. then
    have a toolbar, with a button saying, Sort Items, a tool strip, and when you click on that button, you have a drop down list, of three items, then a sort button, which will then sort the array in the data grid. so, do i need another form, or just do the combo
    box as an invisible control, then just refrence, that in the toolbar. so need to use th file class and an array, learnt about single and multi arrays. any ideas. thanks.
    http://startrekcafe.stevesdomain.net http://groups.yahoo.com/groups/JawsOz

    Hi Marvin,
    -->where do i put this, in the data grid click event. or in the form load event. thanks.
    You could use this code after you initialize the DataGridView. you could put it in the form load event.
    -->what about how get the tool bar and the combo box and another button, then sort from the combo box on the array for the collumns, for to set focus to the first read collumn for the data grid. how do i do that, close the parent form, and have another
    form on the toolbar.
    Since this is another issue of this thread, I would recommend you posting it with
    another thread. We will focus on that thread to help you. Thanks for your
    understanding.
    BTW, Before you asking questions, I suggest you could learn to make it by yourself. You could begin to learn winforms in MSDN articles:
    https://msdn.microsoft.com/en-us/library/dd30h2yb%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396. Or Google it, you will get many answers. In that way, you will learn more from the questions.
    Best regards,
    Youjun Tang
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Powershell script to update a field value (recursively) in sharepoint form a .CSV file and not changing the updated by value

    need to run through a list of old to new data (.csv) file and change them in a sharepoint list - can not make it work
    here is my base attempt.
    $web = Get-SPWeb site url
    $list = $web.lists["List Name"]
    $item = $list.items.getitembyid(select from the items.csv old)
    $modifiedBy = $item["Editor"]
    #Editor is the internal name of the Modified By column
    $item["old"] = "new from the .csv file parsed by power sehll
    $ite.Syste,Update($false);
    $web.Dispose()

    Hi,
    According to your description, my understanding is that  you want to update SharePoint field value from a CSV file recursively.
    We can import CSV file using the Import-CSV –path command, then update the field value in the foreach loop.
    Here is a code snippet for your reference:
    Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    $csvVariable= Import-CSV -path "http://sp2010.contoso.com/finance/"
    # Destination site collection
    $WebURL = "http://sp2010.contoso.com/sites/Utility/"
    # Destination list name
    $listName = "Inventory"
    #Get the SPWeb object and save it to a variable
    $web = Get-SPWeb -identity $WebURL
    #Get the SPList object to retrieve the list
    $list = $web.Lists[$listName]
    #Get all items in this list and save them to a variable
    $items = $list.items
    #loop through csv file
    foreach($row in $csvVariable)
    #loop through SharePoint list
    foreach($item in $items)
    $item["ID #"]=$row."ID #"
    $item.Update()
    $web.Dispose()
    Here are some detailed articles for your reference:
    http://blogs.technet.com/b/stuffstevesays/archive/2013/06/07/populating-a-sharepoint-list-using-powershell.aspx
    http://social.technet.microsoft.com/wiki/contents/articles/25125.sharepoint-2013-powershell-to-copy-or-update-list-items-across-sharepoint-sites-and-farms.aspx
    Thanks
    Best Regards
    Jerry Guo
    TechNet Community Support

  • Reading a CSV file and producing an array of objects

    Hi everybody,
    I am writing an application which will read a cvs file and produce an array of objects.
    Can any body help me to solve this problem?
    Thanks
    Finny

    Hello,
    Have you tried this link?
    http://ostermiller.org/utils/CSV.html

  • Read from csv file and graph at certain interval

    Hi,
    I've been trying all day to modify a labView program so it reads in data from my csv file to graph temperatures from 4 ovens. The temperatures are logged in the csv file at 3s intervals and i wish to display them on 4 graphs. I've written a vi (or modified one i should say) to take in a temperature value from a numeric control. Im just having extreme difficulty with the reading part.
     If someone can help me it would be greatly appreciated.
    Best regards,
    Dawn
    Attachments:
    Oven temps.csv ‏2 KB
    Oven_level_meas.vi ‏58 KB

    Hi there,
    I have a similar problem here.  I see your point that you should read the file at once but I don't seem to be able to manage it.  Shouldn't you use some kind of
    a buffer to achieve this?  Let me tell you what I am trying to do:  I have a csv file with several columns that I want to display in several waveform charts.  Each column is a wavechart.  I should be able to change the speed at which the data is displayed.  I am able to do this because I change the wait until (ms) in the for loop.  However the application is too slow.  I think because I open the csv file in the for loop and display it while I am reading it.  I have tried to put it outside the for loop but this doesn't work.  I think I need some kind of a buffer in which the data is stored after reading it.  And then this buffer should be used in the for loop.  I have looked at the producer-consumer structure but I dont fully understand it as I am not that experienced with labview.  Any help or changes to my VI would be appreciated.  I have attached the VI and the file with meaningless data I am using for testing.
    Thanks
    Attachments:
    read_data_file_dynamically.vi ‏39 KB
    test.CSV ‏332 KB

  • How to read a CSV file and Insert data into an Oracle Table

    Hi All,
    I have a Clob file as a in parameter in my PROC. . File is comma separated.need procedure that would parse this CLOB variable and populate in oracle table .
    Please let me some suggestions on this.
    Thanks,
    Chandra R

    jeneesh wrote:
    And, please don't "hijack" 5 year old thread..Better start a new one..I've just split it off to a thread of it's own. ;)
    @OP,
    I have a Clob file as a in parameter in my PROC. . File is comma separated.need procedure that would parse this CLOB variable and populate in oracle table .You don't have a "clob file" as there's no such thing. CLOB is a datatype for storing large character based objects. A file is something on the operating system's filesystem.
    So, why have you stored comma seperated data in a CLOB?
    Where did this data come from? If it came from a file, why didn't you use SQL*Loader or, even better, External Tables to read and parse the data into structured format when populating the database with it?
    If you really do have to parse a CLOB of data to pull out the comma seperated values, then you're going to have to write something yourself to do that, reading "lines" by looking for the newline character(s), and then breaking up the "lines" into the component data by looking for commas within it, using normal string functions such as INSTR and SUBSTR or, if necessary, REGEXP_INSTR and REGEXP_SUBSTR. If you have string data that contains commas but uses double quotes around the string, then you'll also have the added complexity of ignoring commas within such string data.
    Like I say... it's much easier with SQL*Loader of External Tables as these are designed to parse such CSV type data.

  • How do i read a text file and then display the content as a string

    I also would like to strip the string from a certain substring and convert the remaining string into an array of floating point numbers. I was thinking of using the read from spreadsheet vi but I'm not exactly sure if that is going to work. Any help would be greatly appreciated.
    Solved!
    Go to Solution.

    Here is what I have so far. What I am trying to do is to display the text file as a string and then strip the "curve" from the text file. I think I did this successfully. Now I want to convert the remaining string into an array of floating point numbers, and display the numbers into an array and on a waveform graph.
    Attachments:
    hw3datafile.txt ‏1 KB
    Q4.vi ‏7 KB

  • Read a csv file and update sql db

    I'm a newbie to C#. I've put together the code below - see two commented lines where the for loop starts. need advise as to the correct approach. you may insert pseudo
    code in appropriate places. Thanks in advance.
    Below is my code:
    public class MailingConfirmationService
            private SqlConnection _con = new SqlConnection(ConfigurationManager.AppSettings.Get("ConnectionString"));
            public void ProcessFilesForMailingConfirmation()
                //Process file(s)
                IResource resourceFile = ResourceFactory.GetResourceFile(ResourceList.FileLocation);
                DirectoryInfo dataFiles = new DirectoryInfo(resourceFile.GetString("filesourcelocation"));
                if (dataFiles.GetFiles().Length > 0)
                    log.Info("File Processing started");
                    foreach (FileInfo dataFile in dataFiles.GetFiles("*.csv"))
                        log.Info("Processing Data File: " + dataFile.Name);
                        if (dataFile != null && dataFile.Name.Contains("IN"))
                            foreach (string sLine in File.ReadLines(dataFile))                     
                                      _con.Open();
                                    cmd.ExecuteNonQuery();
                                    _con.Close();

    The   foreach (string sLine in File.ReadLines(dataFile))
      should be  foreach (string sLine in File.ReadLines(dataFile.FullName))
    its expecting path as param.
    Check also for this example to enumerate files and their lines:
    https://msdn.microsoft.com/en-us/library/dd383503%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
    Fouad Roumieh

  • How do I compare two csv files and not disable the user if the username is found in the 2nd file using powershell?

    Hi Guys
    I have two csv files with the following headers and I need to import both files into the script to check whether the StaffCode is present in the Creation/Renewal of Contract csv in a DisableAccount Script so I can stop any action to disable the account as
    the staff has renewed the contract with the company so the account should not be disabled.
    However my accounts are still being disabled. I am not sure now to construct the query so that it detects that the account is to be left alone if the staffcode is present in both files
    I does recognize that the $staffcodeN in the renewal file matches the $staffcode in the termination file
    but still proceeds to disable or set an expiry date to the account anyway based on the termination file. 
    How do I stop it from doing that?
    1)In the Creation/Renewal of contract file the following headers are present
         -  TranCode,StaffCode,LastName,FirstName,SocialSecurityNo,DateJoin,Grade,Dept,LastUpdateDate,EffectiveDate
    2)In the Disable of contract file the following headers are present
        - TranCode,StaffCode,LastName,FirstName,SocialSecurityno,LastDateWorked,Grade,Dept,LastUpdateDate,
    My data is not very clean , I have a-lot of special characters such as = , ' ,/ and \ characters to remove first before i can compare the data
    Thanks for the help in advance.
    Yours Sincrely
    Vicki
    The following is a short snippet of the code 
    $opencsv = import-csv "D:\scripts\Termination.csv"
    $opencsv2 = import-csv "D:\scripts\RenewContractandNewStaff.csv"
    foreach ($usertoaction in $opencsv) 
    $Trancode = $usertoactionTranCode
    $StaffCode = $usertoaction.StaffCode.replace("=","").replace('"','')
    $LastName = [string]$usertoaction.LastName.Replace("/","\/").Replace(",","\,")
    $FirstName = [string]$usertoaction.FirstName.Replace("/","\/").Replace(",","\,")
    $socialsecurityno = $usertoaction.SocialSecurityNo.replace("=","").replace('"','')
    $DateJoin = $usertoaction.DateJoin.replace("=","").replace('"','')
    $LastDateWorked = $usertoaction.LastDateWorked.replace("=","").replace('"','')
    $Grade = [string]$usertoaction.Grade
    $Dept = [string]$usertoaction.Dept
    $LastUpdateDate = $usertoaction.LastUpdateDate.replace("=","").replace('"','')
    $AccountExpiry = [datetime]::Now.ToString($LastDateWorked)
    foreach ($usertoaction2 in $opencsv2) 
    $TrancodeN = $usertoaction2.TranCode
    $StaffCodeN = $usertoaction2.StaffCode.replace("=","").replace('"','')
    $socialsecurityNoN= $usertoaction2.SocialSecurityNo.replace("=","").replace('"','')
    $DateJoinN = $usertoaction2.DateJoin.replace("=","").replace('"','')
    $GradeN = [string]$usertoaction2.Grade
    $DeptN = $usertoaction2.Dept
    $LastUpdateDate = $usertoaction.LastUpdateDate.replace("=","").replace('"','')
    $EffectiveDate = $usertoaction.EffectiveDate.replace("=","").replace('"','')
    $LastName2 = [string]$usertoaction2.LastName.Replace(",", "").Replace("/","").trim()
    $FirstName2 = [string]$usertoaction2.FirstName.Replace("/","").trim()
    # Use DirectorySearcher to find the DN of the user from the sAMAccountName.
    $Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
    $Root = $Domain.GetDirectoryEntry()
    $Searcher = [System.DirectoryServices.DirectorySearcher]$Root
    $Searcher.Filter = "(sAMAccountName=$samaccountname)"
    $doesuserexist1 = $Searcher.Findall()
    if ($doesuserexist1 -eq $Null)
    {Write-Host $samaccountname "account does not exist"}
    elseif ($StaffCodeN -match $staffcode)
    write-host "user has renewed the contract, no action taken"
    else
    if(($lastupdatedate -ne $null)-or($LastDateWorked -ne $null))
                        write-host "Setting Account Expiry to"$accountexpirydate
    #$ChangeUser.AccountExpires = $accountexpirydate
               #$Changeuser.setinfo()
    if ($UserMailforwarding -ne $null)
    #Set Account expiry date to Last Date Worked
    # $ChangeUser.AccountExpires = $accountexpirydate
    # $Changeuser.setinfo()
     write-host "staff" $displayname "with staff employee no" $samaccountname "has                          
    mailforwarding" 
    Write-host "Please disable the account manually via Active Directory Users & Computers and 
    Elseif ($accountexpirydate -lt $todaysdate)
    #disable the account

    Hi Vicki,
    This Forum has an insert-codeblock function. Using it will make your script far more readable
    Your script is missing some parts, it is impossible to follow the problem.
    You are performing the same string cleaning action on $opencsv2 for each element in $opencsv, when doing it once should suffice. Why not start it all by cleaning the values and storing the cleaned values in new arrays?
    The Compare-Object function is great, why not take it out for a stroll on these lists, it might just safe you lots of unnecessarily complicated code ...
    You are creating a new $Domain, $Root and $Searcher object each iteration, when doing it once should suffice. Probably not much of a time-saver, but every little thing contributes.
    Try pinpointing the problem by doing extensive logging, not only by writing which action was taken, but writing the inidividual information (variables, mostly) before evaluation occurs. Your if/elseif/else looks sound, so if it's still not doing what you
    want, the ingoing data must be different from what you think should be there.
    Cheers,
    Fred
    There's no place like 127.0.0.1

  • Reading csv file how to get the Column name

    Hi,
    I am trying to read a csv file and then save the data to Oracle.
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection c = DriverManager.getConnection("jdbc:odbc:;Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=.;Extensions=csv,txn");
    Statement stmt = c.createStatement();
    ResultSet rs = stmt.executeQuery("select * from filename.csv");
    while(rs.next())
       System.out.println(rs.getString("Num"));
    My csv file looks like this:
    "CHAM-23","COMPANY NAME","Test","12",20031213,15,16
    Number,Environ,Envel,Date,Time
    "1","2",3,"4",5
    "6","7",8,"9",9
    Now is there anyway using the above code I start processing the file from the second row that holds the names of the columns and skip the first row. And also can I get the name of the column using ResultSet something like:
    if columnName.equals("Number")
    Because I may have a csv file that could have more columns:
    "CHAM-24","COMPANY NAME","Test","12",20031213,16,76
    Number,Environ,Envel,Date,Time,Total,Count
    "1","2","3","4","5",3,9
    "6","7","8","9",9",,2
    So I want to get the column name and then based on that column I do some other processing.
    Once I read the value of each row I want to save the data to an Oracle Table. How do I connect to Oracle from my Application. As the database is on the server. Any help is really appreciated. Thanks

    The only thing I could think of (and this is a cluj) would be to attempt to parse the first element of each row as a number. If it fails, you do not have a column name row. You are counting on the fact that you will never have a column name that is a number in the first position.
    However, I agree that not always placing the headers in the same location is asking for trouble. If you have control over the file, format it how you want. If someone else has control over the file, find out why they are doing it that way. Maybe there is a "magic" number in the first row telling you where to jump.
    Also, I would not use ODBC to simply parse a CSV file. If the file is formatted identically to Microsoft's format (headers in first row, all subsequent rows have same number of columns), then it's fine to take a shortcut and not write your own parser. But if the file is not adhering to that format, don't both using the M$ ODBC driver.
    - Saish
    "My karma ran over your dogma." - Anon

  • Read a csv file, fill a dynamic table and insert into a standard table

    Hi everybody,
    I have a problem here and I need your help:
    I have to read a csv file and insert the data of it into a standard table.
    1 - On the parameter scrreen I have to indicate the standard table and the csv file.
    2 - I need to create a dynamic table. The same type of the one I choose at parameter screen.
    3 - Then I need to read the csv and put the data into this dynamic table.
    4 - Later I need to insert the data from the dynamic table into the standard table (the one on the parameter screen).
    How do I do this job? Do you have an example? Thanks.

    Here is an example table which shows how to upload a csv file from the frontend to a dynamic internal table.  You can of course modify this to update your database table.
    report zrich_0002.
    type-pools: slis.
    field-symbols: <dyn_table> type standard table,
                   <dyn_wa>,
                   <dyn_field>.
    data: it_fldcat type lvc_t_fcat,
          wa_it_fldcat type lvc_s_fcat.
    type-pools : abap.
    data: new_table type ref to data,
          new_line  type ref to data.
    data: xcel type table of alsmex_tabline with header line.
    selection-screen begin of block b1 with frame title text .
    parameters: p_file type  rlgrap-filename default 'c:Test.csv'.
    parameters: p_flds type i.
    selection-screen end of block b1.
    start-of-selection.
    * Add X number of fields to the dynamic itab cataelog
      do p_flds times.
        clear wa_it_fldcat.
        wa_it_fldcat-fieldname = sy-index.
        wa_it_fldcat-datatype = 'C'.
        wa_it_fldcat-inttype = 'C'.
        wa_it_fldcat-intlen = 10.
        append wa_it_fldcat to it_fldcat .
      enddo.
    * Create dynamic internal table and assign to FS
      call method cl_alv_table_create=>create_dynamic_table
                   exporting
                      it_fieldcatalog = it_fldcat
                   importing
                      ep_table        = new_table.
      assign new_table->* to <dyn_table>.
    * Create dynamic work area and assign to FS
      create data new_line like line of <dyn_table>.
      assign new_line->* to <dyn_wa>.
    * Upload the excel
      call function 'ALSM_EXCEL_TO_INTERNAL_TABLE'
           exporting
                filename                = p_file
                i_begin_col             = '1'
                i_begin_row             = '1'
                i_end_col               = '200'
                i_end_row               = '5000'
           tables
                intern                  = xcel
           exceptions
                inconsistent_parameters = 1
                upload_ole              = 2
                others                  = 3.
    * Reformt to dynamic internal table
      loop at xcel.
        assign component xcel-col of structure <dyn_wa> to <dyn_field>.
        if sy-subrc = 0.
         <dyn_field> = xcel-value.
        endif.
        at end of row.
          append <dyn_wa> to <dyn_table>.
          clear <dyn_wa>.
        endat.
      endloop.
    * Write out data from table.
      loop at <dyn_table> into <dyn_wa>.
        do.
          assign component  sy-index  of structure <dyn_wa> to <dyn_field>.
          if sy-subrc <> 0.
            exit.
          endif.
          if sy-index = 1.
            write:/ <dyn_field>.
          else.
            write: <dyn_field>.
          endif.
        enddo.
      endloop.
    REgards,
    RIch Heilman

Maybe you are looking for

  • Setting up boot WIM... but having trouble setting up the correct NIC driver

    I'm trying to setup a network boot with Windows Deployment Services. Pretty straightforward (http://technet.microsoft.com/en-us/library/cc766320.aspx). Problem though is the OOTB Vista & Win2k8 boot.wim file don't include the necessary driver for the

  • Filters Sometimes Missing Windows 7 64bit

    Weird problem. If I open an image from Windows Explorer to Photoshop (by doubling clicking the image in Explorer), I have no add-on filters available in PS. Programs normally listed under the Automate menu are also missing. If I open Photoshop first,

  • Restoring iphone to ipod

    I have an old iphone 3GS that was a work phone.  It no longer has a SIM Card, but I was using it as an ipod.  I needed to restore it, but now it is looking for the SIM card to finish the setup.  Is there anyway to get through the setup without the SI

  • Inter Company Individual Purchase order!

    Hi All, I need you help on this . Please find the scenario below. Cusotme places order of Mat-A to Company A. The Company A creates PO to Company B. Company B delivers to Company A and then invoices Company A.  Company A recives the goods into own st

  • Windows 7 as Server?

    Hi all, In theory, can we use Windows 7 as the server OS for Sap Business One? We are on 8.81 at the moment, but can upgrade as needed. SQL shouldn't be an issue, but was thinking more about SAP B1 Server Tools. Looking to get rid of the old SBS 2003