SQL Server列表太长



我正在尝试运行以下SQL语句:

select * 
from table
where 1 = 1
and date >= '1/1/2020'
and id = any (**'list of 1300 items'**)
order by date asc;

问题是,我在第二个和语句中的列表实际上有1000多个表达式,所以它不允许我运行这个语句。有人知道更好的方法吗?基本上,我有一个ID,我想在我们的数据库中找到它,我知道最简单的方法是使用一个列表,但很明显我的列表太长了。我是这方面的新手,所以任何见解都将不胜感激!

有多种方法可以做到这一点。例如,如果您的SQL server版本不旧,则可以使用openJSON((。即:

DECLARE @ids VARCHAR(MAX) = '[1,3,34,434,43]' -- your 1300+ ids
select * 
from yourtable
where [date] >= '20200101'
and id IN (SELECT [value] FROM OPENJSON(@ids))
order by [date] asc;

如果您的SQL Server版本是2016或更高版本,则可以考虑string_split。感谢@Cetin Bazos的基本脚本。

DECLARE @ids NVARCHAR(MAX) = '1,3,34,434,43' -- your 1300+ ids
select * 
from yourtable
where [date] >= '20200101'
and id IN (SELECT [value] FROM STRING_SPLIT(@ids,','))
order by [date] asc;

最新更新