How can I convert "in" to inner join in case:
SELECT
m.*,
atypcode_type = CASE
WHEN m.[ATYPCODE] IS NOT NULL
AND m.[ATYPCODE] IN (SELECT lastlevel
FROM [dbo].[tbl2]
WHERE ','+'2921'+',' LIKE '%,' + CAST([ParentId] AS VARCHAR(10)) + ',%')
THEN 100
WHEN m.[ATYPCODE] IS NOT NULL
AND m.[ATYPCODE] IN (SELECT lastlevel
FROM [dbo].[tbl2]
WHERE ',' + '3366' + ',' LIKE '%,' + CAST([ParentId] AS VARCHAR(10)) + ',%')
THEN 101
....
END
FROM
[tbl1] m
INNER JOIN
[tbl2] ncg ON m.ATYPCODE = ncg.lastlevel
How can I convert this code
m.[ATYPCODE] IN (SELECT lastlevel FROM [dbo].[tbl2]
WHERE ','+'2921'+',' like '%,'+cast([ParentId] AS varchar(10))+',%')
to an inner join?
Result is :
atypcode acurrcode tarikh atypcode_type
2741 IRR 1397/06/31 109
2941 IRR 1397/06/31 109
3371 IRR 1397/06/31 101
3381 IRR 1397/06/31 101
3671 IRR 1397/06/31 101
3381 IRR 1397/06/31 101
4371 IRR 1397/06/31 101
3971 IRR 1397/06/31 101
3571 IRR 1397/06/31 101
3771 IRR 1397/06/31 101
Create col atypcode_type
with case, but this code it's too slow
This answers the question that you have asked:
SELECT m.*,
(CASE WHEN m.[ATYPCODE] IS NOT NULL AND
t2_2921.lastlevel IS NOT NULL
THEN 100
WHEN m.[ATYPCODE] IS NOT NULL AND
t2_3366.lastlevel IS NOT NULL
THEN 101
....
END) as atypcode_type
FROM [tbl1] m INNER JOIN
[tbl2] ncg
ON m.ATYPCODE = ncg.lastlevel LEFT JOIN
tbl2 t2_2921
ON m.ATYPCODE = t2_2921.lastlevel AND
',' + '2921' + ',' LIKE '%,' + CAST(?.ParentId AS VARCHAR(10)) + ',%') LEFT JOIN
tbl2 t2_3366
ON m.ATYPCODE = t2_3366.lastlevel AND
',' + '3366' + ',' LIKE '%,' + CAST(?.ParentId AS VARCHAR(10)) + ',%')
It does make the assumption that your delimited list has no duplicates.
The ?
is for the table alias to identify where ParentId
comes from.
I have a few editorial comments. First, I find it hard to imagine that this code does anything useful. It seems to be mixing levels and parents in a rather convoluted way. You haven't explained your data structure so this might be what you want.
Second, there is no performance gain from this. You don't specify why you want to switch to a JOIN
. If that is the reason why, this has little benefit.
And that is related to the third reason. Do not store multiple values as comma-delimited lists. That is not the SQL way to store data. Relational databases have this great data structure to store lists. It is called a table , not a string .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.