if exists(select name from sysobjects
            where name = 'tblToolsStringParserCounter')
drop table tblToolsStringParserCounter

go
create table dbo.tblToolsStringParserCounter
(
    ID INT
)
declare @i INT
select    @i = 1

while (@i <= 200)
begin
    insert into tblToolsStringParserCounter select @i
    select @i = @i + 1
end


if exists(select name from sysobjects
             where name = 'sp_thes_selConceptByRelation' and type = 'P')
    drop procedure sp_thes_selConceptByRelation
go

create procedure dbo.sp_thes_selConceptByRelation
    @conceptReferenceId int,
    @conceptNameId int,
    @relationIds varchar(100)
as


   create table #1
    (
        IDList Int
    )
    -- Optional index on the temp table
    create index idx1 on #1 (IDList)

    insert into #1
    select  Convert(Int, NullIf(SubString(',' + @relationIds + ',' , ID ,
     CharIndex(',' , ',' + @relationIds + ',' , ID) - ID) , '')) as IDList 
    from    tblToolsStringParserCounter
    where   ID <= Len(',' + @relationIds + ',') and SubString(',' + 
      @relationIds + ',' , ID - 1, 1) = ',' 
    and     CharIndex(',' , ',' + @relationIds + ',' , ID) - ID > 0  

    SELECT 
        PTNameFk1, (SELECT NameCache FROM Name WHERE NameId = PTNameFk1) as Name1,
        PTRefFK1, (select Title from Reference where RefId = PTRefFk1) as ReferenceName1,
        ('dataSchemaConcept') as dataSchemaConcept,
        RelQualifierFk, (select RelPTQualifier from RelPTQualifier where RelPTQualifierId = RelQualifierFk) as RelPtQualifier,
        PTNameFk2, (SELECT NameCache FROM Name WHERE NameId = PTNameFk2) as Name2,
        PTRefFk2, (select Title from Reference where RefId = PTRefFk2) as ReferenceName2
    FROM 
        RelPTaxon join #1 on #1.IDList = RelQualifierFk
    WHERE 
        PTNameFk2 = @conceptNameId AND PTRefFk2 = @conceptReferenceId

go