2 начина да направите това въз основа на вашия набор от умения.
-
Можете да създадете SQL CLR функция.
[Microsoft.SqlServer.Server.SqlFunction(Name="fnToList", FillRowMethodName="FillRow", TableDefinition="ID NVARCHAR(1000)")] public static IEnumerable SqlArray(SqlString inputString, SqlString delimiter) { if (string.IsNullOrEmpty(delimiter.Value)) return new string[1] { inputString.Value }; return inputString.Value.Split(delimiter.Value.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); } public static void FillRow(object row, out SqlString str) { str = new SqlString((string)row); }
Или... можете да създадете обикновена SQL функция:
CREATE FUNCTION [dbo].[fnArray] ( @Str varchar(8000), @Delim varchar(1) = ' ' )
returns @tmpTable table ( arrValue varchar(25))
as
begin
declare @pos integer
declare @lastpos integer
declare @arrdata varchar(8000)
declare @data varchar(25)
set @arrdata = replace(replace(replace(replace(upper(@Str),@Delim,'|'),'-',''),'/','|'),'\','|')
set @arrdata = @arrdata + '|'
set @lastpos = 1
set @pos = 0
set @pos = charindex('|', @arrdata)
while @pos <= len(@arrdata) and @pos <> 0
begin
set @data = substring(@arrdata, @lastpos, (@pos - @lastpos))
if rtrim(ltrim(@data)) > ''
begin
if not exists( select top 1 arrValue from @tmpTable where arrValue = @data )
begin
insert into @tmpTable ( arrValue ) values ( @data )
end
end
set @lastpos = @pos + 1
set @pos = charindex('|', @arrdata, @lastpos)
end
return
end
След това да използвате:
SELECT * From Mydatabase Where Names in (select arrValue from dbo.fnArray(@Names, ','))