I have a table with
Table name TB1 mpeFromWHId mpeToStoreList 8 16,18,24
and Table tb2
are the codes of the comma separated storeid
nlid nlcode 16 ncl 18 mcl 24 dcl
I need a query that will result in
col1 Col2 8 ncl,mcl,dcl
I have a table with
Table name TB1 mpeFromWHId mpeToStoreList 8 16,18,24
and Table tb2
are the codes of the comma separated storeid
nlid nlcode 16 ncl 18 mcl 24 dcl
I need a query that will result in
col1 Col2 8 ncl,mcl,dcl
First you need a function to parse comma delimited string into table, you can use this (found [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
Then you can use something like this (but there are many more options off course):
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, '')
If you don't want to create a user function, you can do like this:
;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