Procedure With IN Parameter

前端 未结 1 1245
一生所求
一生所求 2020-12-12 07:20

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         


        
相关标签:
1条回答
  • 2020-12-12 07:41

    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, ','))
    
    0 讨论(0)
提交回复
热议问题