• 动态SQL的执行,注:exec sp_executesql 其实可以实现参数查询和输出参数的


    本文转自:http://www.cnblogs.com/hnsdwhl/archive/2011/07/23/2114730.html

    当需要根据外部输入的参数来决定要执行的SQL语句时,常常需要动态来构造SQL查询语句,个人觉得用得比较多的地方就是分页存储过程和执行搜索查询的SQL语句。一个比较通用的分页存储过程,可能需要传入表名,字段,过滤条件,排序等参数,而对于搜索的话,可能要根据搜索条件判断来动态执行SQL语句。

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

      使用sp_executesql需要注意的一点就是,它后面执行的SQL语句必须是Unicode编码的字符串,所以在声明存储动态SQL语句的变量时必须声明为nvarchar类型,否则在执行的时候会报“过程需要类型为 'ntext/nchar/nvarchar' 的参数 '@statement'”的错误,如果是使用sp_executesql直接执行SQL语句,则必须在前面加上大写字母N,以表明后面的字符串是使用Unicode类型编码的。

      下面来看看几种动态执行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

  • 相关阅读:
    Dependency property changed example
    业务数据分析
    WPF : 以鼠标指针为中心缩放
    WPF待学习问题列表(未完)
    GirdView前台数据类型转换
    牛人的博客
    使用Xpath对XML进行模糊查询
    XPath语法
    【HDU】3415 Max Sum of MaxKsubsequence
    【HDU】3474 Necklace
  • 原文地址:https://www.cnblogs.com/zhouyunbaosujina/p/4389346.html
Copyright © 2020-2023  润新知