我在数据库中有一个表国家,其中包含以下字段
现在,我必须编写一个过程,它将首先检查@CountryName名称是否存在。如果它已经存在,它应该更新该行。如果它不存在它应该执行插入操作..。
发布于 2015-07-29 08:46:00
我想下面的脚本会对你有帮助。
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 find引用这里的merge关键字执行上述代码。
发布于 2015-07-29 08:48:25
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发布于 2015-07-29 09:13:03
如果使用的是Server 2005(或更高版本),请考虑使用MERGE语句。这里合并的文档。
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);https://stackoverflow.com/questions/31692652
复制相似问题