【问题标题】:Perform insert and update operation in one procedure在一个过程中执行插入和更新操作
【发布时间】:2015-07-29 06:21:05
【问题描述】:

我在数据库中有一个表 Country ,其中包含以下字段

  • 国家标识
  • 国名

现在我必须编写一个程序,它首先检查@CountryName 是否存在。如果它已经存在,它应该更新该行。如果它不存在它应该执行插入操作...

【问题讨论】:

标签: mysql sql sql-server-2008


【解决方案1】:
Create Proc [ProcedureName]
@CountryName nvarchar(100)
As
Begin
Declare @Count int
Set @Count = (Select count(CountryId) from Country where CountryName = @CountryName)
if @Count > 0
Begin
-- update 
End
else
begin
-- insert
end

End

【讨论】:

    【解决方案2】:

    如果您使用的是 SQL Server 2005(或更高)版本,请考虑使用MERGEstatement。 Documentation for MERGE here.

    merge [country] as target
    using (select @CountryID, @CountryName) as source(id, name)
    on (target.Countryid = source.id)
    when matched then
        update set CountryName = @CountryName
    when not matched then
        insert (CountryId, CountryName) values (source.id, source.name);
    

    【讨论】:

    • 我知道!这只是另一种方法。
    • 是的,我知道,我的评论是给未来的用户的
    【解决方案3】:

    我认为下面的脚本会对你有所帮助。

    CREATE PROCEDURE ProcedureName
    @CountryName nvarchar(100),
    @CountryID int
    
    AS
    BEGIN
    
    IF EXISTS (SELECT 1 FROM dbo.Country WHERE CountryName = @CountryName)
    BEGIN
        --UPDATE
    END
    
    ELSE
    BEGIN
        --INSERT
    END
    
    END
    

    你也可以用SQL的merge关键字来做上面的代码 查找参考 here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-19
      • 2011-07-04
      • 1970-01-01
      • 2021-07-25
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多