首页 > 解决方案 > 如何避免重复相同的查询?

问题描述

嗨,我在下面有一个查询。我在多个地方使用此查询,但此查询几乎相同。只有在条件发生变化的情况下。

这是我的查询

select
c.first_name,
c.middle_name,
c.last_name,
c.birth_day,
c.birth_month,
c.birth_year,
c.marital_status,
c.education_status,
c.departmant,
c.create_date,
c.create_user,
c.modify_date,
c.modify_user
from customer c 
where c.place='london' and c.create_date>getdate()-100

我在多个地方使用相同的查询,但只在条件发生变化的地方使用。所以我到处重复下面的部分。

select
c.first_name,
c.middle_name,
c.last_name,
c.birth_day,
c.birth_month,
c.birth_year,
c.marital_status,
c.education_status,
c.departmant,
c.create_date,
c.create_user,
c.modify_date,
c.modify_user
from customer c 

我怎样才能避免这种情况。如何防止重复并提高查询性能。

标签: sqlsql-servertsql

解决方案


创建一个VIEW以重用基本 SELECT,例如

create view vCustomer
as
select
c.first_name,
c.middle_name,
c.last_name,
c.birth_day,
c.birth_month,
c.birth_year,
c.marital_status,
c.education_status,
c.departmant,
c.create_date,
c.create_user,
c.modify_date,
c.modify_user
from customer c 

然后你可以运行如下查询:

select * 
from vCustomer c 
where c.place='london' 
  and c.create_date>getdate()-100

推荐阅读