コンマ区切りの文字列を表にしてIN条件クエリーに参加します。
1154 ワード
戻り値は'1,2,3,4,5,6,7'という文字列ですが、INで検索するとsqlは完全な文字列と考えています。内容を分離してテーブルに変換する必要があります。
定義関数は以下の通りです。
呼び出し:
定義関数は以下の通りです。
create Function sysfStrToTable(@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
呼び出し:
declare @str as varchar(100)
set @str='1,2,3,4,6'
select * from table1
where
ID IN (SELECT * FROM dbo.sysfStrToTable(@str) )