Scenario: Create a query that will output the LegID and the CarriCode where in the MCode should matched on the 3rd table. I am using string_split to individually check if the MCode is existing in the 3rd table
Sample table and data can be found here: http://sqlfiddle.com/#!18/f8bd9f
The expected output is this:
LegID, CarriCode
1 AB
3 AD
since CarriCode AB and AD has an MCode of DJM_3R, DJM_1R respectively wherein their MCode is existing in dbo.EFTest table.
My sample query looks like this:
SELECT L.LegID, L.CarriCode
INTO #test
FROM dbo.Leg L
INNER JOIN dbo.[Carri] C
ON L.CarriCode = C.CarriCode
AND CType = 'H'
WHERE MCode IN (select MCode FROM string_split(MCode, ','))
Any ideas how can I output the correct data?
in case the sql fiddle link didnt work, I attached the DML , ddl
--table1
CREATE TABLE [dbo].[Leg](
[LegID] [bigint] NOT NULL,
[CarriCode] [varchar](3) NOT NULL,
[FNumber] [char](4) NOT NULL,
[MCode] [varchar](8) NOT NULL)
INSERT INTO [dbo].[Leg]
(
[LegID],
[CarriCode],
[FNumber],
[MCode]
)
VALUES
(1, 'AB', 2222, 'DJM_3R'),
(2, 'AC', 1222, 'DJM_5R'),
(3, 'AD', 1232, 'DJM_1R')
-- table2
CREATE TABLE [dbo].[Carri](
[CarriCode] [varchar](3) NOT NULL,
[CName] varchar(50) NOT NULL,
[CType] [char](1) NOT NULL
)
INSERT INTO [dbo].[Carri]
([CarriCode],
[CName],
[CType])
VALUES
( 'AB','AB Test', 'H'),
( 'AC','AC Test', 'L'),
( 'AD','AD Test', 'H')
-- table 3
CREATE TABLE [dbo].[EFTest](
[FCode] [varchar](20) NOT NULL,
[Desc] [varchar](max) NOT NULL,
[MCode] [varchar](max) NOT NULL,
)
INSERT INTO [dbo].[EFTest]
VALUES ('CODE', 'test', 'DJM_3R, DJM_2R, DJM_1R, AAABBB')
1条答案
按热度按时间gstyhher1#
To account for the spaces after each comma in
eftest.mcode
you need totrim
the result of string_split. Like this:The result:
(the third column can be omitted if unwanted in the result, it was helpful to debug the problem)
see: http://sqlfiddle.com/#!18/3d5805/1