ALTER FUNCTION [dbo].[ftTicketStateList]
(
	@TicketId INT
)
RETURNS @list TABLE
(
	id INT NOT NULL,
	TicketState NVARCHAR(64) NOT NULL,
	[Order] INT NOT NULL,
	TicketStateBehaviorId INT NOT NULL
)
AS
BEGIN
	INSERT INTO @list SELECT * FROM dbo.ftTicketStateListIncResolved(@TicketId)

	DELETE FROM @list WHERE TicketStateBehaviorId in (3, 11)

	RETURN
END

GO

ALTER FUNCTION [dbo].[ftTicketsStateIntersectList] 
(
	@TicketIds nvarchar(200)
)
RETURNS @list TABLE
(
	id INT NOT NULL,
	TicketState NVARCHAR(64) NOT NULL,
	[Order] INT NOT NULL,
	TicketStateBehaviorId INT NOT NULL
)
AS
BEGIN
	DECLARE @splitStart int
	DECLARE @splitEnd int
	declare @ticketId int
	declare @ticketsEnd bit
	select @splitStart = 0
	select @ticketsEnd = 0
	
	while @ticketsEnd = 0
	begin
		select @splitEnd = CHARINDEX(',', @TicketIds, @splitStart)
		if @splitEnd = 0 and @splitStart = 0  		begin
			select @ticketId = CAST(@TicketIds as int)
		end
		if @splitEnd = 0 and not @splitStart = 0 		begin
			select @ticketId = cast(SUBSTRING(@TicketIds, @splitStart, 200) as int) 
		end
		if not @splitEnd = 0
		begin
			select @ticketId = cast(SUBSTRING(@TicketIds, @splitStart, @splitEnd - @splitStart) as int) 
		end
		if @ticketId > 0
		begin
			if @splitStart = 0  			begin
				INSERT INTO @list SELECT * FROM dbo.ftTicketStateList(@ticketId)
			end
			else
			begin
				delete from @list where not id in (select id from ftTicketStateList(@ticketId))
			end
		end

		if @splitEnd = 0
		begin
			select @ticketsEnd = 1
		end
		select @splitStart = @splitEnd + 1
	end
	
	RETURN 
END