Sql Server 中將由逗號“,”分割的一個字符串轉換為一個表集,並應用到 in 條件中


Sql Server 中將由逗號“,”分割的一個字符串,轉換為一個表,並應用與 in 條件

select * from tablenmae where id in(1,2,3)

這樣的語句和常用,但是如果in 后面的 1,2,3是變量怎么辦呢,一般會用字符串連接的方式構造sql語句

string aa=”1,2,3”;

string sqltxt=”select * from tablename where id in (“+aa+”)”;

然后執行 sqltxt

這樣的風險是存在sql注入漏洞。那么如何在 in 的條件中使用變量呢?可以把形如“1,2,3”這樣的字符串轉換為一個臨時表,這個表有一列,3行,每一行存一個項目(用逗號分隔開的一部分)

該函數可以這樣寫:

create Function StrToTable(@str varchar(1000)) 
Returns @tableName Table 
( 
str2table varchar(50) 
) 
As 
–該函數用於把一個用逗號分隔的多個數據字符串變成一個表的一列,例如字符串’1,2,3,4,5’ 將編程一個表,這個表 
Begin 
set @str = @str+’,’ 
Declare @insertStr varchar(50) –截取后的第一個字符串 
Declare @newstr varchar(1000) –截取第一個字符串后剩余的字符串 
set @insertStr = left(@str,charindex(‘,’,@str)-1) 
set @newstr = stuff(@str,1,charindex(‘,’,@str),”) 
Insert @tableName Values(@insertStr) 
while(len(@newstr)>0) 
begin 
set @insertStr = left(@newstr,charindex(‘,’,@newstr)-1) 
Insert @tableName Values(@insertStr) 
set @newstr = stuff(@newstr,1,charindex(‘,’,@newstr),”) 
end 
Return 
End

然后sql語句就可以這樣了

declare str vchar(100); --定義str變量

set str=’1,2,3’; --給變量賦值

select * from tablename where id in (select str2table from StrToTable(@str) )

解釋:

A. select str2table from StrToTable(1,2,3) --調用函數StrToTable(1,2,3),執行出來的結果就是:(由逗號“,”分割的一個字符串(1,2,3),轉換為一個字段的表結果集)

str2table
1
2
3

 

 

 

 

B.
select * from tablename where id in (select str2table from StrToTable(1,2,3)) 
就相當於執行了
select * from tablename where id in (1,2,3)

最后:附一個實際項目sql例子

declare @str varchar(1000)  --定義變量

select @str=hylb from [dbo].[f_qyjbxx] where qyid = ${qyid} --給變量賦值

select xsqxtbzd+','
from [dbo].[d_hylb]
where hylbid in (select str2table from strtotable(@str))  --調用函數
      for xml path('');  --將查詢結果集以XML形式展現(將結果集以某種形式關聯成一個字符串)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM