在存储过程中,最好是简单地查询数据或构造查询然后执行它?为什么?

pav*_*red 2 sql sql-server stored-procedures

我已经研究过SQL存储过程,我注意到很多人使用两种不同的方法 -

首先,使用选择查询,例如

Select * from TableA where colA = 10 order by colA
Run Code Online (Sandbox Code Playgroud)

其次,是通过构建查询来做同样的事情

Declare @sqlstring varchar(100)
Declare @sqlwhereclause varchar(100)
Declare @sqlorderby varchar(100)

Set @sqlstring = 'Select * from TableA '
Set @sqlwhereclause = 'where colA = 10 '
Set @sqlorderby = 'order by colA'

Set @sqlstring = @sqlstring + @sqlwhereclause + @sqlorderby 
exec @sqlstring
Run Code Online (Sandbox Code Playgroud)

现在,我知道两者都很好.但是,我提到的第二种方法是维护有点烦人.

我想知道哪一个更好?是否有任何具体原因可以采用一种方法而不是另一种方法?一种方法比其他方法有什么好处?

Ode*_*ded 5

使用第一个.这将允许正确缓存查询计划,除了您应该使用SQL的方式.

除了其他问题之外,第二个对SQL注入攻击持开放态度.

使用动态SQL,您将无法进行编译时检查,因此只有在调用时才会失败(您越早了解错误的语法,就越好).

并且,您注意到自己,维护负担也更高.