SQL: efficiently look up many IDs coming from outside the DB
I need to look up thousands of rows by ID, but the IDs come from outside the DB, so I can't get them from other tables like so:
SELECT * FROM some_table WHERE ID IN (
SELECT KnownID FROM some_other_table WHERE someCondition
)
Is there anything better than this:
SELECT * FROM some_table WHERE ID IN ('1001', '1002', '1003', ...)
Can I parametrize such a query where the number of id's isn't fixed? Or do I just end up concatenating a big string together each time?
(I'm using sqlite, btw, but I'm curious about other databases too.)
如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

评论(5)


SQL Server 2008 has a feature called Table Valued Parameters. See this article.

what format are your input IDs arriving in?
Are they manually typed in by a user?
in a text/csv/xml file?
pulled in from a service ?
If you get them in bulk, you could insert them into a #temp table and then select against your #temp table... e.g.
//PSEUDO CODE
foreach(string s in ListOfIdsFromFile)
{
//INSERT INTO #TempTable (ID) Values (ConvertToInt32(s))
}
Then
SELECT * FROM some_table a INNER JOIN #temp_table b ON a.ID = b.ID

(I'm using sqlite, btw, but I'm curious about other db's too.)
in sql server you could have a linked server and then just do a join between the two if it is on a different server. If it is on the same server but in different database then you would just do a regular join and add the dbname in from if the table and schema names
发布评论
需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。