TSQL Query that loops through table with Where Clause Variable

Hello Experts,

I want to write a TSQL query that will search my database for all instances of a serial number based on a variable in the WHERE clause.  I want the variable to be acquired from a value populated in a column from a table with thousands of rows.  The SELECT statement would need to loop through each row of the table holding the serial number value, search the database for each, and write the results into a temp table.  I am having difficulty with the logic for the loop.  Pseudo code (so far) looks like this:

DECLARE @serial as varchar

SET @serial = (Some logic acquired by searching a table with a column named SerialNum)

SELECT * FROM (some Joined tables)

INTO SomeTempTable      

WHERE somejoinedtable.SerialNum = @serial

Loop through this procedure until all SerialNumbers have been searched
Who is Participating?
Scott PletcherConnect With a Mentor Senior DBACommented:
I'd still suggest what I suggested before:

Insert all the serialnumbers into a keyed table, and do a join to that table to do the lookup on the main table.

Looking up one serial number at a time for several thousand serial numbers would naturally take a long time.
SharathData EngineerCommented:
It would be better to explain this with some sample data and expected result.
Scott PletcherSenior DBACommented:
You should loop thru the part that generates the @serial numbers to search for, then do a single read to the db tables to get all the search numbers.

For example:

CREATE TABLE #serialNums (
    serialNum varchar(...) PRIMARY KEY

INSERT INTO #serialNums ( serialNum )
SELECT (Some logic acquired by searching a table with a column named SerialNum)

INTO SomeTempTable
FROM (some Joined tables) sjt
INNER JOIN #serialNums s ON
    s.serialNum = somejoinedtable.SerialNum
ccgmikeTAuthor Commented:
I agree Scott, but I'm having difficulty with the logic syntax.  What I have been doing is running a query for all serial numbers for a given period and then pasting them into the where clause as shown below.  I want to design the logic so that a sub (or parent) query would replace the need for me to do this.

Select * from some tables


ass.serialnumber = '2D8HN44E39R' or
ass.serialnumber = '5N1BV28UXXX' or
ass.serialnumber = '1TKC024221B1' or
ass.serialnumber = '1G2NE52T5WC' or
ass.serialnumber = '1FTRW08L11K' or ..........  and this list continues for several thousand numbers
ass.serialnumber = '1HD1FB4189Y641721' or
ass.serialnumber = '1FTPW14574KC43694' or
ass.serialnumber = '4TARN01P7PZ134784' or
ccgmikeTAuthor Commented:
Thank you Scott, I ran this approach past some of my peers and they all agree with you.


Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.