我是SQL Server的新手,需要帮助编写查询
我收到了大约400个id号码,看起来像(123456、1234555、342345等(。我应该从具有这些ID的表中选择所有记录。问题是引用这些id的列(ActionIDreference(在其某些值(A123456、A1234555、A342345(前面有一个前缀(a(。有时它(ActionIDreference(没有"A"。我需要说明该列中引用这些特定id的任何变化。
我希望能够从列中提取这400个ID,无论它前面有A,或者如果没有A,那么就没有它。
表名称为ActionReport。
我正在使用Sql Server
希望问题清楚。
感谢的帮助
只需使用in
并涵盖所有可能性:
where ActionIDreference in ('123456', '1234555', '342345', '123456', 'A1234555', 'A342345')
任何其他方法都可能导致次优查询计划。是的,SQL Server可以处理IN
列表中的800个值,生成800个值应该不会比生成400个值困难多少。
您可以使用replace()
函数首先从所有ID中去掉"A",然后只与具有in
的ID列表进行比较。
select * fromActionReport
where replace(ActionIDreference,'A','')in (123456, 1234555, 342345 )
另一种方法可以是使用union all
和stuff()
select * fromActionReport
where ActionIDreference like 'A%' and STUFF(ActionIDreference,1,1,'') in (123456, 1234555, 342345 )
union all
select * fromActionReport
where ActionIDreference not like 'A%' ActionIDreference in (123456, 1234555, 342345 )
创建一个表来保存要搜索的ActionIDreference值。然后将400个ID插入其中。
create table search_criterion (ActionIDreference varchar(20));
insert into search_criterion values('123456'), ('1234555'), ('342345'), ('123456');
现在,您不知道表中哪些值的前缀为"A",因此您将复制所有行,然后重新插入前缀为"A"的表中。
insert into search_criterion select 'A'+ActionIDreference from search_criterion;
现在您的实际查询将是:
select * fromActionReport
where ActionIDreference in (select ActionIDreference from search_criterion );
尝试以下操作。创建一个临时表来保存您的id值
Create table #temp (Id varchar(10) not null primary key) /* data type should match the target table*/
插入您的价值清单
Insert into #temp values ('123456'),('345678'),...
用"A"更新您的表和前缀
update #temp set Id='A' + Id
现在重复您的第一次插入,这样您的表最终会包含带有和不带有"A"前缀的值列表。
现在使用临时表运行查询联接
select a.*
from #temp t
join fromActionReport a on a.ActionIDreference=t.Id
您可以加载带有id值和前缀为A
的id值的表变量。
DECLARE @table table(id varchar(10))
-- insert without prefix
insert into @table
SELECT cast(id as varchar(10)) as id FROM (VALUES ('12345'),('13345')) as t(id)
-- insert with prefix
insert into @table
SELECT cast(CONCAT('A',id) as varchar(10)) FROM @table
现在,您可以在主表中为表变量中的id应用IN条件
SELECT * FROM ActionReport where ActionReportIDReference IN
(
Select id from @table)