Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Comment passer un tableau de valeurs entières d'une table à une procédure stockée ?

Peut-être qu'un peu plus de SQL dynamique fera l'affaire (avec un parseur)

Declare @String varchar(max) = '1,25,659'
Declare @SQL varchar(max) = ''
Select @SQL = @SQL + concat('Exec [dbo].[sp1] ',Key_Value,';',char(13))
 From (Select * from [dbo].[udf-Str-Parse-8K](@String,',')) A

Select @SQL
--Exec(@SQL)

Retours

Exec [dbo].[sp1] 1;
Exec [dbo].[sp1] 25;
Exec [dbo].[sp1] 659;

L'UDF si besoin (super rapide !)

CREATE FUNCTION [dbo].[udf-Str-Parse-8K](@String varchar(8000), @Delimiter varchar(50))
Returns Table 
As

--Usage: Select * from [dbo].[udf-Str-Parse-8K]('Dog,Cat,House,Car',',')
--       Select * from [dbo].[udf-Str-Parse-8K]('John||Cappelletti||was||here','||')
--       Select * from [dbo].[udf-Str-Parse-8K]('The quick brown fox',' ')

Return (
   with cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
        cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 a, cte1 b, cte1 c, cte1 d) A ),
        cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter)) = @Delimiter),
        cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter,@String,s.N),0)-S.N,8000) From cte3 S)

   Select Key_PS    = Row_Number() over (Order By A.N)
         ,Key_Value = Substring(@String, A.N, A.L) 
         ,Key_Pos   = A.N
   From   cte4 A
)