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();

     

  • 相关阅读:
    oracle2
    oracle1
    oracle1
    Java复习2.程序内存管理
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
  • 原文地址:https://www.cnblogs.com/dotagg/p/6364488.html
Copyright © 2011-2022 走看看