Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Wie übergibt man ein Array von ganzzahligen Werten aus einer Tabelle an eine gespeicherte Prozedur?

Vielleicht reicht etwas dynamischeres SQL aus (zusammen mit einem Parser)

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)

Rückgabe

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

Die UDF bei Bedarf (superschnell!)

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
)