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

Sql Server 中將由逗號「,」分割的一個字符串,轉換爲一個表,並應用與 in 條件sql

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行,每一行存一個項目(用逗號分隔開的一部分)spa

該函數能夠這樣寫:code

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語句就能夠這樣了xml

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),轉換爲一個字段的表結果集)blog

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形式展示(將結果集以某種形式關聯成一個字符串)
相關文章
相關標籤/搜索