ALTER PROCEDURE [dbo].[spTicketSearch] (@sample NVARCHAR(100), @personId int, @count int) 
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @ftsEnabled BIT = 1
	DECLARE @ftsTestQuery NVARCHAR(120) = 
	N'IF EXISTS(SELECT iHdTicketId FROM tHdTicket WHERE  CONTAINS(sHdTicket, N''_?_''))
		BEGIN
			no_op:
		END'
	BEGIN TRY
		EXECUTE sp_executesql @ftsTestQuery
	END TRY
	BEGIN CATCH
		SET @ftsEnabled = 0
	END CATCH
	IF  @ftsEnabled = 1	AND @sample != ' '
	BEGIN
		DECLARE @SQLString nvarchar(4000)
		DECLARE @ParmDefinition nvarchar(500)
		DECLARE @cond NVARCHAR(3500) = N''
		select @cond = @cond + N' AND (FORMSOF(INFLECTIONAL, "' + word + '" ) OR "' + word + '*")'
			from tfSplitString(@sample, ' ')
		select @cond = substring(@cond, 6, 3500)

		SET @SQLString =
		 N'
		 DECLARE @t TABLE (id INT PRIMARY KEY)
		 INSERT INTO @t
		 SELECT liHdTicketId FROM vHdTicketPersonRead WHERE liPersonId=@personId
		 SELECT TOP(@count)
				HDT.iHdTicketId AS TicketId,
				HDT.sHdTicketMessageTag + '' '' + HDT.sHdTicket AS TicketName
			FROM tHdTicket HDT
			join @t r on r.id=HDT.iHdTicketId
			WHERE HDT.dHdTicketRemoved IS NULL
				AND (CONTAINS(HDT.sHdTicket, @cond )
					OR HDT.iHdTicketId=CASE WHEN ISNUMERIC(@sample)=1 THEN CAST(@sample AS INT) ELSE NULL END)
			ORDER BY CASE WHEN ISNUMERIC(@sample)=1 AND iHdTicketId = CAST(@sample AS INT) THEN 1 ELSE 0 END DESC, iHdTicketId DESC'
		SET @ParmDefinition = N'@count int, @personId int, @sample NVARCHAR(100), @cond nvarchar(3500)'
		EXECUTE sp_executesql @SQLString, @ParmDefinition,
							  @count = @count,
							  @personId = @personId,
							  @cond = @cond,
							  @sample = @sample
	END
	ELSE
	BEGIN
		DECLARE @t TABLE (id INT PRIMARY KEY)
		INSERT INTO @t
		SELECT liHdTicketId FROM vHdTicketPersonRead WHERE liPersonId=@personId

		SELECT TOP(@count)
			HDT.iHdTicketId AS TicketId,
			HDT.sHdTicketMessageTag + ' ' + HDT.sHdTicket AS TicketName
		FROM tHdTicket HDT
			JOIN @t r on r.id=HDT.iHdTicketId
		WHERE HDT.dHdTicketRemoved IS NULL
			AND (HDT.sHdTicket LIKE '%' + @sample + '%' collate Latin1_General_CI_AI
				OR HDT.iHdTicketId=CASE WHEN ISNUMERIC(@sample)=1 THEN CAST(@sample AS INT) ELSE NULL END)
		ORDER BY CASE WHEN ISNUMERIC(@sample)=1 AND iHdTicketId = CAST(@sample AS INT) THEN 1 ELSE 0 END DESC,iHdTicketId DESC	
	END
	RETURN
END