2 sätt att göra detta baserat på din kompetens.
-
Du kan skapa en SQL CLR-funktion.
[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); }
Eller... du kan skapa en vanlig SQL-funktion:
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
Använd sedan:
SELECT * From Mydatabase Where Names in (select arrValue from dbo.fnArray(@Names, ','))