Showing posts with label stored. Show all posts
Showing posts with label stored. Show all posts

Wednesday, 11 November 2015

Pass String Array to stored procedure

Split function to split array of integers values

if object_id('Split') is not null
    drop function split
go

create function dbo.Split
(
    @String varchar(max)
)
returns @SplittedValues table
(
    Id int primary key
)
as
begin
    declare @SplitLength int, @Delimiter varchar(5)

    set @Delimiter = ','

    while len(@String) > 0
    begin
        select @SplitLength = (case charindex(@Delimiter,@String) when 0 then
            len(@String) else charindex(@Delimiter,@String) -1 end)

        insert into @SplittedValues
        select convert(int, substring(@String,1,@SplitLength) )

        select @String = (case (len(@String) - @SplitLength) when 0 then  ''
            else right(@String, len(@String) - @SplitLength - 1) end)
    end
return 
end



Then create the  stored procedure 

CREATE PROCEDURE getLastInsertedRecods
       -- Add the parameters for the stored procedure here
       @currentDate as datetime,
       @carServiceIds as varchar
AS
BEGIN
       -- SET NOCOUNT ON added to prevent extra result sets from
       -- interfering with SELECT statements.
       SET NOCOUNT ON;

    -- Insert statements for procedure here
      
       SELECT TOP 10 carServiceId, position_x, position_y, speed, EngineOn
       FROM Vechile_track
       where dTime>=convert(date,@currentDate) and carServiceId in (select ID from dbo.Split(@carServiceIds))
       ORDER BY dTime ASC

END