Insert missing rows from another table

Hi
I need to insert rows from another table if there is gaps in my transaction table. For each ärendenr there should be 5 Id status rows (1-5). Except for the fact that the inserted rows never should have higher IdStatus number then the highest value from
the transaction for each Ärendenr. See my example below that illustrates my transaction table, Stages master and the desired result.
Is there some t sql code that could handle this problem?
Best regards
Arne
So far i have tried to solve this with the code below but it doesnt work.
I have copied the transaction file information to the TempLogTransTimes
and then insert into LogTransTimes
IF OBJECT_ID('dbo.TempLogTransTimes', 'U') IS NOT NULL --Här raderas den tillfälliga tabellen
DROP TABLE dbo.TempLogTransTimes;
SELECT *
INTO TempLogTransTimes
FROM LogTransTimes
DECLARE @TopÄrende INT
WHILE EXISTS(SELECT * FROM TempLogTransTimes)
BEGIN
SET @TopÄrende = (SELECT TOP(1) Ärendenr FROM TempLogTransTimes ORDER BY Ärendenr)
INSERT INTO LogTransTimes(Ärendenr, IdStatus, StatusNamn, SourceId)
SELECT @TopÄrende, SM.IdStatus, SM.StatusNamn, 'Beräkning'
FROM Statusmall SM
FULL JOIN TempLogTransTimes LT ON SM.IdStatus = LT.IdStatus
WHERE LT.IdStatus IS NULL
DELETE TempLogTransTimes WHERE Ärendenr = @TopÄrende
END
Arne Olsson

Hi Arne Olsson, try this..
DECLARE @Transactions TABLE
Id1 INT,
IdStatus INT,
StatusName VARCHAR(10)
DECLARE @Stages TABLE
IdStatus INT,
StatusName VARCHAR(10)
INSERT INTO @Transactions VALUES(1,1,'AA'), (1,3,'CC'), (1,5,'EE'), (2,1,'AA'), (2,3,'CC')
INSERT INTO @Stages VALUES (1,'AA'), (2,'BB'), (3,'CC'), (4,'DD'), (5,'EE')
;WITH CTE AS(SELECT DISTINCT Id1 FROM @Transactions)
SELECT Id1, IdStatus, StatusName FROM CTE, @Stages
EXCEPT
SELECT Id1, IdStatus, StatusName FROM @Transactions
Please mark as answer, if this has helped you solve the issue.
Good Luck :) .. visit www.sqlsaga.com for more t-sql code snippets and BI related how to articles.

Similar Messages

  • Add rows from another table

    Hi ,
    I have a table with 20 records and 10 columns.I want to add columns from another table with out cross join.

    As others have said, you need to have some sort of join condition otherwise it is a cross join.
    SQL> ed
    Wrote file afiedt.buf
      1  with T1 as (select 'e' as c1, 2 as c2 from dual union all
      2              select 'd', 3 from dual)
      3      ,T2 as (select 'x' as c3, 5 as c4 from dual union all
      4              select 'y', 6 from dual union all
      5              select 'z', 2 from dual)
      6  --
      7  select T2.c3, T2.c4, T1.c1, T1.c2
      8  FROM (select c1, c2, row_number() over (order by c1) as rn from T1) T1
      9       FULL OUTER JOIN
    10       (select c3, c4, row_number() over (order by c3) as rn from T2) T2
    11*      ON (T1.rn = T2.rn)
    SQL> /
    C         C4 C         C2
    x          5 d          3
    y          6 e          2
    z          2
    SQL>This example assigns a row number to each row within each table and then joins using that row number.
    (I've assumed the row number should be generated based on the order of the first column of each table, but you can change that as required).
    What is the point of your requirement?

  • How to populate rows from another table in new blank rows of other table

    I have to convert an oracle form 6i to Jdeveloper application. In forms 6i we use create a cursor for other table and then populate the current table data block row using create record and assigning its values from cursor and then issuing next record until all cursor records are written in data block. After some manual editing we save the whole form and then all block records are saved as new rows in table.
    Now how to create this functionality in jdeveloper application.
    Kindly help.

    two steps-
    1. get row from first VO.iterate them - like below -
    DCBindingContainer bindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
                                    DCIteratorBinding dcIteratorBindings = bindings.findIteratorBinding("ViewObj1Iterator");
                                    HSSFRow  excelrow = null;
                                            // Get all the rows of a iterator
                                            oracle.jbo.Row[] rows = dcIteratorBindings.getAllRowsInRange();
                                        int i = 0;
                                                for (oracle.jbo.Row row : rows) {
                                                                                                                    row.getAttribute(colName).toString());  // by this you can get row attribute value..
    2. inside iteration create row for VO 2 for example-
    ViewObject employee= findViewObject("EmployeeVO");
    // Create a row and fill in the columns.
    Row row = employee.createRow();
    row.setAttribute("Name", "Vinay");
    row.setAttribute("EmpId", 1);
    //Insert row in to the default row set
    employee.insertRow(row);
    Read more: http://www.techartifact.com/blogs/2012/12/creating-new-row-of-view-object-in-adf-techartifact.html#ixzz2iL978UOD
    http://www.techartifact.com/blogs/2012/12/creating-new-row-of-view-object-in-adf-techartifact.html

  • Update one row based on a row from another table

    Hi,
    I have two tables which are having the same field but with a different name.
    CREATE TABLE FAVE_CODE2_NEW_JOIN
    BANKID VARCHAR2(5 BYTE) NOT NULL,
    CUSTOMERID VARCHAR2(12 BYTE) NOT NULL,
    SIXID VARCHAR2(12 BYTE) NOT NULL,
    FAVCODE VARCHAR2(13 BYTE),
    IDX NUMBER(5),
    DEFAULTT NUMBER(1)
    TABLESPACE PORTFOLIO_FAVORITE
    PCTUSED 0
    PCTFREE 10
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 64K
    NEXT 1M
    MINEXTENTS 1
    MAXEXTENTS UNLIMITED
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    LOGGING
    NOCOMPRESS
    NOCACHE
    NOPARALLEL
    MONITORING;
    CREATE TABLE SUBSCRIPTION
    SUBSCRIPTIONID RAW(16) NOT NULL,
    APPID VARCHAR2(64 BYTE) NOT NULL,
    DEVICEID VARCHAR2(64 BYTE),
    SUBSCRIBERID NUMBER NOT NULL,
    TIME_REGISTERED TIMESTAMP(6) DEFAULT SYSTIMESTAMP NOT NULL,
    TIME_LAST_USED TIMESTAMP(6) DEFAULT SYSTIMESTAMP NOT NULL,
    SUBSCRIPTION_TYPE VARCHAR2(30 BYTE) NOT NULL,
    SUBSCRIPTION_INFO VARCHAR2(512 BYTE)
    TABLESPACE PORTFOLIO_FAVORITE
    PCTUSED 0
    PCTFREE 10
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 64K
    NEXT 1M
    MINEXTENTS 1
    MAXEXTENTS UNLIMITED
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    LOGGING
    NOCOMPRESS
    NOCACHE
    NOPARALLEL
    MONITORING;
    SUBSCRIPTION_INFO in SUBSCRIPTION is equal to SIXID in FAVE_CODE2_NEW_JOIN. They have the same value
    In FAVE_CODE2_NEW_JOIN table there is also a FAVCODE filed.
    Now i want to find out the record from VE_CODE2_NEW_JOIN which are having the same sixid like SUBSCRIPTION_INFO in SUBSCRIPTION and then replace that SUBSCRIPTION_INFO with the value in FAVCODE
    Here are some sample from both tables:
    SUBSCRIPTION:
    B31E5F5D3CB6     RIe9pnbe7BtA8IuQ     BB2-58CA815F9958     21     2012-01-10 19:18:39     2012-01-11 12:24:04     FT     FSB0650444
    010FB3AE74AE     RIe9pnbe7BtA8IuQ     845-AD375E95ED90     21     2012-01-12 08:31:47     2012-01-24 08:53:09     FT     FSB0650444
    6119E731A26F     RIe9pnbe7BtA8IuQ     76A-DAD2E359BF3F     113     2012-01-04 00:25:05     2012-01-19 16:17:21     FT     FSB0632948
    FAVE_CODE2_NEW_JOIN:
    08999     191111111111     FSB0650444     SWB0553263     11     0
    As you see they both have the same 'FSB0650368' but i want to replace this code with the corresponding FAVCODE in FAVE_CODE2_NEW_JOIN which is 'SWB0553263'.
    I hope you have got what i mean, please tell me to explain more if you have any problem to understand what i mean.
    Many thanks in Advance!
    / Hesam

    Hesam wrote:
    hi,
    I'm trying this code:
    update subscription a
    set a.subscription_info =
    select b.favcode
             from fave_code2_new_join b
            where b.sixid = a.subscription_info
    where exists
    select b.favcode
             from fave_code2_new_join b
            where b.sixid = a.subscription_info
    )but its taking a lot of time. Until now 10 minutes and lots of presure on the CPU!!
    Can we optimize this or its just due to the number of records?
    Edited by: Hesam on Mar 25, 2013 3:01 PMSo now you are getting into performance issues?
    I would suggest you read {message:id=9360003} and post the necessory details so that we can see what can be improved and how.

  • How to insert subtype data from another table in  a object table ?

    Hi all
    I have been looking at the differences answers there are about insert data form a subtype in a object table of a supertype ,but have not found a solution yet.
    I hope you can help me.
    I my code Action_Logs is the object table and CloseStore_Logs_t is a subtype of Action_Logs_t
    My code is
    insert into Action_Logs(CloseStore_Logs_t (action_logs_id , physicalstores.physicalstores_id , brandedstores.BRANDEDSTORES_ID ,physicalstores.COMPANIES_ID ,brandedstores.CREATED_BY ,
    brandedstores.CREATED_DATE , brandedstores.DELETED ,brandedstores.CLOSED_DATE as brandedstore_closedate,
    physicalstores.CLOSED_DATE as physicalstore_closedate)
    select CloseStore_Logs_t((null as action_logs_id , physicalstores.physicalstores_id , brandedstores.BRANDEDSTORES_ID ,physicalstores.COMPANIES_ID ,brandedstores.CREATED_BY ,
    brandedstores.CREATED_DATE , brandedstores.DELETED ,brandedstores.CLOSED_DATE as brandedstore_closedate,
    physicalstores.CLOSED_DATE as physicalstore_closedate)
    from physicalstores , brandedstores ,companies
    where physicalstores.physicalstores_id = brandedStores.PHYSICALSTORES_ID and
    physicalstores.COMPANIES_ID = companies.COMPANIES_ID and
    brandedstores.closed_date is not null
    oracle gives a ora _917 fault about a missing comma , but I can not se what is wrong.
    I will be glad, if you can give me an example with a right syntax where a subtype is selected from other/s tables an inserted in table of its supertype.
    kinds regards
    steen ostersen

    Hi
    I see two problems with your statement:
    1) The utilization of the values clause is not permitted along with a subquery.
    2) The AS are not allowed.
    So, something like that should work:
    insert into Action_Logs
    select CloseStore_Logs_t(null,
    physicalstores.physicalstores_id,
    brandedstores.BRANDEDSTORES_ID,
    physicalstores.COMPANIES_ID,
    brandedstores.CREATED_BY,
    brandedstores.CREATED_DATE,
    brandedstores.DELETED,
    brandedstores.CLOSED_DATE,
    physicalstores.CLOSED_DATE)
    from physicalstores , brandedstores ,companies
    where physicalstores.physicalstores_id = brandedStores.PHYSICALSTORES_ID and
    physicalstores.COMPANIES_ID = companies.COMPANIES_ID and
    brandedstores.closed_date is not null
    HTH
    Chris

  • INSERTING INTO A TABLE FROM ANOTHER TABLE

    Hi,
    I am having a table called emp in which 5 columns are there, I want to insert some rows from another table called employees, only into three columns of emp table through a sub query.
    Is this scenario is possible, I tried so many queries but it is not working out.
    Can any body help me out.
    The columns in emp table is
    empno, ename, doj, designation, salary, deptno, mgrid
    The columns in employees table is
    empno, name, hiredate, post, salary, commission, deptno, mgr
    I want to insert into empno, ename, doj, designation columns of emp table from the employees table empno, name, hiredate, post columns.
    Ramesh.

    It looks like your EMP table has 7 columns, not 5, and you want to insert into 4 columns, not 3.
    insert into emp
      (empno, ename, doj, designation)
      select empno, name, hiredate, post
        from employees;

  • Polling Strategy to get back inserted/updated rows from BPEL

    Hi,
    Can anybody have code to get back the newly inserted/updated rows from database table, using DbAdapter Polling Strategy from BPEL Process.

    Hi user559009,
    Could you please elaborate a bit more about what it is you need.
    If you create a Partner link that polls a table and then create a receive activity that uses the partner link the variable in the receive activity will contain the data from the table.
    Regards Pete

  • Insert old missing data from one table to another(databaase trigger)

    Hello,
    i want to do two things
    1)I want to insert old missing data from one table to another through a database trigger but it can't be executed that way i don't know what should i do in case of replacing old data in table_1 into table_2
    2)what should i use :NEW. OR :OLD. instead.
    3) what should i do if i have records exising between the two dates
    i want to surpress the existing records.
    the following code is what i have but no effect occured.
    CREATE OR REPLACE TRIGGER ATTENDANCEE_FOLLOWS
    AFTER INSERT ON ACCESSLOG
    REFERENCING NEW AS NEW OLD AS OLD
    FOR EACH ROW
    DECLARE
    V_COUNT       NUMBER(2);
    V_TIME_OUT    DATE;
    V_DATE_IN     DATE;
    V_DATE_OUT    DATE;
    V_TIME_IN     DATE;
    V_ATT_FLAG    VARCHAR2(3);
    V_EMP_ID      NUMBER(11);
    CURSOR EMP_FOLLOWS IS
    SELECT   EMPLOYEEID , LOGDATE , LOGTIME , INOUT
    FROM     ACCESSLOG
    WHERE    LOGDATE
    BETWEEN  TO_DATE('18/12/2008','dd/mm/rrrr') 
    AND      TO_DATE('19/12/2008','dd/mm/rrrr');
    BEGIN
    FOR EMP IN EMP_FOLLOWS LOOP
    SELECT COUNT(*)
    INTO  V_COUNT
    FROM  EMP_ATTENDANCEE
    WHERE EMP_ID    =  EMP.EMPLOYEEID
    AND    DATE_IN   =  EMP.LOGDATE
    AND    ATT_FLAG = 'I';
    IF V_COUNT = 0  THEN
    INSERT INTO EMP_ATTENDANCEE (EMP_ID, DATE_IN ,DATE_OUT
                                ,TIME_IN ,TIME_OUT,ATT_FLAG)
         VALUES (TO_NUMBER(TO_CHAR(:NEW.employeeid,99999)),
                 TO_DATE(:NEW.LOGDATE,'dd/mm/rrrr'),       -- DATE_IN
                 NULL,
                 TO_DATE(:NEW.LOGTIME,'HH24:MI:SS'),      -- TIME_IN
                 NULL ,'I');
    ELSIF   V_COUNT > 0 THEN
    UPDATE  EMP_ATTENDANCEE
        SET DATE_OUT       =  TO_DATE(:NEW.LOGDATE,'dd/mm/rrrr'), -- DATE_OUT,
            TIME_OUT       =   TO_DATE(:NEW.LOGTIME,'HH24:MI:SS'), -- TIME_OUT
            ATT_FLAG       =   'O'
            WHERE EMP_ID   =   TO_NUMBER(TO_CHAR(:NEW.employeeid,99999))
            AND   DATE_IN <=  (SELECT MAX (DATE_IN )
                               FROM EMP_ATTENDANCEE
                               WHERE EMP_ID = TO_NUMBER(TO_CHAR(:NEW.employeeid,99999))
                               AND   DATE_OUT IS NULL
                               AND   TIME_OUT IS NULL )
    AND   DATE_OUT  IS NULL
    AND   TIME_OUT IS NULL  ;
    END IF;
    END LOOP;
    EXCEPTION
    WHEN OTHERS THEN RAISE;
    END ATTENDANCEE_FOLLOWS ;
                            Regards,
    Abdetu..

    INSERT INTO SALES_MASTER
       ( NO
       , Name
       , PINCODE )
       SELECT SALESMANNO
            , SALESMANNAME
            , PINCODE
         FROM SALESMAN_MASTER;Regards,
    Christian Balz

  • Insert Multiple rows into the table from that table data

    Hi All,
    I have a requirement like to insert mulitple rows into the table from that table data only(I need to replicate the data).
    In this table primary key is composite primary key with all foreign keys.primary key also including the Date foreign key.I need to change that date at the of insertion.
    INSERT
    INTO myschema.Fact_page_performance
    time_sk ,
    batch_id ,
    delta_msec ,
    delta_user_msec,
    error_code_sk ,
    content_errs ,
    element_count ,
    page_bytes ,
    Available ,
    date_sk
    VALUES
    (SELECT time_sk ,
    batch_id ,
    delta_msec ,
    delta_user_msec,
    error_code_sk ,
    content_errs ,
    element_count ,
    page_bytes ,
    Available
    FROM myschema.FACT_PAGE_PERFORMANCE_BACKUP
    WHERE date_sk=20090509,20090510
    But it is giving the error like missing Expression.
    Could anyone please help to me.
    Thanks and Regards
    Swetha.

    You can have either VALUES or SELECT not both
    INSERT
    INTO myschema.Fact_page_performance
    time_sk ,
    batch_id ,
    delta_msec ,
    delta_user_msec,
    error_code_sk ,
    content_errs ,
    element_count ,
    page_bytes ,
    Available ,
    date_sk
    SELECT time_sk ,
    batch_id ,
    delta_msec ,
    delta_user_msec,
    error_code_sk ,
    content_errs ,
    element_count ,
    page_bytes ,
    Available
    FROM myschema.FACT_PAGE_PERFORMANCE_BACKUP
    WHERE date_sk=20090509,20090510;

  • How could I insert the deleted row into another table within a trigger?

    Hi,
    How could I insert the deleted row into another table within a trigger? The destination table has the same columns as the source table. Since the statements are in the trigger, it is not allowed to query the source table named 'test'. Thanks! The trigger is as follows, uncompleted:
    CREATE TRIGGER delete_trigger
    AFTER DELETE
    ON test
    FOR EACH ROW
    BEGIN
    -- How could I insert the deleted row into another table
    END delete_trigger;
    Message was edited by:
    user569548

    Hi,
    I'm not sure what's wrong there.
    I read the oracle docs about ANALYZE and ALL_TAB_COLUMNS, and did the following:
    ANALYZE TABLE my_tab VALIDATE STRUCTURE; //went ok.
    SELECT column_name
    FROM all_tab_columns
    WHERE table_name = 'my_tab'; //but no rows selected?
    This topic might not be what this thread should be about. Here I posted a new thread:
    How to get colum names of the newly created table?
    Thanks.
    Message was edited by:
    user569548

  • Copying table rows from one table to another table form

    Hi
    I have a problem about Copying table rows from one table to another table form.On jsf pages if you enter command button go anather jsf page and it copy one row to another table row. But when i execute this process for table FORM it doesn't copy I wrote a code under "createRowFromResultSet - overridden for custom java data source support." Code block is:
    ViewRowImpl value = super.createRowFromResultSet(qc, resultSet);
    try{
    AdfFacesContext fct = AdfFacesContext.getCurrentInstance();
    Number abc = (Number)fct.getProcessScope().get("___");
    value.setAttribute("___",abc);
    }catch(Exception ex){System.out.println(ex);  }
    return value;

    Table may be copied with the
    expdp and impdp utilities.
    http://www.oracle.com/technology/products/database/utilities/index.html

  • How to populate a table based on a row selection from another table.

    Hi, i just started to use ADF BC and Faces. Could some one help me or point me a solution on the following scenario .
    By using a search component , a table is being displayed as a search result. If i select any row in the resulted table , i need to populate an another table at the bottom of the same page from another view. These two tables are related by primary key . May i know how to populate a table based on a row selection from another table. Thanks
    ganesh

    I understand your requirement and the tutorial doesn't talk about Association between the views so that you can create a Master-Detail or in DB parlance, a Parent-Child relationship.
    I will assume that we are dealing with two entities here: Department and Employees where a particular Department has many Employees and hence a Parent-Child relationship.
    Firstly, you need to create an Association between the two Entities - Department and Employees. You can do that by right clicking on the model's entity and then associating the two entities with the appropriate key say, DepartmentId.
    Once you have done that, you need to link the two entities in the View section with this Association that you created. Then go to AppModule and make sure that in the Available View Objects: 'EmployeesView' appears under 'DepartmentView' as "EmployeesView via <link you created>". Shuttle the 'DepartmentView' to the right, Data Model and then shuttle
    "EmployeesView via <link you created>" to the right, Data Model under 'DepartmentView'.
    This will then be reflected in your Data Controls. After that, you simply would have to drag this View into your page as a Master-Detail form...and then when you run this page, any row selected in the Master table, would display the data in the Detail table.
    Also, refer to this link: [Master-Detail|http://baigsorcl.blogspot.com/2010/03/creating-master-detail-form-in-adf.html]
    Hope this helps.

  • How to insert a row in Tree table which is dragged from the table?

    Hi All,
    I am having a Tree table and a Table in the same page, like below
    Treetable                                         Table
    Item1                                              Subitem12
         Subitem1                                   Subitem13
         Subitem2                                   Subitem14
         Subitem3                                   Subitem15
         Subitem4                                   Subitem16
    Item2                                              Subitem17
         Subitem5                                   Subitem18
         Subitem6                                   Subitem19
         Subitem7                                   Subitem20
         Subitem8                                   Subitem21
    Item3
         Subitem9
         Subitem10
         Subitem11
    The requirement is i need to "drag" a row from the Table and place it under any parent node in the Tree table.
    What i have done is I make the Tree table as ".ui-sortable" and table as a "draggable".
    I am not able to find the position of the dragged item when i dropped it in the Treetable.
    Please provide me a solution.
    Regards,
    Aravindh

    Hello:
    Do you mean setting the selectedRowKeys in the setter method of the treeTable in the Request Scoped Managed Bean?
    If that is what you mean, I tried that and there was no change in behavior. (Still does not highlight the correct row in the tree table upon execution of the next method for the bindings) Does anyone have any sample code they can provide that works?
    Thanks for the help.

  • Deleting rows from one table while filter condition lies into another table

    Hi All,
    I'm facing a problem deleting a row from a table where the condition lies in other table. To ealaborate the scenario further let's say I have two table T1 (transaction table) and T2 (Master Table). I want to delete a record from table T1 by checking some conditions lies in table T2.
    I tried with the below query but this query deleting records from both the table.
    DELETE FROM ( SELECT * FROM T1 top INNER JOIN T2 tp
    ON top.TID = tp.TID
    WHERE top.DEAL_SITE_ID = inputparameter1
    AND (TP.SEGMENT <>inputparameter2 OR tp.segment is not null));
    Here the record is getting deleted from both the tables but I don't want to delete data from my master table i.e table T2.
    Any help would be highly appreciated. Thanks in advance.
    Regards,
    Subhadeep

    SQL> select *
      2   from the_table;
    X          Y
    AA         a
    BB         a
    CC         a
    AA         b
    DD         b
    SQL> select *
      2   from the_table_2;
    X          Y
    AA         a
    BB         a
    CC         a
    SQL>  delete from
      2  (
      3  select *
      4  from the_table  t1 inner join the_table_2 t2
      5  on  t1.x = t2.x
      6  and t1.y = t2.y);
    3 rows deleted.
    SQL> select *
      2   from the_table;
    X          Y
    AA         b
    DD         b
    SQL> select *
      2   from the_table_2;
    X          Y
    AA         a
    BB         a
    CC         a

  • Help with inserting records conditionally in another table

    I need some help on this task please. I have a table with some records like so
    Table1
    Column1   Column2   Column3      Colum4
    1                 Name1    Lastname1     1,2
    2                 Name2    Lastname2     3
    3                  Name3    Lastname3     NULL
    4                  Name4    Lastname4     1,3
    So the last column, Column4 has the number of the column that the values got changed. So the values on the first row on the Columns 1 and 2 got changed. So I have to insert those values in another table and the same for the other records.
    Table2
    Column1   Column2    Column3      
    1                Name1     NULL
    2                 NULL      Lastname2
    4                 NULL      Lastname4
    Any ideas on how to accomplish this? Any ideas would be much appreciated.

    Hi
    Try below, Next time please POST DDL & DML
    select 1 Column1, 'Name1' Column2, 'Lastname1'Column3, '1,2' Colum4 into #temp union all
    select 2 , 'Name2', 'Lastname2', '3' union all
    select 3 , 'Name3' , 'Lastname3', NULL union all
    select 4, 'Name4', 'Lastname4', '1,3'union all
    select 5, 'Name4', 'Lastname4', '1'
    select 1 Column1 ,'Name1' Column2, NULL Column3 into #temp1 union all
    select 2 ,NULL ,'Lastname2' union all
    select 4, NULL, 'Lastname4'
    select Column1, Column2, Column3, Colum4 ,C2,C1 from #temp a
    --(select Column1, Column2, Column3, case when Colum4 like '%,%' OR Colum4 IS null then Colum4 else Colum4+',' end as Colum4 from #temp) a
    outer apply (select COALESCE(Column2,Column3) From #temp1 where column1 = parsename(replace(a.colum4,',','.'),1)) a1(C1)
    outer apply (select COALESCE(Column2,Column3) From #temp1 where column1 = parsename(replace(a.colum4,',','.'),2)) a2(C2)
    You can also use split function
    http://sqlperformance.com/2012/07/t-sql-queries/split-strings
    select a.*,COALESCE(a2.Column2,a2.Column3) From #temp a
    cross apply dbo.Split(Colum4,',') a1
    left outer join #temp1 a2 on a1.item=a2.Column1
    Thanks
    Saravana Kumar C

Maybe you are looking for

  • Cannot able to save Excel 2013 file in Sharepoint 2007 document library

    Dear All, We have SharePoint 2007 intranet portal where in we have teamplace created for internal users to collaborate on documents. Now we are having issues when using uploads Excel 2013 or Excel 2010 file on document library and try to edit the doc

  • Message not available in wf_bpel_qtab table for item creation event.

    Hi, In Oracle EBS I enabled subscription for event oracle.apps.inv.itemCreate. When I create item, message is available in wf_deferred table. There is record in this table with user_data having event_id, organization_id, item_id and other information

  • OS X 10.6.7 corrupted images uploaded to websites with any browser

    Since upgrading to 10.6.7 i have problems uploading images to any website. they end up having only part of their color information. (http://imgur.com/XjojB) I have tried every browser, multiple web sites, etc, and all are the same. maybe 20% of image

  • Jukebox Zen Problems ripp

    I seem to get a problem with CDs that I am trying to rip to the Music Library. The majority of the time the tracks are recognised and it starts ripping ok, but when it gets about half way, it stops ripping and sends a Microsoft error report. It's dri

  • Date&time Calculation with respect to Service&Response Profile

    Hi all, The scenario is  -  we are creating service request which is having service profile and response profile , according to these the First response time and to do by time are getting calculated. In this calculation system is considering the week