zoukankan      html  css  js  c++  java
  • sp_prepare

    sp_prepare用于参数化一个特定模式的sql语句,并返回句柄(handle),之后的sql语句就可以使用这个句柄来传递不同的参数。使用sp_prepare,可是让不同的参数的语句共用一个查询计划,避免声称不同的计划,从而节省编译时间。

    Syntax: sp_prepare handle OUTPUT, params, stmt, options

    1.下面是一个例子

    1)数据准备:

    create table testtable(id int ,c1 int)

    go

    insert testtable values(1,2)

    insert testtable values(1,3)

    insert testtable values(2,1)

    go

    create index index1 on testtable(id)

    2)使用 sp_prepare的例子:

    declare @N int

    exec sp_prepare @n output,N'@p1 int',N'select *From testtable where id=@p1'

    exec sp_execute @n,1---@n就是sp_prepare返回的句柄,使用sp_execute来通过这个句柄来传递参数

    exec sp_execute @n,2

    这两个语句的执行效果相当于:

    select *From testtable where id=1

    select *From testtable where id=2

    但是会使用同样的查询计划,且只编译了一次。

     2. .net代码调用sp_prepare

    下面是一个.net代码调用sp_prepare的例子

    SqlConnection con = new SqlConnection("server=stswordman6\sql2008r2_3;Trusted_Connection=True;");          

      con.Open(); 

    SqlCommand cmd = con.CreateCommand(); 

    cmd.CommandText = "exec sp_prepare @n output,N'@p1 int',N'select *From testtable where id=@p1'";

    SqlParameter par=cmd.CreateParameter();

                par.SqlDbType = System.Data.SqlDbType.Int;

                par.ParameterName="@n";

                par.Direction= System.Data.ParameterDirection.Output;

                cmd.Parameters.Add(par);

                cmd.ExecuteNonQuery();

                 cmd.CommandText = "exec sp_execute "+par.Value.ToString()+",1";

                 SqlDataAdapter da = new SqlDataAdapter(cmd);

                DataSet ds = new DataSet();

                da.Fill(ds);

                 Console.WriteLine(ds.Tables[0].Rows.Count);

                con.Close();

     

  • 相关阅读:
    php数组的使用
    php数组的定义、php数组的类型
    小米手机安卓手机微信里出现意外的边框线,border:0也没用
    php实现WEB在线文件管理器
    安装了https ssl证书,但浏览器显示并非完全安全(此页面内容部分不安全)
    thinkphp无限分类模块实现
    常见的移动web问题,终端触摸交互,各种bug坑如何解决
    现代都市风 移动端可折叠导航菜单
    电器类电商网站分类大菜单,配色超舒服~
    帮助中心模板框架--简约小清新风格
  • 原文地址:https://www.cnblogs.com/dotagg/p/6364488.html
Copyright © 2011-2022 走看看