1

我有一张桌子

表名 TB1
mpeFromWHId mpeToStoreList
8 16,18,24

和 Tabletb2是逗号分隔的 storeid 的代码

nlid nlcode
16个
18 毫升
24 分

我需要一个会导致

col1 Col2
8 ncl,mcl,dcl
4

2 回答 2

3

首先,您需要一个函数将逗号分隔的字符串解析为表,您可以使用它(找到 [here])1

CREATE FUNCTION [dbo].Split1(@input AS Varchar(4000) )
RETURNS
      @Result TABLE(Value BIGINT)
AS
BEGIN
      DECLARE @str VARCHAR(20)
      DECLARE @ind Int

      IF(@input is not null)
      BEGIN
            SET @ind = CharIndex(',',@input)
            WHILE @ind > 0
            BEGIN
                  SET @str = SUBSTRING(@input,1,@ind-1)
                  SET @input = SUBSTRING(@input,@ind+1,LEN(@input)-@ind)
                  INSERT INTO @Result values (@str)
                  SET @ind = CharIndex(',',@input)
            END
            SET @str = @input
            INSERT INTO @Result values (@str)
      END
      RETURN
END 

然后你可以使用这样的东西(但当然还有更多的选择):

declare @searchId int
set @searchId = 8

declare @tb1 table (mpeFromWHId int, mpeToStoreList varchar(100))
insert into @tb1
select 8, '16,18,24'

declare @tb2 table (nlid int, nlcode varchar(30))
insert into @tb2
select 16, 'ncl' union
select 18, 'mcl' union
select 24, 'dcl'

select stuff((
    select ',' + nlcode
    from @tb2
    where nlid in (
        select Value 
        from dbo.Split1((select mpeToStoreList from @tb1 where mpeFromWHId = @searchId))
    )
    order by nlcode
    for xml path(''), type
).value('(./text())[1]','varchar(max)'), 1, 2, '')
于 2013-09-23T07:15:26.797 回答
0

如果您不想创建用户功能,可以这样做:

;with TB1(mpeFromWHId, mpeToStoreList) AS (
   select 8,'16,18,24'
)
SELECT t.mpeFromWHId,n.ID FROM (
      select *,convert(XML,'<n>'+replace(mpeToStoreList,',','</n><n>')+'</n>') as x from tb1 
) AS t
cross apply(select s.b.value('.','INT') as ID from t.x.nodes('n') s(b)) n
mpeFromWHId ID

8 16
8 18
8 24
于 2016-09-03T10:30:08.520 回答