嗨,我在下面有一個查詢。我在多個地方使用此查詢,但此查詢幾乎相同。只有在條件改變的地方。
這是我的查詢
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
我怎樣才能避免這種情況。如何防止重復并提高查詢性能。
uj5u.com熱心網友回復:
創建一個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
uj5u.com熱心網友回復:
您可以使用行內表值函式。這就像一個引數化視圖(并且表現得一樣好,如果不是更好的話)
CREATE OR ALTER FUNCTION GetCustomer
(
@place varchar(100),
@fromCreateDate datetim
)
RETURNS TABLE AS RETURN
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 = @place
and c.create_date > @fromCreateDate;
GO
你會像這樣使用它
SELECT *
FROM GetCustomer( 'london', DATEADD(day, -100, getdate()) ) c
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/351711.html
標籤:sql sql-server 查询语句
上一篇:SQL將重復項轉換為一行
