Skip to content Skip to sidebar Skip to footer

How Can I Update Sql Table Logic

I have a table structured as, Table 3 Fruit ID - Foreign Key (Primary Key of Table 1) Crate ID - Foreign Key (Primary Key of Table 2) Now I need to execute a query which will

Solution 1:

You can do an "upsert" with the MERGE syntax in SQL Server:

MERGE[SomeTable]AStargetUSING (SELECT @FruitID, @CrateID) ASsource (FruitID, CrateID)
ON (target.FruitID = source.FruitID)
WHEN MATCHED THEN 
    UPDATE SET CrateID = source.CrateID
WHENNOT MATCHED THEN   
    INSERT (FruitID, CrateID)
    VALUES (source.FruitID, source.CrateID);

Otherwise, you can use something like:

update [SomeTable] set CrateID =@CrateIDwhere FruitID =@FruitID
if @@rowcount=0insert [SomeTable] (FruitID, CrateID) values (@FruitID, @CrateID)

Post a Comment for "How Can I Update Sql Table Logic"