LINQ: Update a column with auto increment value

Hi All,
Greetings.
I am very new to C# (though with lot of experience in VC++). Now a days, I am engaged in a C# project where I need to deal with ADO.NET DataTable and related classes. I am stuck up in a scenario as follows:
I have a data table (of DataTable type) pre-populated with many rows (50000+), parsed from a log file. Now I need to add a column that will be holding index number for each records; eg. 1, 2, 3......
I have tried to add the auto-incremented column dynamically, with seed = 0 and increment = 1, but it is not working.
Is there any LINQ query that I can run to update the DataTable at once? Or foreach loop per DataRow is the only option here?
I appreciate any quick suggestion on this.
Thanks in advance.
Sanjoy Jana.

You should add the auto increment column to the DataTable before you pouplate it with the other data:
//1. Create a datatable
DataTable dt = new DataTable();
//2. add the autoincrement column:
DataColumn column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.AutoIncrement = true;
column.AutoIncrementStep = 1;
column.AutoIncrementSeed = 1;
//3. Fill the dataTable using an SqlDataAdapter or whatever
dt.Columns.Add(new DataColumn("name"));
dt.Rows.Add("1");
dt.Rows.Add("2");
dt.Rows.Add("3");
dt.Rows.Add("4");
Then you don't have to add the "auto incremented" values yourself in some kind of a loop (using for example LINQ or foreach).
If you want to know how to poplulate the DataTable from a database query using an adapter, please refer to the following page:
http://www.dotnetperls.com/sqldataadapter
Hope that helps.
Please remember to mark helpful posts as answer to close your threads and then start a new thread if you have a new question.

Similar Messages

  • How to create auto increment value in my column using identity ?

    hi Team,
    I have an requirement where i create an auto increment value ,with my table column
    Create table Temp(
    DeptID int IDENTITY(1,1) PRIMARY KEY,
    Name varchar(50),
    Emailid nvarchar(50),
    Phone varchar(50)
    so this is my table structure ,Here my column name is
    Deptid here i need to creat an autoincrement value with today's date like below
    ex:STM0000120012015
        STM0000221012015
        STM0000322012015(Currentdate)
    .......................................... like this
    Here i need  only one column like identity column with the given incremental order,not more than one column
    so can u pls help me out any one.
    Thanks!

    Here the output came like this ,
    1 STM0000120150121
    2 STM0000220150121
    3 STM0000320150121
    4 STM0000420150121
    5 STM0000520150121
    6 STM0000620150121
    7 STM0000720150121
    8 STM0000820150121
    9 STM0000920150121
    10 STM00001020150121 --see this exceed length
    and here i dnt need to increment that Stm000010,Here my output will come like this, idnt need to increment my charcter size
    1 STM0000120150121
    2 STM0000220150121
    3 STM0000320150121
    4 STM0000420150121
    5 STM0000520150121
    6 STM0000620150121
    7 STM0000720150121
    8 STM0000820150121
    9 STM0000920150121
    10 STM0001020150121
    11    STM0001120150121
    12    STM0001220150121 
    so here i dont  need to increment my charcter length(16)
    The length should be STM(3char)+00001(5Charcters)+CurrentDateFormat,
    see the above suggested o/p
    so can u pls help me out Dimant

  • How to update person or group column with peopleeditor control values

    Hi,
    I have created custom aspx page and added "PeopleEditor" control(can select multiple users)  in that page. Now I am trying to update person or group column with peopleeditor control values.I am not getting any error if I select single user
    in PeopleEditor control but getting error if I select more than one user.
    UpdateItem(listItem, "ListColumnName",
    listItem.ParentList.ParentWeb.EnsureUser(peopleeditorId.CommaSeparatedAccounts));
    Can anybody help me out to resolve the issue?
    Thank you in advance!!!
    AA.

    First get all the users/groups from the PeapleEditor by using PeapleEditor.ResolvedEntities
    foreach (PickerEntity pickerEntity in peopleEditor.ResolvedEntities)
    SPPrincipalType principalType = (SPPrincipalType)Enum.Parse(typeof(SPPrincipalType), pickerEntity.EntityData["PrincipalType"].ToString());
    if (principalType == SPPrincipalType.User || principalType == SPPrincipalType.SecurityGroup)
    string loginName = pickerEntity.Key;
    //your code here
    else if (principalType == SPPrincipalType.SharePointGroup)
    string groupName = pickerEntity.Key;
    //your code here
    Add all the users/groups in an instance of SPFieldUserValueCollection
    and then update your list item.
    SPFieldUserValueCollection users = new SPFieldUserValueCollection();
    users.Add(new SPFieldUserValue(web,user.ID,user.Name));
    item["YourUserColumn"] = users;
    item.Update();

  • How to update a column with default in a tabular form.

    We have a tabular form that has a submit button that does a multi row update. We would like to update a column with a defaut like APP_USER = updated user when the row is updated. Is this possible and how?

    used lovs and conditions.

  • Auto increment value

    Can i use an auto increment value in ldap entry?
    For example i can insert, for each ldap entry, an id that is different from the previous one.
    Thanks

    Can i use an auto increment value in ldap entry?
    For example i can insert, for each ldap entry, an id
    that is different from the previous one.
    ThanksI don't think that there is a "built-in" way to do this, but I have seen several methods for doing this. One way is to use a primary/unique key from another system (i.e. an employee number from an HR database), another way is to create a GUID for each object prior to creating it in the Directory. You can muck around in the schema to set a attribute globally unique, if you want to avoid doing the lookup for an existing entry when you create a new one.

  • Show row/column with empty dimension values.

    I have 2 columns where 1 column is dimension and 1 column is measure.  I need to hide the row when the dimension is empty.
    What I did is at the block I UN-TICK  "Show row/column with empty dimension values".  But it didnt works.
    Thanks.

    click on the block and add a filter with condition dimension isnotnull. this will eliminate the dimension rows with empty values.
    Thanks,
    karthik

  • Column with header data value

    Hi All.
    I have a control file which i need to add a column with header data value.
    example
    data file:
    123456;201303
    santiago;producto1;100
    santiago;producto2;200
    valparais;producto1;400
    valparais;producto3;900
    The control file skip the first column and load the three columns on the table, but, now i need to add other column with 201303 value constant of the first record and load it on the table.
    Then
    select * from table:
    santiago producto1 100 201303
    santiago producto2 200 201303
    valparais producto1 400 201303
    valparais producto3 900 201303
    How i do this in the control file?
    Regards!

    SCOTT@orcl_11gR2> host type test.dat
    123456;201303
    santiago;producto1;100
    santiago;producto2;200
    valparais;producto1;400
    valparais;producto3;900
    SCOTT@orcl_11gR2> host type test1.ctl
    options (load=1)
    load data
    infile test.dat
    replace
    into table onecol_onerow
    fields terminated by ';'
    trailing nullcols
    (filler1 filler, newcol)
    SCOTT@orcl_11gR2> host type test2.ctl
    options (skip=1)
    load data
    infile test.dat
    append
    into table test_tab
    fields terminated by ';'
    trailing nullcols
    (col1, col2, col3,
    newcol expression "(select newcol from onecol_onerow)")
    SCOTT@orcl_11gR2> create table onecol_onerow
      2    (newcol number)
      3  /
    Table created.
    SCOTT@orcl_11gR2> create table test_tab
      2    (col1   varchar2(15),
      3     col2   varchar2(15),
      4     col3   number,
      5     newcol number)
      6  /
    Table created.
    SCOTT@orcl_11gR2> host sqlldr scott/tiger control=test1.ctl log=test1.log
    SQL*Loader: Release 11.2.0.1.0 - Production on Mon May 6 10:46:44 2013
    Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.
    Commit point reached - logical record count 1
    SCOTT@orcl_11gR2> select * from onecol_onerow
      2  /
        NEWCOL
        201303
    1 row selected.
    SCOTT@orcl_11gR2> host sqlldr scott/tiger control=test2.ctl log=test2.log
    SQL*Loader: Release 11.2.0.1.0 - Production on Mon May 6 10:46:45 2013
    Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.
    Commit point reached - logical record count 4
    SCOTT@orcl_11gR2> select * from test_tab
      2  /
    COL1            COL2                  COL3     NEWCOL
    santiago        producto1              100     201303
    santiago        producto2              200     201303
    valparais       producto1              400     201303
    valparais       producto3              900     201303
    4 rows selected.

  • Update table column with same auto-increment value, via T-SQL stored procedure

    Good Evening to every one,
    I have a table 'Contracts' as we can see in the picture below (I exported my data on An Excel Spreadsheet). Table's primary key is 'ID' column.
    I am trying to create a stored procedure (i.e. updContractNum), through which I am going to update the 'Contract_Num' column, in every row where the values on Property_Code, Customer, Cust_Category and Amnt ARE EQUAL, as we can see in the schema above.
    The value of Contract_Num is a combination of varchar and auto_increment (integer). For example, the next value on 'Contract number' column will be 'CN0005' for the combination of 11032-14503-02-1450,00
    I' m trying to use CURSORS for this update but I am new in using cursors and I am stuck in whole process. I atttach my code below:
    CREATE PROCEDURE updContractNum
    AS
    --declare the variables
    DECLARE @CONTRACT_NUM VARCHAR(10); -- Contract Number. The value that will be updated on the table.
    DECLARE @CONTRACT INTEGER; -- Contract number, the auto increment section on contract number
    DECLARE @CONTR_ROW VARCHAR(200); -- Contract row. The row elements that will be using on cursor
    DECLARE CONTRACT_CURSOR CURSOR FOR -- Get the necessary fields from table
    SELECT PROPERTY_CODE, CUSTOMER, CUST_CATEGORY, AMNT
    FROM CONTRACTS;
    OPEN CONTRACT_CURSOR -- open a cursor
    FETCH NEXT FROM CONTRACT_CURSOR INTO @CONTR_ROW
    WHILE @@FETCH_STATUS = 0 -- execute the update, for every row of the tabl
    BEGIN
    --update Contract_Num, using the format coding : contract_number = 'CN' + 0001
    UPDATE CONTRACTS
    SET CONTRACT_NUM = 'CN'+@CONTRACT_NUM+1
    END
    CLOSE CONTRACT_CURSOR
    Thank you in advance!

    You dont need cursor
    You can simply use an update statement like this
    UPDATE t
    SET Contract_Num = 'CN' + RIGHT('00000' + CAST(Rnk AS varchar(5)),5)
    FROM
    SELECT Contract_Num,
    DENSE_RANK() OVER (ORDER BY Property_Code,Customer,Cust_category,Amnt) AS Rnk
    FROM table
    )t
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Insert data into Access with Auto-Increment column

    Is there anyone out there that has come across this problem I am experiencing?
    I have a form I'm trying to submit to an Access DB that has an Auto-Incremented Table Column. I have followed Stefan Cameron's instructions to a "T" on his blog page here:
    http://forms.stefcameron.com/2006/09/18/connecting-a-form-to-a-database/
    but I keep getting the following error"
    GeneralError: Operation failed.
    XFAObject.open:10:XFA:form1[0]:mysubform[0]:myEIFform[0]:overflowLeader[0]:Submit[0]:click
    open operation failed. [Microsoft][ODBC Microsoft Access Driver] Number of query values and destination fields are not the same.
    My OLEDB Connection Record Source is the SQL Query which reads: SELECT FedTaxID, LegalID FROM dbtest; My simple test DB is Access and its only 3 columns; dbID, FedTaxID, LegalID. dbID is the Auto-Incremented Column.
    If I remove the Auto column from my DB table it inserts just fine but I get this error:
    GeneralError: Operation failed.
    XFAObject.open:10:XFA:form1[0]:mysubform[0]:myEIFform[0]:overflowLeader[0]:Submit[0]:click
    ado2xfa operation failed. Item cannot be found in the collection corresponding to the requested name or ordinal.
    I've looked over alot of the blogs and other help forums and there's info on Selects, I don't find much on Inserts.
    Can anyone direct me in the right direction? Thank you.

    First, please pay attention to the forum in which you are posting.  This particular post would be more appropriate to tsql rather than datamining.  Second, what specific problem are you trying to solve.  The code you posted appears to be
    correct.  I will say that your DataTable will likely be a source of future problems if it contains only the 2 columns.

  • Update other items with the same value when when column contains Y

    CREATE TABLE TEST
       (     "QUATINTY" NUMBER(17,2),
         "AMOUNT" NUMBER(17,2),
         "ERRORRED" VARCHAR2(16 BYTE),
         "PO" VARCHAR2(12 BYTE),
         "LINE" VARCHAR2(10 BYTE),
         "SEQ" VARCHAR2(14 BYTE),
         "INVOICE" VARCHAR2(16 BYTE)
    Insert into TEST (PO,QUATINTY,AMOUNT,ERRORRED,LINE,SEQ,INVOICE) values ('123',5,50,'Y','1','1','inv1');
    Insert into TEST (PO,QUATINTY,AMOUNT,ERRORRED,LINE,SEQ,INVOICE) values ('123',5,50,null,'1','2','inv1');
    Insert into TEST (PO,QUATINTY,AMOUNT,ERRORRED,LINE,SEQ,INVOICE) values ('125',5,50,null,'1','1','inv2');
    Insert into TEST (PO,QUATINTY,AMOUNT,ERRORRED,LINE,SEQ,INVOICE) values ('125',4,50,null,'1','2','inv2');If you notice by the table above what im trying to acomplish is update the errorred column with 'Y' if any of the po and invoice are the same and have a 'Y' on the errored column.
    in other words, i should end up with 'Y' in the errorred column for INV1.
    Can someone point me in the right direction i cant for the life of me figuered this one out.

    Hi,
    Here's one way:
    UPDATE     test
    SET     errorred     = 'Y'
    WHERE     NVL (errorred, 'N') != 'Y'
    AND     (po, invoice)          IN (
                              SELECT  po, invoice
                         FROM      test
                         WHERE      errorred  = 'Y'
    ;This assumes that po and invoice are not NULL. If either column can be NULL, then the solution might be a little messier, depending on the results you want, but only a little. Post some sample data (with NULLs) that shows what kinds of situations you need to handle, and the results from that sample data.

  • Update a column with value of column of other table

    Hi,
    I am looking for an update statement for the following scenario
    With following 2 tables
    TABLE1 (Primary A, B)
    TABLE2 (Secondary C , D).
    C Column is not unique.
    Please provide me an update statement to update TABLE1.B with TABLE2.D where TABLE1. A = TABLE2.C
    Please note that TABLE2.C is not unique.
    Please let me know whether this satement is correct.
    UPDATE TABLE1
    SET B = (SELECT DISTINCT D FROM TABLE 2 WHERE A=C )
    Thanks
    Alla Kishore

    UPDATE TABLE1 T1
    SET T1.B = (SELECT DISTINCT D FROM TABLE2 T2 WHERE T2.C=T1.A )

  • How to get auto-increment value after insert on ACCESS db?

    When you insert a new record to a table with an auto-incrementing key, how do you find the value for the row you just inserted? This works differently with different databases. I know how it's done on ORACLE and mySql.
    How does it work with ACCESS through ODBC? How about MSSQL?

    I have discovered there's a LAST aggregate function which when I've tested it gets the just inserted auto-increment, but I'm not sure if it's reliable. You have to do:
    SELECT LAST(index-field) FROM table
    That ought to be faster than MAX, which I've noticed some people use. Persumable LAST will get the value from the last row in the table's natural order.
    In fact an auto-increment field has no business filling in missing slots since the main point is a a foreign key in other tables and a foreign key pointing to a deleted table row ought to be invalidated, not point to some unrelated successor record.
    I could use a separate table as a source of counters, of course, though that's one more call. In either case I'm worried about thread safety. In Oracle there are special sequence objects for this purpose which are incremented and read atomically. I'm not sure if the access driver transaction handling works adequately.
    Perhaps the safest approach might be to use a separate sequencer table and Java sychronisation to serialise access to each row in the sequencer table (assuming all the access is from the same app).

  • Update one column while getting the value in another column

    Is it possible to in one single SQL statement update two columns in a table while at the same time obtaining the value of another column, on the same row, in the same table, and independently (that is, the update of the columns has nothing to do with the data that I want from another column)*?* Of course, I can do this in two operations, one being a "select" and the other one being an "update", but since I am in the same table and even on the same row, is it really necessary to make TWO database calls? That's why I want to combine the the two SQL-statements, for reasons of presumed effiency.

    jsun wrote:
    Is it possible to in one single SQL statement update two columns in a table while at the same time obtaining the value of another column, on the same row, in the same table, and independently (that is, the update of the columns has nothing to do with the data that I want from another column)*?* Of course, I can do this in two operations, one being a "select" and the other one being an "update", but since I am in the same table and even on the same row, is it really necessary to make TWO database calls? That's why I want to combine the the two SQL-statements, for reasons of presumed effiency.Two statements != two database calls.
    At least not in terms of SQL.
    JDBC requires a 'statement' but in SQL (depending on the data source) that can include multiple statements. An obvious example of this is a stored proc but there are other ways as well.

  • Add an auto incremental value to TITLE field.

    Hi, i am currently working on a custom list in SharePoint 2010 and there is a title field. I would like to append an auto incremental variable to "Request" to make it look like:
    Request 1
    Request 2
    Request 3
    and so on...
    As you can see below, i tried to use the calculated value Request+ID, but it didn't work out. So is there anyway to solve this problem?
    <input name="ctl00$m$g_0bb0fcf5_65ea_4af9_ba76_7c0babad1a82$ctl00$ctl05$ctl00$ctl00$ctl00$ctl04$ctl00$ctl00$TextField"
    type="text" value="[Request-]&amp;[ID]"
    maxlength="50" id="ctl00_m_g_0bb0fcf5_65ea_4af9_ba76_7c0babad1a82_ctl00_ctl05_ctl00_ctl00_ctl00_ctl04_ctl00_ctl00_TextField"
    title="Title" class="ms-long ms-spellcheck-true" /><br />

    Hi andylow,
    You can also accomplish this without using a workflow but with a custom form on your list. To do this take the following steps:
    Make sure that the title field of your list is not a required value
    When you're in the list, click on the List tab in the ribbon
    There select "Customize Form"
    Your form will now open in InfoPath. In the right hand menu you will see all your data fields.
    Make the Title number field "Read Only". To do this right click the field, select properties, click on the second tab and select Read Only
    In the menu bar, click on Manage Rules
    Now click the Data tab in the menu and select Sumit Options
    In the menu that opens select the option to run rules before submit
    Now there will be a button available in the menu for Submit Options, click on that
    Now you can add rules and actions on the submit action
    Create a new Action rule and call it Initial Save
    As condition for the rule, set the condition that the Title field must be blank
    The first action of the rule will be to Submit the form. When the form is submitted it will be assigned an ID, before that will be blank
    Now add an Action to set a fields value.
    Select the Title field as the field to set
    You can set a hard coded value for the value to set but you can also click the function button, click on that
    Now another window opens where you can add fields, functions etc.
    Now first select the concat function from the function menu
    Then double click the first link in the resulting function and type Request
    Now double click the second link and select the ID field
    Now get rid of the last remaining arguments in the concat function
    Click OK until you're back in InfoPath
    Now set one more action to submit the form again
    Now ad a second rule and call that Edit
    As condition for the rule, set the condition that the Title field must be not blank
    Add the Submit Form action for this rule
    Now you can publish your form with the Quick Publish button. This is a Blue circle with a white upward arrow and a lightning bolt next to the save button in the top menu bar.
    Now when you add a new item and save it, the title will be set to Request&ID. When you edit the form no changes will be made.
    Cheers,
    Eduard Spelier

  • UPDATE multiple columns with conditional SET parameters

    I have a procedure that updates multiple columns of a table using the procedure's parameter. Is it possible to have one update statement with conditional SET parameter?
    CREATE TABLE TEMP
    (POL_NUM NUMBER,
    OED DATE,
    TERM NUMBER,
    TRANS_CD CHAR(2));
    INSERT INTO TEMP VALUES (1, '1 AUG 2009', 12, 'NB');
    INSERT INTO TEMP VALUES (2, '4 AUG 2009', 12, 'XL');
    INSERT INTO TEMP VALUES (3, '2 AUG 2009', 12, 'RN');
    COMMIT;
    CREATE OR REPLACE PROCEDURE TMP_PROC (
      pPOL_NUM NUMBER,
      pOED IN DATE,
      pTERM IN NUMBER,
      pTRANS_CD CHAR2)
    AS
    BEGIN
      IF pOED IS NOT NULL THEN
        UPDATE TEMP SET OED = pOED WHERE POL_NUM = pPOL_NUM;
      END IF;
      IF pTERM IS NOT NULL THEN
        UPDATE TEMP SET TERM = pTERM WHERE POL_NUM = pPOL_NUM;
      END IF;
      IF pTRAN_CD IS NOT NULL THEN
        UPDATE TEMP SET TRANS_CD = pTRANS_CD WHERE POL_NUM = pPOL_NUM;
      END IF;
      COMMIT;
    EXCEPTION
      WHEN OTHERS THEN
         NULL;
    END;Is it possible to replace multiple IFs from the code to have only one UPDATE statement with condition that update the column only if the passed parameter is not null? In real scenario I have more than 3 columns and I don't want to write many IF blocks.
    Please help Gurus!!
    Edited by: Kuul13 on Sep 18, 2009 1:26 PM

    Hi,
    You certainly don't want to issue separate UPDATE statements for every column; that will be really inefficent.
    SQL has several ways to implement IF-THEN-ELSE logic. CASE is the most versatile, but NVL will do everything you need for this job. You can use one of those to set a column to itself (and therefore not really update that column) when appropriate.
    For example:
    CREATE OR REPLACE PROCEDURE TMP_PROC (
      pPOL_NUM   IN       NUMBER,
      pOED          IN   DATE,
      pTERM          IN   NUMBER,
      pTRANS_CD  IN       CHAR
    AS
    BEGIN
         UPDATE  temp
         SET     oed      = NVL (poed,       oed)
         ,     term      = NVL (pterm,       term)
         ,     trans_cd = NVL (ptrans_cd, trans_cd)
         WHERE     pol_num      = ppol_num;
      COMMIT;     -- Maybe
    END    tmp_proc;"EXCEPTION WHEN OTHERS THEN NULL" is almost always a bad idea. If there's an error, don't you want to know about it? Shouldn't you at least log a message in a warnings table or something?
    Think careflully about whether or not you want to COMMIT every time you call this procedure.
    Just as it's inefficient to issue a separate UPDATE statement for every column, it's also inefficient to issue a separate UPDATE statement for every row. If efficiency is important, it should be possible to UPDATE several rows in a single UPDATE statement, using NVL (or CASE, or COALESCE, or NULLIF, or NVL2, or ...).
    This was a very well-written question! Thanks for providing the CREATE TABLE and INSERT statements, and such a clear explanation.

Maybe you are looking for

  • Help with my Dock please

    I turned my Dock transparent when positioning is on the bottom doing the following command: I need help reverting my dock back to it's origional state: When the Dock is positioned at the bottom it dosent look transparent

  • JSF Portlet using IBM RAD 6.0 and tomahawk.jar

    I am trying to use the tomahawk Date tag in a JSR 168 Portlet using IBM's RAD 6.0 but am unable to make the date's calendar button show. Has anyone been able to successfully make this work? I have the filter defined and tag mported. I get the followi

  • Varient confi

    hi friends                  i saw this  below answer from one of the thread. i am not getting clearly.plz explain. thnks venkat answer: To get the BOM Components, use Function Module CS_BOM_EXPLOSION. Use : cuobj = vbap-cuobj and mtnrv = vbap-matnr.

  • Rights Authentication Failed, Ticket expired

    Hello, I'm getting an error on remote control with rights to an pc. ZCM 10.3 and Windows XP SP3. The error is: Rights Authentication Failed. The ticket has expired. if the connection was initiated from the managed device, close the Remote Management

  • HT5527 Where do I go to upgrade my plan? Why don't you have a link? It *****!!!

    Where do I go to upgrade my plan? Why don't you have a link? It *****!!!