简体   繁体   中英

Best way to join this into a temp table and inner join

Just wondering the best way to put this into a temp table and then join it.

 IF EXISTS(SELECT LocId
FROM dbo.Locations WITH (NOLOCK)
WHERE SourceSystem = @SourceSystem 
AND LocId IN (SELECT ListVal
FROM etopsuser.fnParseListToTable(@LocIdList, ';')) AND IsHot = 1)
BEGIN

Specifically trying to do it on this line of code

    (SELECT ListVal
FROM etopsuser.fnParseListToTable(@LocIdList, ';')) AND IsHot = 1)

The NOLOCK is unrelated

You would create a temporary table just like any other table from a select :

SELECT ListVal
INTO #templist
FROM etopsuser.fnParseListToTable(@LocIdList, ';');

Then you would use it as:

SELECT l.LocId
FROM dbo.Locations l JOIN
     #templist tl
     ON l.LocId = tl.Listval
WHERE l.SourceSystem = @SourceSystem AND l.IsHot = 1

The best way to pass a list into a procedure is to use a Table Valued Parameter

CREATE TYPE dbo.List AS TABLE (ListVal varchar(255));
IF EXISTS(SELECT 1
    FROM dbo.Locations l
    WHERE l.SourceSystem = @SourceSystem 
    AND l.LocId IN (
        SELECT ll.ListVal
        FROM @LocIdList ll
    ) AND IsHot = 1)

Notes: Always use table references on every column, especially if subqueries are involved. Never use NOLOCK unless you are prepared for incorrect results. EXISTS ignores its SELECT , so SELECT 1 or SELECT NULL is standard.

Then you can pass in the table variable either from client code depending on language, or in T-SQL like this

DECLARE @list dbo.List;
INSERT @list (ListVal)
VALUES ('SomeValue');

EXEC YourProc @LocIdList = @list;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM