CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: SQL Question

  1. #1
    Join Date
    Jan 2006
    Posts
    35

    SQL Question

    Assume I have a table of parts for a particular job. Parts are added to the job as they are needed. Some times a given part is needed more than once so I could potentially have multiple parts show up in the table. To avoid this I'd rather just have a quantity field so that would increment instead.

    Is there a way to make an INSERT statement add a part if it doesn't already exist OR increment the quantity if it does?

    Thanks!

  2. #2
    Join Date
    Mar 2001
    Posts
    2,529

    Re: SQL Question

    One option is have all parts already in the database with a zero quantity.

    Then just do an UPDATE with the new quantity.

    Or you will have to do a SELECT and if the number of records returned is 1, do an UPDATE otherwise do the INSERT.

    HTH,
    ahoodin
    To keep the plot moving, that's why.

  3. #3
    Join Date
    Mar 2006
    Location
    Graz, Austria
    Posts
    273

    Re: SQL Question

    Hi, I agree with ahoodin having all the records in database with 0 quantity. It is more performant that counting each time
    Daniela
    ******
    I would love to change the world, but they won't give me the source code

  4. #4
    Join Date
    May 2006
    Location
    Warsaw, PL/Oslo, NO
    Posts
    19

    Re: SQL Question

    Hi,

    im ms sql, it could also look like:

    -- check for part
    if not exists (select 1 from mytable where mypk = 'mypk')
    begin
    -- we dont have this row, create it
    insert into mytable (col1, col2, col3) values ('val1','val2', 'val3')
    end
    else
    begin
    -- its already there, update qty
    update mytable set col1 = col1+1 where mypk = 'mypk'
    end


    it could also be done in 2 separate stmts, using insert into... select ... where not exists... followed by an update...set qty=qty+1 where ....


    HTH,

    Fridthjof

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured