大数据&云计算|SQL存储过程的详细用法,不信你看不懂( 二 )


示例:查询订单表中订单总数

--查询存储过程IF OBJECT_ID (N"PROC_ORDER_COUNT", N"P") IS NOT NULLDROP procedure PROC_ORDER_COUNTGOCREATE procedure PROC_ORDER_COUNTAS SELECT COUNT(OrderID) FROM OrdersGO--执行上述存储过程:EXEC PROC_ORDER_COUNT
2、创建带参数的存储过程
示例:根据城市查询订单数量
--查询存储过程 , 根据城市查询总数IF OBJECT_ID (N"PROC_ORDER_COUNT", N"P") IS NOT NULLDROP procedure PROC_ORDER_COUNTGOCREATE procedure PROC_ORDER_COUNT(@city nvarchar(50))ASSELECT COUNT(OrderID)FROM Orders WHERE City=@cityGO--执行上述存储过程:EXEC PROC_ORDER_COUNTN"GuangZhou"
进阶应用
3、参数带通配符
--查询订单编号头两位是LJ的订单信息 , 含通配符IF OBJECT_ID (N"PROC_ORDER_INFO", N"P") IS NOT NULLDROP procedure PROC_ORDER_INFOGOCREATE procedure PROC_ORDER_INFO@OrderIDnvarchar(50)="LJ%"--默认值AS SELECT OrderID,City,OrderDate,Price FROM OrdersWHERE OrderID like @OrderIDGO--执行上述存储过程:EXEC PROC_ORDER_INFOEXEC PROC_ORDER_INFO N"LJ%"EXEC PROC_ORDER_INFO N"%LJ%"
4、带输出参数

--根据订单查询的信息 , 返回订单的城市及单价IF OBJECT_ID (N"PROC_ORDER_INFO ", N"P") IS NOT NULLDROP procedure PROC_ORDER_INFO GOCREATE procedure PROC_ORDER_INFO@orderidnvarchar(50),--输入参数@citynvarchar(20) out,--输出参数@price float output--输入输出参数AS SELECT @city=City,@price=Price FROM OrdersWHERE OrderID=@orderidAND Price=@priceGO--执行上述存储过程:declare @orderidnvarchar(50),@citynvarchar(20),@price intset @orderid= N"LJ0001"set @price = 35.21exec PROC_ORDER_INFO @orderid,@city out, @price outputselect @city, @price
上面两个在平时工作中遇到的较少 , 需要的时候知道怎么用即可 , 1 , 2个是必须掌握的操作 。
存储过程进行增删改
1、新增
--新增订单信息IF OBJECT_ID (N"PROC_INSERT_ORDER", N"P") IS NOT NULLDROP procedure PROC_INSERT_ORDERGOCREATE procedure PROC_INSERT_ORDER@orderidnvarchar(50),@city nvarchar(20),@price floatAS INSERT INTO Orders(OrderID,City,Price)VALUES(@orderid,@city,@price)GO--执行EXEC PROC_INSERT_ORDER N"LJ0001",N"GuangZhou",35.21
2、修改

--修改订单信息IF OBJECT_ID (N"PROC_UPDATE_ORDER", N"P") IS NOT NULL DROP procedure PROC_UPDATE_ORDERGOCREATE procedure PROC_UPDATE_ORDER @orderid nvarchar(50), @city nvarchar(20), @price floatASUPDATE Orders SET OrderID=@orderid,City=@city,Price=@priceGO--执行EXEC PROC_UPDATE_ORDER N"LJ0001",N"ShangHai",37.21
3、删除
--修改订单信息IF OBJECT_ID (N"PROC_DELETE_ORDER", N"P") IS NOT NULLDROP procedure PROC_DELETE_ORDERGOCREATE procedure PROC_DELETE_ORDER@orderid nvarchar(50),AS DELETEFROM Orders WHERE OrderID=@orderidGO--执行EXEC PROC_DELETE_ORDER N"LJ0001"
存储过程其他功能
这部分是选修内容 , 有兴趣的可以了解一下
1、重复编译存储过程
--重复编译IF OBJECT_ID (N"PROC_ORDER_WITH_RECOMPILE", N"P") IS NOT NULLDROP procedure PROC_ORDER_WITH_RECOMPILEGOCREATE procedure PROC_ORDER_WITH_RECOMPILEwith recompile --重复编译AS SELECT * FROM OrdersGO


推荐阅读