打开SQL Server 2005的管理工具,选中需要创建存储过程的数据库,找到“可编程性”,展开后可以看到“存储过程”。右键点击它,选择“新建存储过程”,右侧的编辑窗口打开了,里面装着微软自动生成的SQL Server创建存储过程的语句。
将存储过程的名字,参数,操作语句写好后,点击语法分析,没有错误就直接“F5”运行就好了,存储过程创建完毕,以下是一个基本的存储过程的代码:
CREATE PROCEDURE Get_Data ( @Dealer_ID VARCHAR(50) //定义数据Dealer_ID 类型为varchar ) AS SELECT * FROM myData WHERE Dealer_ID = @Dealer_ID
既然创建存储过程已经会了,那么修改还会难吗?显然不会。修改存储过程也是相当的容易。首先,刷新当前数据库的存储过程列表,这时就能看到你刚创建的存储过程的名字了,右键点击它,选择修改,右侧又打开了一个编辑窗口,装着的就是修改存储过程的代码(如下)
ALTER PROCEDURE [dbo].[Get_Data] ( @Dealer_ID VARCHAR(50), @Period VARCHAR(20) ) AS SELECT * FROM myData WHERE Dealer_ID = @Dealer_ID AND Period = @Period
1 CREATE PROCEDURE PROC_INSERT_DATA_DETAIL 2 @DealerID varchar(50), 3 @FieldName varchar(2000), 4 @FieldValue varchar(2000) 5 AS 6 BEGIN 7 DECLARE @Count INT 8 SET @Count = (SELECT COUNT(*) FROM myDATA_Details WHERE DealerID = @DealerID) 9 10 IF (@COUNT>0) 11 BEGIN 12 UPDATE myDATA_Details SET DealValue = @FieldValue WHERE DealerID = @DealerID 13 END 14 ELSE 15 BEGIN 16 INSERT INTO myDATA_Details (DealerID) VALUES (@DealerID) 17 END 18 END
1 ALTER PROCEDURE PROC_INSERT_DATA_DETAIL 2 @DealerID varchar(50), 3 @FieldName varchar(2000), 4 @FieldValue varchar(2000) 5 AS 6 BEGIN 7 DECLARE @Count INT 8 DECLARE @StrSQL VARCHAR(2000) 9 SET @Count = (SELECT COUNT(*) FROM myDATA_Details WHERE DealerID = @DealerID) 10 11 IF (@COUNT>0) 12 BEGIN 13 SET @StrSQL = 'UPDATE myDATA_Details SET '+ @FieldName + ' = ''' +@FieldValue + ''' WHERE DealerID = '+ @DealerID 14 EXEC(@StrSQL) 15 END 16 ELSE 17 BEGIN 18 INSERT INTO myDATA_Details (DealerID) VALUES (@DealerID) 19 SET @StrSQL = 'UPDATE myDATA_Details SET '+ @FieldName + ' = ''' +@FieldValue + ''' WHERE DealerID = '+ @DealerID 20 EXEC(@StrSQL) 21 END 22 END