SQLServer存储过程基本操作

存储过程通常被使用在重数据交互的场合,它能使服务端的处理逻辑更简单,最极端的情况是,服务端只管和数据库进行交互,而不需要根据业务逻辑对数据进行过多处理。使用存储过程的另外一个好处是方便数据测试,直接执行存储过程查看结果,就能根据结果判断业务逻辑是否正确。
查看表是否存在

if object_id(N'表',N'U') is not null   
begin
drop table integration_list
end

查看存储过程是否存在

if object_id(N'存储过程',N'P') is not null
begin
drop procedure 存储过程
end

或者

if exists(select name from sysobjects where name=N'存储过程名字' type=N'p')
drop procedure 存储过程名字 

返回所有的表名

select name from sysobjects where type=N'U'

返回所有存储过程的名字

select name from sysobjects where type=N'P'

例子:

use temp --使用库
if exists(select name from sysobjects where name=N'integration_details' and type=N'p')
drop procedure integration_details
go
create procedure integration_details
as

--如果存在临时表就删除重新创建
if object_id(N'#integration_top',N'U')is not null  
begin 
drop table #integration_top
end
--建立临时表
create table #integration_top
       (
        customer_id nvarchar(20),
        integration int
         )


insert into #integration_top(customer_id,integration)select top 200 cuno,sum(jifen) as integration from [xa_wechat].[dbo].[tbwx_jifen] where jftype !='活期存款积分' and jftype !='定期存款积分' group by cuno order by integration desc

select customer_id,integration from #integration_top    --积分前一百的客户

select cuno,jftype,jifen,integration from [xa_wechat].[dbo].[tbwx_jifen],#integration_top where cuno in (select customer_id from #integration_top) and cuno=customer_id and jftype !='活期存款积分' and jftype !='定期存款积分'  order by integration desc  --积分前一百客户详情
--删除临时表
drop table #integration_top

注意:SQLServer的语法和MySql有区别。

posted @ 2016-08-01 17:58  sam976  阅读(298)  评论(0编辑  收藏  举报