How to select and duplicate the records and update some column values using cursor

I have a table with 920 records, we need to update the end date to 6/30/2014 for 920 records and I need to create all 920 records with start date is 7/1/2014 and update the external value to
CCC.
Note: the table primary key is not auto increment, but I have sp to get the latest key for that.
Existing table.  
ID
Source Name
Internal value
External value
Start date
End date
1
XXX
AAA
BBB
1/1/2013
6/30/2015
Create new records
ID
Source Name
Internal value
External value
Start date
End date
921
XXX
AAA
CCC
7/1/2013
12/30/2015

Hi ManuGT
If I understand what you need then you ask for:
1. updating all current rows (920 rows in the table now)
2. insert new rows which are duplicates of the preiviews rows, but with value 'CCC' insteade of 'BBB'
If so, there is not reason to use a cursor and it is highly NOT RECOMMENDED to use ant type of loop.
You should work with SET and do it all in 2 simple queries:
-- first we duplicate the existing rows,
-- but we use the values 'CCC" and '20140107' for the new rows values
INSERT test (SourceName, InternalValue, ExternalValue, StartDate, EndDate)
select SourceName, 'CCC', ExternalValue, '20140107' , EndDate
from test
where
-- You can use any filter that you need if you dont want to update all rows
InternalValue = 'AAA' and ExternalValue = 'BBB' and StartDate = '20140101' and EndDate = '20140630'
-- Now we update the old rows (check the filter! I get only the old rows since I filter the new rown out)
UPDATE test
SET EndDate = '20140107' -- I use date in format yyyymmdd, You can use other formats as well
where
-- You can use any filter that you need if you dont want to update all rows
InternalValue = 'AAA' and ExternalValue = 'BBB' and StartDate = '20140101' and EndDate = '20140630'
Unfortunately you did not post DDL+DML! Therefore we cant see your table structure and the data sample and we can only guess. I used Saeid's post as the basic DDL+DML.
Please next time post DDL+DML
here is the full code with the DDL+DML that i used:
-- This is our DDL - A create table query:
create table test
( id int identity(1,1) primary key,
SourceName nvarchar(3),
InternalValue nvarchar(3),
ExternalValue nvarchar(3),
StartDate date,
EndDate date
go
-- This is our DML - A query that insert some sample data
declare @i int = 1 ;
while @i < 921
begin
insert test (SourceName, InternalValue, ExternalValue, StartDate, EndDate)
values ('XXX', 'AAA', 'BBB', '1/1/2014', '6/30/2014' ) ;
set @i += 1 ;
end ;
GO
-- Here is the solution for the problem as I understood your needs:
-- first we duplicate the existing rows,
-- but we use the values 'CCC" and '20140107' for the new rows values
INSERT test (SourceName, InternalValue, ExternalValue, StartDate, EndDate)
select SourceName, 'CCC', ExternalValue, '20140107' , EndDate
from test
where
-- You can use any filter that you need if you dont want to update all rows
InternalValue = 'AAA' and ExternalValue = 'BBB' and StartDate = '20140101' and EndDate = '20140630'
-- Now we update the old rows (check the filter! I get only the old rows since I filter the new rown out)
UPDATE test
SET EndDate = '20140107' -- I use date in format yyyymmdd, You can use other formats as well
where
-- You can use any filter that you need if you dont want to update all rows
InternalValue = 'AAA' and ExternalValue = 'BBB' and StartDate = '20140101' and EndDate = '20140630'
-- Here we just check how the result look like :-)
select *
from test ;
-- And since we do not realy need this table in our server... Here we clean the DDL (you probaby DO NOT WANT TO EXECUTE THIS!)
DROP table test
GO
I hope this was useful :-)
[Personal Site] [Blog] [Facebook]

Similar Messages

  • How to add same name records from datagrid,while i am selecting one of the record and click add butt

    hi  friends,
    i  am doing flex 4 mxml web application with as3,i am struck up in the following  concept,shar your suggession about this.
    i am using datagrid with 3 columns NUMBER, NAME, AMOUNT. one text box and one add button and one delete button.
    i have two records in the same name in grid, when i click one record from the grid and click ADD button means that time ,both records  AMOUNT WILL ADDED   which record having the same name and give that value in a text box.
    how to do this?
    any useful suggesssion or modal sample
    Thanks in advance,
    B.venkatesan.

    hi gajanan hiroji,
    Thanks for the useful help.
    And one more think i want ask you, i am doing web application, i am using 5 modules in that,every module in a single page.
    In this application i am using datagrid in last 3 models. the operation is same for the models, select a record from grid then click post it should move to next page.
    In that i am writting init() function . this for showing the last module posted records here while i am entering this model.
    At the panel initializing time the records loading and showing in the gird,
    i written refresh function for this .
    But some times the function working properly and show the records in grid.
    some time it wont show the records.
    refresh function not working properly..
    looking for usful suggession,
    Thanks,
    B.venkatesan.

  • How to Update some column values in some rows in an advanced table

    Hi Gurus,
    Can any body help on this issue.
    I am having a results table which is showing all the queried parties data queried in a seeded page in OCO module.
    Lets assume the table contains 10 rows with the below columns
    Party Name, Registry ID, Address Country, Match Percentage, Certification Level, Certification Reason, Internal Indicator, Status .
    Certification Level, Certification Reason and Internal Indicator are the dropdowns.
    The user want to update some of these fields values for some rows randomly.
    After doing this if he click on Save button, Only thosed changed rows need to get update using a Custom Procedure.
    But here all the rows irrespective of the change getting updated.
    So  how to capture the modified rows.
    Appreciate any inputs..
    Thanks
    Palepu
    Edited by: Palepu on 9 Aug, 2012 4:25 PM

    Not sure if you got the answer. You need to capture the row which got changed using the below and get the column value using the getAttribute method. This works for single selection row, if it is multi selection then you will have to loop through all selected rows and find the VO attribute value.
    String rowReference = pageContext.getParameter(OAWebBeanConstants.EVENT_SOURCE_ROW_REFERENCE);
    Row currentRow = am.findRowByRef(rowReference);
    String param1= (String)currentRow.getAttribute("VOAttribute");
    Let me know if there are any issues.
    Thanks
    Shree

  • How to delete same name records from datagrid,while i am selecting one of the record and delete

    hi friends,
    i am working in flex 4 mxml web application with action script....i am using a data grid and one delete button outside the gird.
    i have two records in the same name in grid, when i click one record from the grid and click delete means that time ,both records will delete from that grid
    which record having the same name..
    how to do this?
    any useful suggesssion or snippets code for this..
    Thanks in advance,
    B.venkatesan.

    hello,
    first get the length of the datagrid.
    suppose your datagrid id is db and you want to delete the the row which have same name .....
    first get the selected row and from that name of the selcted row.
    supoose selected name is
    var index:int=db.selectedindex;
    var selname:string =bd.dataprovide.getItemAt(index).name;(name id datafield of the column).
    now you got the selected name search for the same rows in datagrid.
    var totallen:int=(db.dataprovider).length;
    for(var i:int=0;i<totallen;i++)
        var  checkduplicate:string=bd.dataprovide.getItemAt(i).name;
       if(checkduplicate==selname)
         db.dataProvider.removeItemAt(i);
    this will delete all the row which are with same name with selected row name...
    Gajanan Hiroji | [email protected] | www.isacglobal.com

  • Problem in the code to update a column value based on the value of a column

    Merge into item_TMP S using items I on (S.ITL_ITEM= I.ITEM_ITEM)
    when matched then
    update set
    S.ITL_UOM = I.ITEM_UOM;
    when not matched then null;

    Try
    update Item_TMP set ITL_UOM = (select ITEM_UOM from ITEMS
                                                     where Item_TMP_TMP.ITL_ITEM = ITEMS.ITEM_ITEM
                                                      and items.ITEM_UOM is not null )
    where ITL_ITEM in   (select  ITEMS.ITEM_ITEM from ITEMS
                                                     where items.ITEM_UOM is not null )
    /Cheers, APC
    blog: http://radiofreetooting.blogspot.com

  • Workflow changing the status based some columns value

    OOB workflow SP  designer 2013
    The workflow purpose is change the status columns from
    COMPLETE to IN PROGRESS or from
    IN PROGRESS to COMPLETE according some columns value.. And if the change is from
    IN PROGRESS to COMPLETE
    there will be change in some columns like
    If alertSOP Date <= today then change the status (Columns value) from Complete to In Progress and send email to the manager (the manager email address is a column (Manager Email)
    Else pause until the alert date=Today()
    If the status (columns) = in progress send Remainder email every 10 days
    If the status change from in progress to
    Complete (BY MANAGER MANUALLY) then
     last renewed Date =TODAY()
    Valid to Review=TODAY() + 4 MONTH
     Alert  Date=today() + 5 month
    and  Due Date=today() + 6 months
    AND START THE WORKFLOW AFTER UPDATING THIS COLUMNS FOR NEXT cycle
    SharePoint List(http://server/site/..) LIST ITEMS
    Department
    Contractor
    Division
    Manager Email
    Contractor last renewed Date
    Contractor Valid to Review
    Alert SOPReview
    DueDate Review
    Status
    Workflow Status
    ABC
    JONAH
    10
    [email protected]
    01/01/2014
    05/06/2014
    5/07/2014
    5/08/2014
    COMPLETE
    paused 
    DEF
    SMITH
    20
    [email protected]
    01/01/2014
    02/03/2014
    2/28/2014
    3/20/2014
    INPROGRESS
    INPROGRESS
    Note:
    The status is changed manually by manager from IN PROGRESS TO COMPLETE
    The status from COMPLETE to IN PROGRESS is changed by event or Triggers  (based the alert date) 

    The First Part are coded as follow
    (The workflow purpose is change the status columns from COMPLETE to IN
    PROGRESS or fromIN PROGRESS to COMPLETE according
    some columns value.. And if the change is from IN
    PROGRESSto COMPLETE there
    will be change in some columns like
    If alertSOP Date <= today then change the status (Columns value) from Complete to In Progress and send email to the manager (the manager email address is a column (Manager Email)
    Else pause until the alert date=Today()
    If the status (columns) = in progress send
    Reminder email every 10 days)
    Note:
    The first if Block work as expected
    the second if block generate error.. Internal States Canceled
    RequestorId: 3b262286-66e8-5f9f-09f8-3b09c5be0ebc. Details: System.ApplicationException: HTTP 400 {"Transfer-Encoding":["chunked"],"X-SharePointHealthScore":["1"],"SPClientServiceRequestDuration":["1997"],"SPRequestGuid":["3b262286-66e8-5f9f-09f8-3b09c5be0ebc"],"request-id":["3b262286-66e8-5f9f-09f8-3b09c5be0ebc"],"X-FRAME-OPTIONS":["SAMEORIGIN"],"X-Content-Type-Options":["nosniff"],"X-MS-InvokeApp":["1;
    RequireReadOnly"],"MicrosoftSharePointTeamServices":["15.0.0.4420"],"Cache-Control":["max-age=0, private"],"Date":["Tue, 25 Mar 2014 21:25:35 GMT"],"X-AspNet-Version":["4.0.30319"],"X-Powered-By":["ASP.NET"]} at Microsoft.Activities.Hosting.Runtime.Subroutine.SubroutineChild.Execute(CodeActivityContext
    context) at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager) at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager
    bookmarkManager, Location resultLocation)

  • I selected display duplicates by mistake and can't restore my folder settings. How do I restore

    I selected 'Display duplicates' by mistake and in the music folder list that's all it shows.How do I restore my settings on my i-Tunes folder?

    At the bottom of the iTunes, centered in main panel will be a button that says Display All.
    tt2

  • I was trying to make a new screen recording using quicktimeplay, but when I watched the video after recording it all I could hear was me talking while the video was showing on the screen. How do I turn off that recording and turn the right one on? thanks

    I was trying to make a new screen recording using quicktimeplay, but when I watched the video after recording it all I could hear was me talking while the video was showing on the screen. How do I turn off that recording and turn the right one on? thanks

    Hi j2399123,
    It sounds like your screen recording is doing what it was designed to do, capture what is happening on your screen, with optional voice over with the microphone.
    Screen recording is for recording what you see on the screen, it is not a "video capture" option, like for capturing a movie with sound that is playing on your screen.
    For the QuickTime recording options, check out "Recording with QuickTime Player" in
    Mac Basics: QuickTime Player creates, plays, edits, and shares video and audio files
    http://support.apple.com/kb/ht4024
    And for screen recording specifically, there's
    QuickTime Player 10.x: Record your computer’s screen
    http://support.apple.com/kb/PH5882
    Thank you for thinking of Apple Support Communities for your support needs.
    Nubz

  • How do I select and email a whole lot of photos on my iPad from my iPad emails? It seems I have to go into Email and then insert one photo at a time? Isn't there a way to select all in the photos and then email the batch.?

    How do I select and email a whole lot of photos on my iPad from my iPad emails? It seems I have to go into Email and then insert one photo at a time? Isn't there a way to select all in the photos and then email the batch.?

    Actually, you can email up to 5 at a time from the Photos app. Select any more and the email share option will not appear.
    If you explain why you need to email large numbers of photos, we might be able to offer an alternative.

  • How to update and insert the records without using Table_comparison and Map_operation?

    How to update and insert the records without using Table_comparison and Map_operation?

    Use either join or MERGE see this Inserting, Updating, and Deleting Data by Using MERGE

  • How do I duplicate the budget and transaction tabs?

    When I duplicate the budget and trasaction tabs the transaction tab does not translate to the month of my budget that i am in.  Is there an easy way to duplicate two tabs that are initially in a new personal budget template into 12 months of the year?
    Thank you for the help.

    Hi K,
    Duplicating the Budget sheet leaves the formulas refering to the original Transactions sheet.
    Plan A
    After duplicating both sheets, rename the new sheets with something meaningful (for example Transactions January and Budget January).
    on the Budget January sheet, edit the formula in cell C2 of the Summary by Category table to this:
    =SUMIF(Transactions January::Transactions::C,A2,Transactions January::Transactions::$D)
    I find it easier to copy the cell contents, then paste onto the canvas. It becomes a text box. Edit, then select the contents of the text box. Copy and Paste back into cell C2. Fill Down.
    Plan B
    Open a new document from Template chooser for each month. Numbers will not reference formulas between documents, so each month is safe and sound within its own document.
    Regards,
    Ian.

  • I need to move 1000 photos from one library to another. How do I do that and keep the ratings and dates they were created?

    I need to move 1000 photos from one library to another. How do I do that and keep the ratings and dates they were created? I tried exporting them, but it loses all info. Also, how do I move the quicktime movies from one iphoto library to another? They were exported as jpgs

    Add both libraries to iPhoto Library Manager.  Then select the events or albums that you want to copy from library A  and drag them to library B in iPLM.
    This video shows the process:
    OT

  • I recorded a panel presentation on my Ipod and would like to edit the recording on my itunes so I can export the recording and send it to my colleagues over the internet.  I was able to import the recording to my itunes library but need help editing it.

    Hello, thanks in advance for your help.  I recorded a panel presentation on an ipod and would like to edit the audio recording to just one portion of the recording.  I was able to import the audio into my itunes 11.1.3 music library but I have not been able to edit the length of the recording.  I followed an online tutorial and was able to edit when the recording starts and stops on the recording but I haven't been able to edit out the parts of the recording that I dont want.  Also when I try to export it to my Desktop or to Garageband (not sure if that helps or not) I am not able to export it.  It is currently a .WAV file.  I would like to edit the length of the recording and then export the file onto my desktop.  I would like to email the presentations to my colleagues online so I could also use advice on how to make it a smaller file since it is current 945.6 MB.

    iTunes isn't an editor. You need an app that's intended for editing audio files, like Adobe Audition (http://www.adobe.com/products/audition.html) or Audacity (free in the App Store).

  • How do I back up the music and apps etc. I restored my computer and I reinstalled iTunes, I was told something about a terminal command line, what does that mean? Please help

    How do I back up the music and apps etc. I restored my computer and I reinstalled iTunes, I was told something about a terminal command line, what does that mean? Please help

    - Transfer iTunes purchases to the computer by:
    iTunes Store: Transferring purchases from your iOS device or iPod to a computer
    - Transfer any other music by using a third-party program like one of those discussed here:
    Copy music
    - Connect the iPod to the computer and make a backup by right clicking on the iPod under Devices in iTunes and select Back Up
    - Restore the iPod from that backup. The restore will also update the iOS.
    Note that the backup that iTunes makes does not include synced media like apps and music
    Are you sure you have a 3G iPod? A 1G iPod can only go to iOS 3.1.3
    See:
    Identifying iPod models

  • We have 3 locations coming up for our TV listings how do we make one the default and stop others?

    We have 3 locations coming up for our TV listings how do we make one the default and stop others?
    There is Bed Room, Living Room and Family how can we make ONLY FAMILY COME UP?
    When we check the listings or record from the TV Listing the LIVING ROOM comes up and only the Family has the controls to record.
    THANK YOU.
    Solved!
    Go to Solution.

    Please provide more details.
    What equipment do you have?
    Where do you see this listing? On STB? Online? Verizon App?
    If a forum member gives an answer you like, give them the Kudos they deserve. If a member gives you the answer to your question, mark the answer as Accepted Solution so others can see the solution to the problem.

Maybe you are looking for

  • CO60 Time out

    Hello Experts, I am runing the transaction code CO60 to display the PI sheet,but it is resulting in a short-dump as a result of time out. This is happening with only one sheet. can we increase the time line to execute this particular trasaction ? I f

  • Best way to call EJBs from JavaBeans/JSP

    Does anyone have a favorite way for getting EJB data from a JavaBean into           your JSPs?           I'm looking for a way of caching the EJBHome references so the beans don't           have to do a lookup on each page, each time they are called.

  • When do I need to use "void" ?

    When do I need to use "void" ? Thanks!!!

  • Numeral Format for Quick Part

    Hi,  I have a big problem with a template for document. I have some numeral fields in my content type, that i used in document liblary. In .doc template i use Document Property from Quick Part. I begin to fill my fields, for example, i want to use th

  • Customizing the Monitoring and Report Viewer - ACS 5.2

    Is there a way to modify the columns shown in the monitoring and reporting viewer so that I can see all of the relevant columns in one screen, similar to the ACS 4.x view?  I would like to view things at a glance, rather than having to click into eac