【发布时间】:2015-07-29 06:21:05
【问题描述】:
我在数据库中有一个表 Country ,其中包含以下字段
- 国家标识
- 国名
现在我必须编写一个程序,它首先检查@CountryName 是否存在。如果它已经存在,它应该更新该行。如果它不存在它应该执行插入操作...
【问题讨论】:
标签: mysql sql sql-server-2008
我在数据库中有一个表 Country ,其中包含以下字段
现在我必须编写一个程序,它首先检查@CountryName 是否存在。如果它已经存在,它应该更新该行。如果它不存在它应该执行插入操作...
【问题讨论】:
标签: mysql sql sql-server-2008
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
【讨论】:
如果您使用的是 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);
【讨论】:
我认为下面的脚本会对你有所帮助。
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
【讨论】: