【问题标题】:If condition in SQL file verticaSQL文件vertica中的if条件
【发布时间】:2017-11-03 04:25:12
【问题描述】:

我需要为大约 10 个表执行插入,在插入之前我必须检查一个条件,每个表的条件都保持不变,而不是在插入查询中给出那个条件,我希望我可以给出 if 条件(选择查询),如果满足则执行插入语句,有没有办法在 Vertica SQL 文件中给出 if 条件?如果条件不满足,我不想执行任何插入查询。

【问题讨论】:

    标签: sql vertica


    【解决方案1】:

    如果条件是,例如,您只在星期天插入数据,试试这个:

    a) 一个测试表:

        CREATE LOCAL TEMPORARY TABLE input(id,name)
        ON COMMIT PRESERVE ROWS AS
                  SELECT 42,'Arthur Dent'
        UNION ALL SELECT 43,'Ford Prefect'
        UNION ALL SELECT 44,'Tricia McMillan'
        KSAFE 0;
    

    从此表中选择带有WHERE 条件的选择,以测试是否是星期天——仅此而已,请参见此处:

        SELECT
          *
        FROM input
        WHERE TRIM(TO_CHAR(CURRENT_DATE,'Day'))='Sunday'
        ;
    
        id|name
        42|Arthur Dent
        43|Ford Prefect
        44|Tricia McMillan
    

    使用不同的工作日值(我在星期天写这篇文章......),你会得到这个:

        SELECT
          *
        FROM input
        WHERE TRIM(TO_CHAR(CURRENT_DATE,'Day'))='Monday'
        ;
    
        id|name
        select succeeded; 0 rows fetched
    

    我在 SQL 生成 SQL 中使用这种技术来创建一个脚本或一个确定环境的空文件,然后调用该脚本(完整或空),以这种方式实现条件 SQL 执行....

    【讨论】:

      【解决方案2】:

      我知道这是一篇旧帖子,但我想分享一下我最近解决的问题。

      我需要根据某些条件在一个或另一个表中插入。您首先应该有一个字段或值,这将是您的搜索条件。

      create table tmp1 (
          Col1        int null
          ,Col2       varchar(100) null
      )
      
      --Insert values
      insert into tmp (Col1,Col2) Values
          (1,'Text1')
          ,(2,'Text2')
      
      --Insert into table001
      insert into table001
      select
          t.field1
          ,t.field2
          ,......
      from table1 t
      inner join tmp t2
          on t2.col1 = t.ColX
      where 1 = case when t2.Col2 = 'Text1' then 1 else 0 end --Search condition; if 1<>0 then it doesn't do anything; otherwise insert.
      
      --Insert into table002
      insert into table002
      select
          t.field1
          ,t.field2
          ,......
      from table2 t
      inner join tmp t2
          on t2.col1 = t.ColX
      where 1 = case when t2.Col2 = 'Text2' then 1 else 0 end --Search condition; if 1<>0 then it doesn't do anything; otherwise insert.
      

      如果是同一个工作表,也可以基于此使用 UNION/UNION ALL。

      问候!

      【讨论】:

        猜你喜欢
        • 2016-02-07
        • 1970-01-01
        • 2017-06-16
        • 2016-04-09
        • 2021-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-24
        相关资源
        最近更新 更多