替换VIEW定义中的文本

时间:2019-05-22 07:09:02

标签: sql sql-server tsql sql-server-2008-r2 ssms

我有以下VIEW定义:

create view v_1
as
select * from t1
where [date] between '2010-01-01' and '2019-01-01'
union all
select * from t2
where [date] between '2012-01-01' and '2019-01-01'
union all
select * from t3
where [date] between '2013-01-01' and '2019-01-01'
union all
select * from t4
where [date] between '2014-01-01' and '2019-01-01'

方案1:想要删除(或替换为空字符串)table t1 select语句。

视图应如下所示:

create view v_1
as
select * from t2
where [date] between '2012-01-01' and '2019-01-01'
union all
select * from t3
where [date] between '2013-01-01' and '2019-01-01'
union all
select * from t4
where [date] between '2014-01-01' and '2019-01-01'  

方案2:要删除table t4 select语句。

视图应如下所示:

create view v_1
as
select * from t1
where [date] between '2010-01-01' and '2019-01-01'
union all
select * from t2
where [date] between '2012-01-01' and '2019-01-01'
union all
select * from t3
where [date] between '2013-01-01' and '2019-01-01'

注意:根据要求,可能要从VIEW定义中删除所有select语句。

3 个答案:

答案 0 :(得分:3)

代替视图,创建内联表功能也称为带有参数的视图。例如:

create function v_1
(   
    @HasQuery1 BIT
   ,@HasQuery2 BIT
   ,@HasQuery3 BIT
   ,@HasQuery4 BIT
)
RETURNS TABLE
as
RETURN
(
select * from t1
where [date] between '2010-01-01' and '2019-01-01'
    AND @HasQuery1  = 1
union all
select * from t2
where [date] between '2012-01-01' and '2019-01-01'
    AND  @HasQuery2  = 1
union all
select * from t3
where [date] between '2013-01-01' and '2019-01-01'
    AND  @HasQuery3  = 1
union all
select * from t4
where [date] between '2014-01-01' and '2019-01-01'
    AND  @HasQuery4  = 1
)

您可以在类似视图的联接中使用该函数,但是可以传递要返回的数据。 例如:

SELECT *
FROM T1 A
INNER JOIN V_1(1, 0, 0, 1) B
   ON ....

答案 1 :(得分:0)

SQL服务器使您可以在编辑器中使用正则表达式作为搜索模式,因此您要做的就是:

  1. 按Ctrl + F

  2. 使用正则表达式启用

  3. 使用搜索模式select.+from t1(.*\n)+?select,其中t1可以用任何表名替换

  4. 使用select

  5. 作为替换模式

请参见下面的屏幕(更换后):

enter image description here

答案 2 :(得分:0)

我喜欢@gotqn的答案,但是,如果必须是视图,我会这样做:

--Sample Tables:
CREATE TABLE dbo.t1(id INT IDENTITY PRIMARY KEY, col1 INT);
CREATE TABLE dbo.t2(id INT IDENTITY PRIMARY KEY, col1 INT);
CREATE TABLE dbo.t3(id INT IDENTITY PRIMARY KEY, col1 INT);
CREATE TABLE dbo.t4(id INT IDENTITY PRIMARY KEY, col1 INT);

INSERT dbo.t1(col1) VALUES (10),(20),(30);
INSERT dbo.t2(col1) VALUES (60),(620),(630);
INSERT dbo.t3(col1) VALUES (0);
INSERT dbo.t4(col1) VALUES (0);
GO

--Solution
CREATE VIEW dbo.yourView AS
  SELECT t.*,show = 1 FROM dbo.t1 AS t UNION ALL
  SELECT t.*,show = 2 FROM dbo.t2 AS t UNION ALL
  SELECT t.*,show = 3 FROM dbo.t3 AS t UNION ALL
  SELECT t.*,show = 4 FROM dbo.t4 AS t
GO

这里的好处是优化器足够聪明,可以完全忽略并避免触摸最终结果集中未包含的数据的表。

请注意以下查询和执行计划:

SELECT v.* FROM dbo.yourView AS v;
SELECT v.* FROM dbo.yourView AS v WHERE v.show = 1;
SELECT v.* FROM dbo.yourView AS v WHERE v.show IN (1,3);
SELECT v.* FROM dbo.yourView AS v WHERE v.show <> 1;

enter image description here

相关问题