Home Forums Programming General conditional update query syntax RE: conditional update query syntax

  • paulgq - Friday, August 17, 2018 8:25 PM

    This is the best I can do right now even though your guide says not to do it this way.  CompanyName in table1 does not allow duplicates.

    table1
    ID, CompanyName
    100, sears
    101, walmart
    102, home depot
    103, lowes
    103, target

    table2
    ID, Description, Mfg
    150, blah blah blah blah blah, null
    151, blah blah home depot blah, null
    152 ,blah blah lowes blah blah, null

    after the query runs, I need table2 to be updated in the following manner
    table2
    ID, Description, Mfg
    150, blah blah blah blah blah, null
    151, blah blah home depot blah, home depot
    152 ,blah blah lowes blah blah, lowes

    is this any clearer?

    What the guys are asking for, is consumable data, so that we can better understand your requirements.
    In the future please format your data like this
    CREATE TABLE #Table1 (
      ID int NOT NULL
    , CompanyName varchar(20) NOT NULL PRIMARY KEY -- CompanyName in table1 does not allow duplicates
    );
    GO

    INSERT INTO #Table1 ( ID, CompanyName )
    VALUES ( 100, 'sears' )
      , ( 101, 'walmart' )
      , ( 102, 'home depot' )
      , ( 103, 'lowes' )
      , ( 103, 'target' );
    GO

    CREATE TABLE #Table2 (
      ID int NOT NULL
    , [Description] varchar(100) NOT NULL
    , Mfg varchar(20) NULL
    );
    GO
    INSERT INTO #Table2 ( ID, [Description], Mfg )
    VALUES ( 150, 'blah blah blah blah blah', null )
      , ( 151, 'blah blah home depot blah', null )
      , ( 152 ,'blah blah lowes blah blah', null )
    --------------------------------------------------------
    -- I have added these, as you may want to think about how to handle these cases
      , ( 501, 'blah blahhome depotblah', null )
      , ( 502, 'blah blah homedepot blah', null )
      , ( 503, 'blah blahhomedepotblah', null )
      , ( 504 ,'blah blahlowes blah blah', null )
      , ( 505 ,'blah blah lowesblah blah', null )
      , ( 506 ,'blah blah home depot blah lowes blah', null )
      , ( 507 ,'blah blah homedepot blah lowes blah', null );
    GO

    SELECT ID, [Description], Mfg
    FROM (
      VALUES ( 150, 'blah blah blah blah blah', null )
       , ( 151, 'blah blah home depot blah', 'home depot' )
       , ( 152 ,'blah blah lowes blah blah', 'lowes' )
      ) AS ExpectedResults( ID, [Description], Mfg );