SQLServer存储过程基本操作

来源:互联网 发布:如何编程手机游戏 编辑:程序博客网 时间:2024/06/01 07:37

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

if object_id(N'表',N'U') is not null   begindrop table integration_listend

查看存储过程是否存在

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

或者

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

判断空

--判断NULLselect * from table where 列名 is null--判断空串select * from table where 列名 = ''--判断空串或NULLselect * from table where isnull(列名,'') = ''

返回所有的表名

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_detailsgocreate procedure integration_detailsas--如果存在临时表就删除重新创建if object_id(N'#integration_top',N'U')is not null  begin drop table #integration_topend--建立临时表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 descselect 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有区别。

0 0
原创粉丝点击