Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

sql - Procedure With IN Parameter

Can you please help me, i want to create a procedure that allows me to send a parameter to put it in a IN clause, like this:

CREATE PROCEDURE [dbo].[NamesQry] 
@Names char(150)
AS 

SELECT * From Mydatabase Where
    Names in (@Names);

And execute

EXEC    [dbo].[IGDMediaSkills] 'Carl,Johnson'

The problem is that i don′t know how to send the multi parameters to the procedure.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

2 ways of doing this based upon your skill set.

  1. You can create a SQL CLR function.

    [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);
    }
    

Or...you can create a regular SQL Function:

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

Then to use:

SELECT * From Mydatabase Where Names in (select arrValue from dbo.fnArray(@Names, ','))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...