我有一个ID和名称的表。我无法查询第4行和第5行

时间:2016-12-18 13:28:54

标签: sql sql-server

表A

ID  Name
1  Sachin
2  Rahul
3  Saurav

我想根据UI上的ID显示名称。

IDs are 1,2,3,1/2,1/2/3

我已经显示了1,2,3的名称,但是我无法像sachin / rahul和sachin / rahul / saurav那样获取1/2和1/2/3的id。

2 个答案:

答案 0 :(得分:1)

乐趣与字符串...以下将主要进行全局搜索并替换ID字符串。

现在,如果您需要更强大的方法,我们可以使用解析/拆分功能

Declare @YourTable table (ID int,Name varchar(25))
Insert Into @YourTable values
(1,'Sachin'),
(2,'Rahul'),
(3,'Saurav')

Declare @Fetch varchar(max) = '1,2,3,1/2,1/2/3'

Select @Fetch = Replace('|'+Replace(Replace(@Fetch,',','|,|'),'/','|/|')+'|',MapFrom,MapTo)
 From  (
        Select MapFrom='|'+cast(ID as varchar(25))+'|'
              ,MapTo  =Name
        From  @YourTable
       ) A
Select Replace(@Fetch,'|','')

返回

Sachin,Rahul,Saurav,Sachin/Rahul,Sachin/Rahul/Saurav
  

编辑 - 以防您需要TABLE版本

Declare @Names table (ID int,Name varchar(25))
Insert Into @Names values (1,'Sachin'),(2,'Rahul'),(3,'Saurav')

Declare @IDs table (ID int,IDList varchar(150))
Insert Into @IDs values (1,'1,2,3,1/2,1/2/3'),(2,'2,3,1/2/3')

;with cte as (
      Select A.*
            ,Name = IIF(Charindex('/',B.RetVal)>0 and C.RetVal>1,'/','')+N.Name
            ,RN  = Row_Number() over (Partition By A.ID Order By B.RetSeq,C.RetSeq)
       From  @IDs A
       Cross Apply [dbo].[udf-Str-Parse](A.IDList,',') B
       Cross Apply [dbo].[udf-Str-Parse](B.RetVal,'/') C
       Join  @Names N on N.ID=C.RetVal
)
Select Distinct 
       ID
      ,IDList
      ,NewString = Replace((Select Stuff((Select ',' +Name From cte Where ID=A.ID Order By RN For XML Path ('')),1,1,'') ),',/','/')
 From cte A

返回

ID  IDList            NewString
1   1,2,3,1/2,1/2/3   Sachin,Rahul,Saurav,Sachin/Rahul,Sachin/Rahul/Saurav
2   2,3,1/2/3         Rahul,Saurav,Sachin/Rahul/Saurav

UDF如有兴趣

CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table 
As
Return (  
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From (Select x = Cast('<x>'+ Replace(@String,@Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A 
    Cross Apply x.nodes('x') AS B(i)
);
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
--Performance On a 5,000 random sample -8K 77.8ms, -1M 79ms (+1.16), -- 91.66ms (+13.8)

答案 1 :(得分:0)

这样的东西?

declare     @ids    varchar(100) = '1/2/3'
           ,@names varchar(100) = ''

select      @names += case when @names = '' then '' else '/' end  + name
from        mytable
where       '/' + @ids +'/' like '%/' + cast(id as varchar(10)) + '/%'
order by    id  

select @names  
  

萨钦/拉胡/ Saurav