sql 存儲過程,最簡單的添加和修改

數據庫表結構數據庫

 《1》新增數據,而且按照"name" 字段查詢,若是重複返回「error」=-100 ,若是成功返回ID,若是失敗ID=0服務器

USE [數據庫]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[存儲過程名稱]
(
@name varchar(50),
@state int,
@capbility int,
@ip varchar(50),
@port int
)
AS
SET NOCOUNT ON;
BEGIN
declare @count int;
declare @id int;
--判斷此服務器是否已經註冊
select @count=COUNT(*) from serverlist where name =@name;
if(@count>0)--此服務器已經註冊過
BEGIN
select "ERROR" = -100; --此服務器已經註冊過
END else
BEGIN
insert into serverlist(name,[state],capbility,ip,port) values (@name,@state,@capbility,@ip,@port);select @@identity;
select @id;
END
ENDide

注意,代碼執行此存儲過程當中,只查詢表中第一個字段便可,string id=表.rows[0][0].tostring().trim(); server

《2》 修改數據,依然查詢詞數據是否已經存在blog

USE [數據庫]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[存儲過程名稱]
(
@name varchar(50),
@state int,
@capbility int,
@ip varchar(50),
@port int,
@id int
)
AS
SET NOCOUNT ON;
BEGIN
declare @count int;
declare @return int;
select @count=COUNT(*) from serverlist where name =@name and ID<>@id;
if(@count>0)
BEGIN
select "error"=-100;
end
begin
select @count=COUNT(*) from serverlist where id =@id
if(@count>0)
begin
update serverlist set name=@name,[state]=@state,capbility=@capbility,ip=@ip,port=@port where ID=@id;
set @return = 1;
end else
begin
set @return = 0;
end
end
select @return;
END


ip

相關文章
相關標籤/搜索