how can i update SQL table logic

前端 未结 1 1965
夕颜
夕颜 2021-01-22 07:48

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

相关标签:
1条回答
  • 2021-01-22 08:31

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

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

    Otherwise, you can use something like:

    update [SomeTable] set CrateID = @CrateID where FruitID = @FruitID
    if @@rowcount = 0
        insert [SomeTable] (FruitID, CrateID) values (@FruitID, @CrateID)
    
    0 讨论(0)
提交回复
热议问题