简体   繁体   中英

sql server - insert if not exist else update

I have here a list of 100 types of item flavor. Then I have a table where I need a record for every item in every flavor. So if I have 50 items, I need 100 records for each of the 50 items in this table_A. so there will be a total of 100x50 records in this table at the end.

What I have now is a random mix of data and I know I don't have a record for each type of flavor for every item.

What I need help with is, an idea/algorithm so solve this problem. pseudo code would do. I have a table with all possible flavors (tbl_flavor) and a table with all 50 items (tbl_items). These two will dictate what needs to be put in table_A which is basically an inventory.

Please advise.

There are a few ways you can tackle this sort of problem. Here is psuedocode for one of those ways.

Update table
set Col1 = SomeValue
where MyKeys = Mykeys

if (@@ROWCOUNT = 0)
begin
    Insert table
    (Cols)
    Values
    (Vals)
end

Or you can use MERGE. https://msdn.microsoft.com/en-us/library/bb510625.aspx

If I'm understanding your question correctly, a SQL Server EXCEPT query will help.

As already pointed out in the comments, here's how to get the matrix of items and flavors:

SELECT Items.Item, Flavors.Flavor
FROM Items
CROSS JOIN Flavors

Here's how to get the matrix of items and flavors, omitting the combinations that are already in your other table.

SELECT Items.Item, Flavors.Flavor
  FROM Items
  CROSS JOIN Flavors
EXCEPT SELECT Item, Flavor
  FROM Table_A

So the INSERT becomes:

INSERT INTO Table_A (Item, Flavor)
SELECT Items.Item, Flavors.Flavor
  FROM Items
  CROSS JOIN Flavors
EXCEPT SELECT Item, Flavor
  FROM Table_A

This query is untested because I'm not 100% sure about the question. If you post more detail I'll test it.

Try This

UPDATE MyTable
        SET
        ColumnToUpdate = NewValue
        WHERE EXISTS
        (
            SELECT
                1
                FROM TableWithNewValue
                    WHERE ColumnFromTable1 = MyTable.ColumnName
        )

INSERT INTO MyTable
(
    Column1,
    Column2,
    ...
    ColumnN
)
SELECT
    Value1,
    Value2,
    ...
    ValueN
    FROM TableWithNewValue
        WHERE NOT EXISTS
        (
            SELECT
                1
                FROM MyTable 
                    WHERE ColumnName = TableWithNewValue.ColumnFromTable1 
        )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM