SQL多條件查詢安全高效比較

2021-10-08 06:37:03 字數 1806 閱讀 9537

alter  procedure _tmp

@id varchar(50),

@pn varchar(50),

@type int

asbegin

/**********************************

-- 功能:多條件查詢效能

_tmp 'k3g8kg6nn94sbbs0','k7f7ff',0

**********************************/

print '測試資料條數500w'

set nocount on

declare @time datetime

declare @warring varchar(5000)

if(@type=1 or @type=0)

begin

set @warring=char(10)+'第一種方式,直接拼sql語句,有sql注入漏洞';print @warring;select @warring

set @time=getdate()

declare @sql varchar(4000)

select @sql='select * from dbo.tb_timetest where 1=1'

if(isnull(@id,'')<>'')    set @sql=@sql+' and id='''+@id+''''

if(isnull(@pn,'')<>'')    set @sql=@sql+' and pn='''+@pn+''''    

exec(@sql)

print '所需時間_毫秒'

print datediff(millisecond,@time,getdate())

endif(@type=2 or @type=0)

begin

set @warring=char(10)+'第二種方式,沒有像第一種方式那樣的sql漏洞,但是效能大大折扣,就是耗時';print @warring;select @warring

set @time=getdate()

select * from  dbo.tb_timetest where (isnull(@id,'')=''or id = @id) and (pn = @pn or @pn is null)

print '所需時間_毫秒'

print datediff(millisecond,@time,getdate())

endif(@type=3 or @type=0)

begin

set @warring=char(10)+'第三種方式,雖然寫法沒有第二種簡潔,但是也沒有像第一種方式那樣的sql注入漏洞,是本人目前能想到最優的';print @warring;select @warring

set @time=getdate()

declare @s nvarchar(4000),@p nvarchar(4000)

set @p=n'@id varchar(50),@pn varchar(50)'

set @s='select * from dbo.tb_timetest where 1=1'

if(isnull(@id,'')<>'')    set @s=@s+' and id = @id'

if(isnull(@id,'')<>'')    set @s=@s+' and pn = @pn'

exec sp_executesql @s,@p,@id=@id,@pn=@pn

print '所需時間_毫秒'

print datediff(millisecond,@time,getdate())

endend

SQL多條件查詢子查詢SQL多條件查詢子查詢

多條件搜尋時where 1 1並不高效,如果使用這種方法,在資料庫中會做全表查詢 對每行資料都進行掃瞄比對 會無法使用索引等優化查詢的策略,建立的索引會暫時失效。case函式 case必須和end一起使用,下接when then select 數學成績 case when math 100 then...

Sql多條件查詢

sql 多條件查詢的一種簡單的方法 以前我們做多條件查詢,一種是排列結合,另一種是動態拼接sql 如 我們要有兩個條件,乙個日期 adddate,乙個是 name 第一種寫法是 if adddate is not null and name select from table where addda...

多條件查詢的sql

用程式來生成。例如 四個框分別為 txt1,txt2,txt3 對應字段分別為 key1,key2,key3,key4 查詢的表名為 table 程式如下 txt1 requtst.form txt1 取得變數 txt2 requtst.form txt2 txt3 requtst.form txt...