zoukankan      html  css  js  c++  java
  • 动态sql语句

          当需要根据外部输入的参数来决定要执行的SQL语句时,常常需要动态来构造SQL查询语句,个人觉得用得比较多的地方就是执行搜索查询的SQL语句。对于搜索,可能要根据搜索条件判断来动态执行SQL语句。

    在SQL Server中有两种方式来执行动态SQL语句,分别是exec和sp_executesql。sp_executesql相对而言具有更多的优点,它提供了输入输出接口,可以将输入输出变量直接传递到SQL语句中,而exec只能通过拼接的方式来实现。还有一个优点就是sp_executesql,能够重用执行计划,这就大大提高了执行的性能。所以一般情况下建议选择sp_executesql来执行动态SQL语句。  

     

    下面来看看几种动态执行SQL语句的情况

    1.普通SQL语句

    (1)exec('select * from Student')

    (2)exec sp_executesql N'select * from Student'--此处一定要加上N,否则会报错

    2.带参数的SQL语句

    (1)declare @sql nvarchar(1000)
        declare @userId varchar(100)
        set @userId='0001'
        set @sql='select * from Student where UserID='''+@userId+''''

        exec(@sql)

    (2)declare @sql nvarchar(1000)
    declare @userId varchar(100)
    set @userId='0001'
    set @sql=N'select * from Student where UserID=@userId'
    exec sp_executesql @sql,N'@userId varchar(100)',@userId

      从这个例子中可以看出使用sp_executesql可以直接将参数写在sql语句中,而exec需要使用拼接的方式,这在一定程度上可以防止SQL注入,   因此sp_executesql拥有更高的安全性。另外需要注意的是,存储sql语句的变量必须声明为nvarchar类型的。

    (3)带输出参数的SQL语句

    create procedure sp_GetNameByUserId

    (

        @userId varchar(100),

    @userName varchar(100) output

    )

    as

    declare @sql nvarchar(1000)

    set @sql=N'select @userName=UserName from Student where UserId=@userId'

    exec sp_executesql N'@userId varchar(100),@userName varchar(100) output',@userId,@userName output

      select @userName


  • 相关阅读:
    关于Dll、Com组件、托管dll和非托管dll的理解
    委托-异步调用-泛型委托-匿名方法-Lambda表达式-事件
    类静态和实例化执行顺序优先级(静态构造函数、静态变量、静态方法)
    ActionFilter的四个方法使用场景
    C# 中? 和 ?? 在变量中的使用
    Nginx 安装配置
    jetty + maven + (frontend) + eclipse
    plsql function
    [Postgres] drop database , but the database is being accessed by other users
    js在table中添加tbody块,方便整块的添加和删除
  • 原文地址:https://www.cnblogs.com/riskyer/p/3347953.html
Copyright © 2011-2022 走看看