SQL Update a Single Row Multiple Times Using 2 Data Sets

I'm working in tsql and have an issue where I need to do multiple updates to a single row based on multiple conditions. 
By Rank_
If the column is NULL I need it to update no matter what the Rank is.
If the Ranks are the same I need it to update in order of T2_ID.
And I need it to use the last updated output.
I've tried using the update statement below but it only does the first update and the rest are ignored. Here is an example of the data sets i'm working w/ and the Desired results. Thanks in advance!
update a
set Middle = case when a.Rank_> b.Rank_ OR a.Middle IS NULL then ISNULL(b.Middle,a.Middle) end,
LName = case when a.Rank_> b.Rank_ OR a.Lname IS NULL then ISNULL(b.LName,a.LName) end,
Rank_ = case when a.Rank_> b.Rank_ then b.Rank_ end
from #temp1 a
inner join #temp2 b on a.fname = b.fname
where b.T2_ID in (select top 100% T2_ID from #temp2 order by T2_ID asc)

The Merge clause actually errors because it attempt to update the same record.  I think this CTE statement is the closest I've come but I'm still working through it as I'm not too familiar w/ them.  It returns multiple rows which I will have to
insert into a temp table to update since the resulting row I need is the last in the table.
;WITH cteRowNumber
AS(
Select DISTINCT
Row_Number() OVER(PARTITION BY a.LName ORDER BY a.LName ASC, a.Rank_ DESC,b.T2ID ASC) AS RowNumber
,a.FName
,a.LName
,b.LName as xLname
,a.MName
,b.MName AS xMName
,a.Rank_
,b.Rank_ AS xRank
,b.T2ID
FROM #temp1 a
inner join #temp2 b
ON a.fname = b.fname
), cteCursor
AS(
Select a.RowNumber,
a.Fname
,a.LName
,a.xLname
,a.MName
,a.xMName
,a.xRank
,a.T2ID
,CASE WHEN a.Rank_ >= a.xRank THEN ISNULL(a.xRank,a.Rank_) else ISNULL(a.Rank_,a.xRank) end AS Alt_Rank_
,CASE WHEN a.Rank_ >= a.xRank THEN ISNULL(a.xMName,a.MName) else ISNULL(a.MName,a.xMName) end AS Alt_MName
,CASE WHEN a.Rank_ >= a.xRank THEN ISNULL(a.xLName,a.lname) else ISNULL(a.LName,a.xlname) end as Alt_Lname
FROM cteRowNumber a
where a.RowNumber = 1
UNION ALL
Select crt.RowNumber
,crt.FName
,crt.LName
,crt.xLname
,crt.MName
,crt.xMName
,crt.xRank
,crt.T2ID
,CASE WHEN Prev.Alt_Rank_ >= crt.xRank THEN ISNULL(crt.xRank,Prev.Alt_Rank_) else ISNULL(Prev.Alt_Rank_,crt.xRank) end AS Alt_Rank
,CASE WHEN Prev.Alt_Rank_ >= crt.xRank THEN ISNULL(crt.xMName,Prev.Alt_MName) else ISNULL(Prev.Alt_MName,crt.xMName) end AS Alt_MName
,CASE WHEN Prev.Alt_Rank_ >= crt.xRank THEN ISNULL(crt.xLName,Prev.Alt_Lname) else ISNULL(Prev.Alt_Lname,crt.xLName) end as Alt_Lname
FROM cteCursor prev
inner join cteRowNumber crt
on prev.fname = crt.fname and prev.RowNumber + 1 = crt.RowNumber
SELECT cte.*
FROM cteCursor cte

Similar Messages

  • Want to be able to open tabs in multiple rows, rather than in a single row. I used tab mix plus before, but it says it is not compatible with New tab Homepage. The older version of Firefox allowed this very easily.

    Want to be able to open tabs in multiple rows, rather than in a single row. I used tab mix plus before, but it says it is not compatible with New tab Homepage. The older version of Firefox allowed this very easily.

    Your plugins list shows outdated plugin(s) with known security and stability risks.
    *Java Plug-in 1.5.0_06 for Netscape Navigator (DLL Helper)
    Update the [[Java]] plugin to the latest version.
    *http://java.sun.com/javase/downloads/index.jsp (Java Platform: Download JRE)

  • Insert same row multiple times

    Hi,
    I've this table TAB1:
    COD.........TYPE........DESCRIP
    1..............RED..............MY COLOR
    I'd like to insert into table TAB2 this record 10000 times
    How can I write my insert or procedure to insert this row multiple times?
    Thanks in advance!

    Hi,
    Assuming tab1.col is unique:
    INSERT INTO tab2 (col_a, col_b, col_c)
    SELECT            cod,   type,  descrip
    FROM    tab1
    START WITH  cod = 1
    CONNECT BY  cod = 1
           AND  LEVEL <= 10000;If tab1.cod is not unique, use whatever is unique in the START WITH and CONNECT BY clauses. You do not have to SELECT the unique key.
    This does not assume that tab1 contains only the row you want to copy.
    As shown, this only works for making multiple copies of a single row.
    The multi-row version isn't much more complicated.

  • Insert pages from a single document multiple times

    I'm trying to create a simple program that I can use to display PDF files that I can use to play at the piano. I perform often, and need to create "play lists" from which I can pull all, or part of, a PDF file containing music and display it.
    I have it all working, except for one problem. I may need to "repeat" a section of a piece. I'm building up the play list by calling AcroPDDoc.InsertPages for each item in the play list. If a PDF file appears multiple times in the play list, when I call InsertPages, the call fails.
    In this code snippet, pdDoc is the main doc to which I'm adding pages. playList is a generic List of my own PlayList objects, and I need to iterate through all the items in the playList except the first one, which is already loaded.
    This code works great unless the fileName I specify has already been opened. The call to AcroPDDoc.Open succeeds just fine, but the call to pdDoc.InsertPages fails if the file has already had pages from it inserted. All other documents work fine. The documentation, of course, doesn't mention this.
            int insertPage = pdDoc.GetNumPages() - 1;
            for (int i = 1; i < playList.Count; i++)
              var newDoc = new AcroPDDoc();
              var item = playList(i);
              int startPage = 0;
              int endPage = 0;
              if (newDoc.Open(item.fileName))
                startPage = Math.Max(0, item.startPage);
                endPage = Math.Max(0, item.endPage);
                var totalPages = newDoc.GetNumPages;
                if (item.endPage < 0 || item.endPage > totalPages)
                  endPage = totalPages - 1;
                int numPages = (endPage - startPage) + 1;
                if (pdDoc.InsertPages(insertPage, newDoc, startPage, numPages, 0))
                  insertPage += numPages;
    So, the questions:
    1.) Is it possible to load pages from a single document multiple times?
    2.) Is there a better way to do this? (That is, loop through a list of file names, starting and ending page numbers, and add the documents to an existing document.)
    Any help appreciated! Thanks -- Ken

    Hi Ken,
    >The documentation, of course, doesn't mention this.
    The documentation does not state explicitly that you can't insert pages again from a PDDoc you open again and never close.
    But it mentions that you get references only from an already opened PDDoc.
    "...Opens the specified document. If the document is already open, it returns a reference to the already opened PDDoc. You must call PDDocClose() once for every successful open..."
    It doesn't state that you can't insert pages from a referenced PDDoc but it seems so.
    I would close the PDDoc within your for-loop after inserting pages and release newDoc.
    Regards
    Norbert

  • Problem returning same rows multiple times

    Hi there. I have three tables called GP_T, LDMK_T, and FP_T.
    GP_T is a spatial table and has the following attributes:
    Location | Land - where location is of type sdo_geometry
    LDMK_T has the following attributes:
    Land | CFCC
    FP_T has the following attributes:
    Land | CFCC | Score
    Each land is assoicated with only one location. As can be seen the attribute "Land" is common to all three tables and uniquely identifies the objects that I am trying to access. "CFCC" is common to LDMK_T and FP_T and each unique object has an associated "CFCC" where more than one object can have the same "CFCC". Essentially what I am trying to do is return all distinct "lands" based on a "CFCC" value and where the objects' score > 20.
    My select statement looks as follows:
    select a1.land, a1.location from GP_T a1, LDMK_T a2, FP_T a3
    where a1.land = a2.land and a1.land = a3.land and a2.cfcc = a3.cfcc
    and a2.cfcc = 'D43' and a3.feature_score > 20;
    However, this query returns certain objects multiple (2 or more) times. When I run this second query it appears to return the correct number of values but without the "Location" attribute:
    select distinct (a1.land) from GP_T a1, LDMK_T a2, FP_T a3
    where a1.land = a2.land and a1.land = a3.land and a2.cfcc = a3.cfcc
    and a2.cfcc = 'D43' and a3.feature_score > 20;
    I cannot use "select distinct a1.land, a1.location...." as it throws up the following error:
    ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type
    Is it a question of using GROUP_BY or can anybody else see anything wrong with the way I set up the initial query. Any help would be greatly appreciated. Joe

    Hi there. Thanks a lot for your response. I tried removing the second table completely from the query as you suggested, seeming as it appears redundant, but the query still retrieves certain rows multiple times. In fact the query that you suggested actually returns the exact same results as my initial query so at least some progress has been made. However, I really have no idea how to remove duplicates without using the "DISTINCT" option. Has anybody else got any further suggestions? Any help would be great. Thanks, Joe

  • How to update a single row of data table

    How we can update a single row of the data table by clicking the button in the same row.
    Thanks in Advance.

    Hi!
    What do You mean 'update'? Get fresh data from DB or change data and commit it in DB?
    If commit, try to read here:
    http://developers.sun.com/jscreator/learning/tutorials/2/inserts_updates_deletes.html
    Thanks,
    Roman.

  • Issues after updating iPhone3GS to iOS5 on TIM cellular data network (Italy)

    Hi everyone
    I have issues after updating iPhone3GS to iOS5 on TIM cellular data network.
    After installing iOS5 I had to switch from apn ibox.tim.it to wap.tim.it
    Since then the phone is unusable for any internet activity that is barely "data demanding" (e.g facebook app take literaly hours to update), everyting requires way to much time... the iPhone is not an iPhone anymore... it's worse than my blackberry with just GPRS on it.
    TIM technical support suggested me to switch back on apn ibox.tim.it, but then I would not be able to use internet tethering anymore (they say because of Apple iOS5) ... to bad I need internet tethering for work.
    I am seriously thinking to switch ISP or phone.
    Anyone did experience same problem / found a solution?

    Hi Raia.D,
    Welcome to the Support Communities!
    The first thing I would suggest is to restart your iPhone.  Then tap the Settings app, and you should see Cellular listed on the main settings screen.  You should see Airplane Mode, Wi-Fi, Bluetooth, and then Cellular.
    Here are some additional troubleshooting steps to try:
    iPhone: Troubleshooting a cellular data connection
    http://support.apple.com/kb/ts3780
    Cheers,
    - Judy

  • HT5706 My Apple TV is frozen on the time and date setting and then it goes to the screen saver I tried changing the batteries on the remote and it still doesn't make a difference someone help

    My Apple TV is frozen on the time and date setting and then it goes to the screen saver I tried changing the batteries on the remote and it still doesn't make a difference someone help...has anyone else had these problems?

    Hi i ran into the same problem Ithoght it was the control, i changed the batteries the the control, and stil did not work, in the same connection (network and everything) i installed a new one and it worked perfectly, i can deduct the unit is nit working properly

  • How to store array of data into a single row of  table ,using any of Stmts

    HI Friends,
    Based on my requirements ,i have retrived a set of data from a XXX.jsp page using a request.getParameter() and stored into single dimenssional array . Now i am paassing that array to JAVA class to store a into some table .
    In JSP page users can add text boxes dynamically based on his intrest then those attributes will store in table .it means table attributes are not conatant , it table attributes may change at any time when user adds any textboxs or any fields on JSP page ....thats my module ..
    Now i wanted to store all array of data into Table in a single row .......thats is my requirements .
    How can we use prepareStatement and Statement to store array of results intoo table row ...on each iteration i wanted to store array of results into table atributes ..It means entire array of results should to into table row at time .....coule any one write sytax ,how we do this...
    could any one suggest me stps that i can impliment ......?....please reply ASAP

    Well ..you code can be works for constant number of attributes in table .oopss here my requirement is table attributes not fixed ,we cant put constant number of place holder(? ) in a statement ,because those are not fixed ,
    Let me explain here :
    i am doing in that way only. As i mentioned you Table attributes are not constant .It may very if users add any fields dynamically on JSP page .If users have option to add any text box on Jsp page ,then that attribute will store in table as a attribute .
    Now i amable fetching the all dyamic form data and stored in a Result Array below ...in this iteration all form result data are from jsp page as suggestion form ,it should stored in table in single row on corrsponding attribtes ......next time when users fills FROM ,then those data i am fetching and storing in a Result Array as below and need to store in corrsponding table attributes in a single row ....
    for(int i=0;i<result.length;i++)
                   System.out.println(result);
                   pst3=connection.prepareStatement("insert into *emprecord* values(?)");
                   if(!result[i].equals(""))
                        System.out.println(result[i]);
                             pst3.setString(1,result[i]);
                             pst3.executeUpdate();
    Thnks in advance ....let me know the the way we can store dynamic form data into dyanamic table ...

  • JOB in Sql Server Agent should run multiple times.

    Hi Guys,
    I have a ETL SSIS job in Sql Server Agent, Which should run multiple times.
     1. For Example : I scheduled a job at 10:00 PM, If the job fails at 10:00 PM it should run automatically again at 10:10 PM, if the job fails again at 10:10 PM then the job should run at 10:40 PM.
    If the job gets success at first attempt i.e 10:00 PM, then it should not run at 10:10 PM.
    Note : The time difference between jobs is 10 minutes and 30 minutes. And i know that we can run the job at regular intervals.
    Thanks in advance

    Just add retry attempts to whatever number you want (2 as per your original explanation) in Job step properties as below
    Have a logic to include a delay of 10 mins . You can make use of WAITFOR function for that
    see
    http://www.mssqltips.com/sqlservertip/1423/create-delays-in-sql-server-processes-to-mimic-user-input/
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • 11g DBAdatper returns 1st row multiple times

    We have a db adapter that was built using the adapters-db-102-select pdf as a guideline. When we test the query being executed by the adapter in the database it returns ten rows. When we test the BPEL process from the soa-infra console with debugging turned on and view the audit trail we see the following discrepancy. After the invoke operation I view the payload and see that the returned collection does in fact contain ten elements. The issue is that instead of returning the same ten rows as when we execute the query in the database it returns only the first row ten times. Can anyone suggest a possible resolution?
    Thank you.

    Ryan -
    I've always had to work to get a row repeated ten times, e.g. iterating through with a while loop and not putting the loop variable as a subscript in the assignment. You may have found a labor-saving new feature! :-( Being suspicious of new releases, I would try interating through the output variable, to see if maybe the person who coded the console display made that "not putting the loop variable as a subscript" error. If you confirm that you really do have the first row ten times, then you have two possibilities: (1) even though you think it's the same, the SQL you defined in the BPEL DB adapter wizard is not exactly the same as what you ran in the database, OR (2) the SQL in BPEL is right but returns repeated rows ("undocumented feature").
    If you aren't positive the DB adapter SQL is perfect, you might post the SQL you ran in the DEB and the SQL from the Toplink mappings (assuming 11G still has those). In 10.1.3 it would be in the JDeveloper BPEL project directory {JDevProjectName}/toplink/{DbAdapterPartnerlinkName}/descriptor, in the file named {DbAdapterPartnerlinkName}.{TableName}.ClassDescriptor.xml, in the XML element (tag) called query. It may be in a different place in 11G, but you get the idea. Compare what you think you coded with what the BPEL designer actually coded.
    If you're sure the SQL is right, you may want to open an SR. They'll probably ask for the SQL anyway, so posting it first won't hurt unless you're in a hurry.
    Good luck, Andy

  • Need query to convert Single Row Multiple Columns To Multiple rows

    Hi,
    I have a table with single row like below
    Column0 | Column1 | Column2 | Column3 | Column4|
    Value0    | Value1    | Value2    | Value3    |  Value4  |
    Am looking for a query to convert above table data to multiple rows having column name and its value in each row as shown below
    Column0 | Value0
    Column1 | Value1
    Column2 | Value2
    Column3 | Value3
    Column4 | Value4
    Thanks in advance.
    Mohan

    Hi ykMohan,
    Dynamic UNPIVOT can be applied in this case as well.
    CREATE TABLE dbo.T(ID INT,Column0 VARCHAR(99),Column1 VARCHAR(99),Column2 VARCHAR(99),Column3 VARCHAR(99),Column4 VARCHAR(99))
    INSERT INTO T VALUES
    (1,'Value0','Value1','Value2','Value3','Value4'),
    (2,'Value0','Value1','Value2','Value3','Value4');
    DECLARE @columns VARCHAR(MAX)
    SELECT @columns=
    STUFF(
    SELECT ','+ COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='T' AND TABLE_SCHEMA='dbo' AND Column_name NOT IN('ID') FOR XML PATH('')
    ),1,1,'')
    DECLARE @Sql NVARCHAR(MAX)
    SET @Sql =
    'SELECT ID, UPT.col,UPT.val FROM T
    UNPIVOT
    (val FOR col IN('+@columns+')) AS UPT'
    EXEC sp_executeSQL @Sql
    DROP TABLE T
    If you have any feedback on our support, you can click
    here.
    Eric Zhang
    TechNet Community Support

  • HT1222 I have tried updateing 10.8.4 multiple times and restarting my computer but the update is still visible on the ap store.

    I keep trying to update the M Lion 10.8.4 and restarting my Mac and the update is still there.  I have tried multiple times including a complete shutdown.  It seems it wont update.

    Run the standalone updater instead of updating through the Mac App Store.
    (84400)

  • Update gives "single-row subquery returns more than one row"

    Hi,
    I have to update a table by getting values from two other tables. While doing that the inner query returns more than one value. I am not sure how to implement the logic without returning more than one row in sub quesry. Need help on that.
    My query:
    update buf_office_str o
    set o.manager_ident =
    (select sp.ident
    from se2_r_src_sourceperson sp ,
    (select distinct director_name, team_name from buf_sales_dump )t
    where SP.SRCNAME = upper(substr(t.director_name,instr(t.director_name,' ')+1,length(t.director_name))||', '||substr(t.director_name,1,instr(t.director_name,' ')-1 ) )
    and o.office_descr = t.team_name
    Basically the query gets teh manager id from sp table where sp.srcname = t.team-name.
    The office descr should be equal to the team_name.
    This is the logic I am working towards:
    For each office, i get the office_descr and get corresponding team_name. Match the team's director_name (from table t) with the sp.name and return the employee's id (sp.ident) for that office_descr.
    I need to update all 50 offices with corresponding managerid for that office in buf_office_str table.
    Is it possible to get done in one update? Pls let me know.

    Hi,
    "Single-row subquery returns more than one row" is one of those error messages that actually means what it says: the correlated sub-query in your SET clause is sometimes returning 2 or more rows .
    The solution could be as simple as making the sub-query SELECT DISTINCT , as its in-line view, t, already is.
    It's possible you have bad data, or a mistake in your statement.
    To find the problem cases, you can run something like this:
    WITH  sub_q     AS
                       SELECT  -- DISTINCT ?
                                sp.ident
                       ,         t.team_name
                       ,         COUNT (*) OVER (PARTITION BY t.team_name)     AS cnt
                       FROM    se2_r_src_sourceperson     sp
                       ,         (  SELECT DISTINCT director_name
                                   ,                  team_name
                               FROM            buf_sales_dump
                             )                    t
                       WHERE   sp.srcname     = UPPER ( SUBSTR ( t.director_name
                                                         , INSTR ( t.director_name
                                                  ) + 1
                                                , LENGTH (t.director_name)
                                          || ', '
                                          || SUBSTR ( t.director_name
                                                          , 1
                                                   , INSTR ( t.director_name
                                                        ) - 1
    SELECT     o.*     -- or whatever helps you
    ,     sq.*
    FROM     buf_office_str     o
    JOIN     sub_q          sq     ON     o.office_descr = sq.team_name
    WHERE     sq.cnt          > 1
    ;If you'd like more help, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables as they exist before the UPDATE, and the results you want from that data (that is, the contents of buf_office_str after the UPDATE). Make sure the problem occurs with the sample data you post.

  • How to update all the rows of table using stored procedures

    Hi,
    I want to update all the rows of a table of a specific column
    sp_a  male
    sp_b female
    sp_c  male
    sp_d female
    in above table 
    gender of all the columns has to be interchanged.

    Sir table is like this detail(name varchar(10),gender varchar(10))
    Where Details  are like this 
    Name  Gender
    sp_a 
    male
    sp_b
    female
    sp_c 
    male
    sp_d
    female
    I want to create a stored procedure which automtically updates gender from male to female and female to male
    for all the rows . i.e., all the rows are updated for column gender by just running a stored procedure.
    So after execution of stored proc the above table looks
    Name  Gender
    sp_a 
    female
    sp_b
    male
    sp_c 
    female
    sp_d
    male

Maybe you are looking for

  • Mail will not send or receive.

    I am having awful problems with Mail since upgrading to mountain lion. If I choose a folder (as opposed to keeping it on Inbox for all) everything goes blank and Mail crashes. I can't go back to a draft I started either because that requires going to

  • Accounting document not generating for Invoice cancellation

    Hi Gurus We have a scenario where two invoices are getting generated from one contract(Order related billing). But when cancelling these two invoice one cancellation document is not generating accounting document. The posting period is open on the da

  • Aperture Library Help

    Hi, When I try to upload photos to any website, using their upload feature, my Aperture librar does not show up.  The iPhoto library, which I don't use, is the only available library. While in Aperture, my library seems fine.  However, when I look at

  • Why does my 15' macbook keep shutting down?

    I never had this problem till recently. My macbook keeps shutting down around the 60% mark on the battery indicator. I have requested for the new battery, as my battery is eligible. I'm hoping this will fix the problem. Also, the light on the mag-saf

  • Javascript popup causing Japanese text transformation

    I found out that ALL the popup creating javascript (window.open - triggered from swf or HTML code) causes the double to single-byte japanese display transformation. This happens only on PCs, not on Macs. You can see the real time exemple on http://ce