zoukankan      html  css  js  c++  java
  • Sql Server存储过程详解

    存储过程--查询:

    if (exists (select * from sys.objects where name = 'GetUser')) drop proc GetUser   --判断存储过程是否存在,存在则删除然后重建。
    go
    create proc GetUser  --创建存储过程 GetUser
    @Id int --参数
    as 
    set nocount on;  --不返回计数,提高应用程序性能
    begin --开始
        select * from [dbo].[User] where Id=@Id  --执行sql语句
    end;--结束

    调用存储过程

    EXEC GetUser 1;

    执行结果

     存储过程--修改:

    if (exists (select * from sys.objects where name = 'UpdateUser')) drop proc UpdateUser   --判断存储过程是否存在,存在则删除然后重建。
    go
    create proc UpdateUser  --创建存储过程 GetUser
    @Id int, --参数
    @Name varchar(255),--参数
    @Sex int, --参数
    @Age int, --参数
    @Birthday date --参数
    as 
    set nocount on;  --不返回计数,提高应用程序性能
    begin --开始     
        UPDATE [dbo].[UserInfo] SET [Name]=@Name,[Sex]=@Sex, [Age]=@Age,[Birthday]=@Birthday WHERE ([Id]=@Id) --执行sql语句
    end;--结束

    调用存储过程:

    EXEC UpdateUser 1,'赵大1',2,222,'1994-07-16 11:36:27';

    执行结果:

    存储过程分页

    --查询测试表(分页)
    if (exists (select * from sys.objects where name = 'Page_Test')) --判断存储过程是否存在,
    BEGIN 
      drop proc Page_Test   --存在则删除然后重建。
    END
    GO
    
    CREATE PROC Page_Test  --创建存储过程 
     @PageIndex INT,
     @PageSize INT,
     @Name nvarchar (50),
     @TypeId nvarchar (50)
    AS
    BEGIN  --开始
    DECLARE @PageHome  INT ; --起始页
    DECLARE @condition nvarchar (2000) ;--WHERE条件
    SET @PageHome = @PageIndex * @PageSize ;
    SET @condition = ' where 1=1 ' ;
    IF (@Name <> '')
    SET @condition =@condition + ' and Name like ''%' +@Name + '%''' ;
    IF (@TypeId <> '')
    SET @condition =@condition + ' and TypeId = ' +@TypeId + '';
    EXEC ('
    select top '+@PageSize+' * from (select row_number() over(order by Id asc) as rownumber,* from [Test] '+@condition+') AS  A where rownumber > '+@PageHome+'
    select count(*) as rows from [Test] '+@condition+'
    ') ;
    END ; --结束

    调用方式:

    EXEC Page_Test 1000,1000,'',''

    调用结果:(运行速度很快160W数据 0.3秒查询完成)

     

  • 相关阅读:
    docker 入门5
    docker 入门4
    Machine概念和获取帮助 【翻译】
    docker 入门3
    docker 入门2
    docker 入门1
    在生产环境中使用Compose 【翻译】
    docker常用命令整理
    ASP.NET WebAPI 06 HttpMessageHandler管道
    ASP.NET WebAPI 05 参数绑定
  • 原文地址:https://www.cnblogs.com/zj19940610/p/9655746.html
Copyright © 2011-2022 走看看