I have an SQL table including two columns depicting a range of IDs; those ranges needs to be compared with a cell under a particular ID column in a second table – if it is within the range, inclusively, the row of the second table will be included in the return.
Edit: The ranges available are limited by a range of user-supplied dates.
I’m only familiar with the basics of SQL; before I start researching loops and predefined tabular functions, does anyone have any suggestions?
SELECT * FROM [ADataBase].[dbo].[AFirstTable]
WHERE [ALongIDNumber] <=
(SELECT [StartOfIDRange] FROM [DHL].[dbo].[ASecondTable]
WHERE [date] BETWEEN '2010-01-21' AND '2010-01-22')
AND [ALongIDNumber] >=
(SELECT [EndOfIDRange] FROM [DHL].[dbo].[ASecondTable]
WHERE [date] BETWEEN '2010-01-21' AND '2010-01-22')
Currently, this returns the error
Msg 512, Level 16, State 1, Line 2
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Which I’m guessing is causing it to fluff up because there’s several rows returned by the selects.
I’ve researched, and come across a similar question of which the only answers are for fixed number of ranges. Because I query a table for the ranges, the number of ranges will change.
Due to the nature of this scenario, modifying the databases is a last resort.
Thanks for your help!
I’m really unclear from your narrative, but I think that what you might be looking for is the concept of a Join:
This will find rows in
firstthat fit into any range of ID values that occurs as a single row insecond. This does mean that if there are overlapping ranges of ID values in second, you might receive multiple rows in the result set, for a single original row infirst.Don’t. Although there are some crude ways to perform looping in SQL, you really shouldn’t go there. The idea behind SQL is you describe what result you want, and the SQL engine works out the best way to achieve that (whether that be, behind the scenes, looping, creating hash tables, spilling items to disk, etc).