MACRO to create a table in SQL

江枫思渺然 提交于 2019-12-11 05:21:55

问题


Hi everyone thanks so much for taking the time to read this.

I'd like to create a macro in Teradata that will create a table from another table based on specific parameters.

My original table consists of three columns patient_id, diagnosis_code and Date_of_birth ......

I'd like to build a macro that would allow me to specify a diagnosis code and it would then build the table consisting of data of all patients with that diagnosis code.

My current code looks like this

Create Macro All_pats (diag char) as (
create table pats as(
select *
from original_table 
where diag = :diagnosis_code;)
with data primary index (patid); 

I cant seem to get this to work - any tips?

Thanks once again


回答1:


Your code has a semicolon in a wrong place and a missing closing bracket:

Create Macro All_pats (diag char) as (
  create table pats as
   (
    select *
    from original_table 
    where diag = :diagnosis_code
   ) with data primary index (patid);
);

Edit:

Passing multiple values as a delimited list is more complicated (unless you use Dynamic SQL in a Stored Procedure):

REPLACE MACRO All_lpats (diagnosis_codes VARCHAR( 1000)) AS
(
  CREATE TABLE pats AS
   (
     SELECT *
     FROM original_table AS t
     JOIN TABLE (StrTok_Split_To_Table(1, :diagnosis_codes, ',')
                 RETURNS (outkey INTEGER,
                          tokennum INTEGER,
                          token VARCHAR(20) CHARACTER SET Unicode)
                ) AS dt
     ON t.diag = dt.token
   ) WITH DATA PRIMARY INDEX (patid);
);

EXEC All_lpats('111,112,113');

As the name implies StrTok_Split_To_Table splits a delimited string into a table. You might need to adust the delimiter and the length of the resulting token.



来源:https://stackoverflow.com/questions/44574915/macro-to-create-a-table-in-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!