在SQL中下"IN" 的動態查詢條件
如何能在SQL中下"IN" 的動態查詢條件,而且要避免駭客利用SQL Injection (資料隱碼)入侵呢?
可以先將@字串轉為@table,然後再WHERE COL_NAME IN (SELECT col from @table)
以下提供一個範例:
DECLARE @Merchant_Number varchar(max)
DECLARE @split varchar(2)
DECLARE @t table(col varchar(20))
SELECT @Merchant_Number='211170011,211170012,010010007,020520034',@split=','
while(charindex(@split,@Merchant_Number)<>0)
begin
insert @t(col) values (substring(@Merchant_Number,1,charindex(@split,@Merchant_Number)-1))
set @Merchant_Number = stuff(@Merchant_Number,1,charindex(@split,@Merchant_Number),'')
end
insert @t(col) values (@Merchant_Number)
SELECT *
FROM MERCHANT WITH(NOLOCK)
WHERE MERCHANT_NUMBER IN (SELECT col from @t)