Published on :
ETL INTERNAL_CREATION

Create a View with Two Tables

This code is also available in: Deutsch Español Français
Awaiting validation
The objective is to demonstrate how the `table.view` action from the 'table' action set can be used to create a logical view from two in-memory CAS tables. The example loads a 'cars.csv' dataset, creates a summary table 'cars_summary' via FedSQL, then combines these two tables into a view named 'cars_view'. Options such as `replace=True` and the use of prefixes for joined columns (`f1_`, `d1_`) are also illustrated. Finally, view information is displayed via `table.tableInfo` and the first rows are extracted with `table.fetch`, including computed variables. Additional examples explore the creation of basic views, the application of filters and computed columns, the integration of categorized data, and error handling during view creation.
Data Analysis

Type : INTERNAL_CREATION


Examples use CSV data loaded from a support.sas.com URL, then aggregated or directly used for creating temporary in-memory CAS tables, as well as data generated via `datalines`.

1 Code Block
DATA STEP / table.view Data
Explanation :
This example creates two small in-memory CAS tables using DATA steps and `datalines`. It then uses the `table.view` action to create a view named `simple_view` by joining `table1` and `table2` on the `ID` column. The aliases `t1` and `t2` are used to prefix columns in the view. Finally, it displays the view's information and first rows.
Copied!
1/* Exemple 1 : Utilisation Basique */
2/* Crée deux tables CAS simples et une vue qui les joint. */
3 
4/* Assurez-vous d'avoir une session CAS active */
5options cashost="cloud.example.com" casport=5570;
6cas casauto;
7 
8/* Création de la première table (fictif) */
9DATA casuser.table1(promote=yes);
10 INPUT ID $ Name $;
11 DATALINES;
12 101 Alice
13 102 Bob
14 103 Charlie
15 ;
16RUN;
17 
18/* Création de la deuxième table (fictif) */
19DATA casuser.table2(promote=yes);
20 INPUT ID $ Score;
21 DATALINES;
22 101 85
23 102 92
24 104 78
25 ;
26RUN;
27 
28/* Création de la vue en joignant les deux tables */
29PROC CAS;
30 TABLE.view /
31 name="simple_view",
32 replace=True,
33 tables={
34 {name="table1", as="t1"},
35 {name="table2", as="t2", keys="t1_ID=t2_ID"}
36 };
37RUN;
38 
39/* Affichage des informations de la vue */
40PROC CAS;
41 TABLE.tableInfo / TABLE="simple_view";
42RUN;
43 
44/* Affichage des premières lignes de la vue */
45PROC CAS;
46 TABLE.fetch /
47 TABLE="simple_view",
48 to=5;
49RUN;
50 
2 Code Block
DATA STEP / table.view Data
Explanation :
This example extends the basic case by adding filtering (`where='t2_Score > 80'`) to include only rows where the score is greater than 80. It also introduces a computed column `FullInfo` using `computedVarsProgram` which concatenates name and score information. The `table.fetch` command then selects specific variables, including the computed variable.
Copied!
1/* Exemple 2 : Options Courantes (Filtrage et sélection de colonnes) */
2/* Utilise les tables de l'exemple 1 et crée une vue filtrée avec des colonnes spécifiques. */
3 
4/* Assurez-vous d'avoir une session CAS active */
5options cashost="cloud.example.com" casport=5570;
6cas casauto;
7 
8/* Création de la première table (fictif) */
9DATA casuser.table1(promote=yes);
10 INPUT ID $ Name $;
11 DATALINES;
12 101 Alice
13 102 Bob
14 103 Charlie
15 104 David
16 ;
17RUN;
18 
19/* Création de la deuxième table (fictif) */
20DATA casuser.table2(promote=yes);
21 INPUT ID $ Score;
22 DATALINES;
23 101 85
24 102 92
25 103 78
26 104 65
27 ;
28RUN;
29 
30/* Création de la vue avec un filtre et sélection de colonnes */
31PROC CAS;
32 TABLE.view /
33 name="filtered_view",
34 replace=True,
35 tables={
36 {name="table1", as="t1"},
37 {name="table2", as="t2", keys="t1_ID=t2_ID"}
38 },
39 where="t2_Score > 80",
40 computedVarsProgram="FullInfo = t1_Name || ' (Score: ' || strip(put(t2_Score, 3.)) || ')'",
41 computedVars={"FullInfo"}
42 ;
43RUN;
44 
45/* Affichage des informations de la vue */
46PROC CAS;
47 TABLE.tableInfo / TABLE="filtered_view";
48RUN;
49 
50/* Affichage des premières lignes de la vue avec les colonnes sélectionnées */
51PROC CAS;
52 TABLE.fetch /
53 TABLE="filtered_view",
54 fetchVars={"t1_ID", "t1_Name", "t2_Score", "FullInfo"},
55 to=5;
56RUN;
3 Code Block
PROC HTTP / PROC CAS / FedSQL
Explanation :
This example loads the 'cars.csv' dataset. It then creates an aggregated table `cars_summary_with_category` using `fedSql.execDirect`. This table aggregates data by `drivetrain` and a dynamically derived `Weight_Category` via a SQL `CASE` statement. The `advanced_cars_view` is then created by joining `cars_raw` and this new aggregated table on the `Drivetrain` column. A computed column `FullCarInfo` is added to combine multiple textual information.
Copied!
1/* Exemple 3 : Cas Avancé (Table dérivée avec catégorie de poids et jointure) */
2/* Charge le jeu de données Cars, crée une table agrégée avec une catégorie de poids, puis une vue. */
3 
4/* Assurez-vous d'avoir une session CAS active */
5options cashost="cloud.example.com" casport=5570;
6cas casauto;
7 
8/* Téléchargement et chargement du fichier CSV cars.csv */
9%let DATA='http://support.sas.com/documentation/onlinedoc/viya/exampledatasets/cars.csv';
10filename t temp;
11PROC HTTP method="get" url=&DATA. out=t;
12RUN;
13%let temppath = %sysfunc(quote(%sysfunc(pathname(t))));
14 
15PROC CAS;
16 upload path=&temppath.
17 importoptions={
18 fileType="csv",
19 getNames=True
20 },
21 casout={
22 name="cars_raw",
23 replace=True
24 };
25RUN;
26 
27/* Création d'une table agrégée avec une catégorie de poids dérivée */
28PROC CAS;
29 fedSql.execDirect /
30 query="create table cars_summary_with_category{options replace=True} as
31 select
32 drivetrain,
33 (case
34 when weight <= 1500 then 'Light'
35 when weight > 1500 and weight <= 3000 then 'Medium'
36 else 'Heavy'
37 end) as Weight_Category,
38 avg(mpg_city) as Avg_MPG_City
39 from cars_raw
40 group by drivetrain, Weight_Category;";
41RUN;
42 
43/* Création de la vue en joignant cars_raw et cars_summary_with_category */
44PROC CAS;
45 TABLE.view /
46 name="advanced_cars_view",
47 replace=True,
48 tables={
49 {name="cars_raw", as="r1"},
50 {name="cars_summary_with_category", as="s1", keys="r1_Drivetrain=s1_Drivetrain"}
51 },
52 computedVarsProgram="FullCarInfo = r1_Make || ' - ' || r1_Model || ' (' || s1_Weight_Category || ')';"
53 ;
54RUN;
55 
56/* Affichage des informations de la vue */
57PROC CAS;
58 TABLE.tableInfo / TABLE="advanced_cars_view";
59RUN;
60 
61/* Affichage des premières lignes de la vue */
62PROC CAS;
63 TABLE.fetch /
64 TABLE="advanced_cars_view",
65 fetchVars={"FullCarInfo", "r1_Drivetrain", "r1_Weight", "s1_Weight_Category", "s1_Avg_MPG_City"},
66 to=5;
67RUN;
68 
4 Code Block
DATA STEP / table.view Data
Explanation :
This example creates a simple `existing_table`. It then deliberately attempts to create a view (`error_view`) by joining `existing_table` with a `non_existent_table`. Since `non_existent_table` does not exist, the `table.view` action will fail, thus demonstrating an error scenario. Errors will be logged in the SAS/CAS log. The subsequent attempt to access `error_view` with `table.tableInfo` will also result in an error, confirming that the view was not created. The `existing_table` is then dropped.
Copied!
1/* Exemple 4 : Intégration Viya (Gestion d'erreur lors de la création de vue) */
2/* Tente de créer une vue avec une table inexistante et capture l'erreur. */
3 
4/* Assurez-vous d'avoir une session CAS active */
5options cashost="cloud.example.com" casport=5570;
6cas casauto;
7 
8/* Création d'une table valide pour la démonstration */
9DATA casuser.existing_table(promote=yes);
10 INPUT ID $ Value;
11 DATALINES;
12 A 10
13 B 20
14 C 30
15 ;
16RUN;
17 
18/* Tentative de création d'une vue avec une table inexistante */
19/* La vue ne sera pas créée, et une erreur sera loguée. */
20PROC CAS;
21 /* La commande 'table.view' générera une erreur si 'non_existent_table' n'existe pas. */
22 /* Dans un programme CASL plus robuste, un bloc try/catch serait utilisé. */
23 /* Pour cet exemple, l'erreur sera visible dans le log SAS/CAS. */
24 TABLE.view /
25 name="error_view",
26 replace=True,
27 tables={
28 {name="existing_table", as="e1"},
29 {name="non_existent_table", as="n1", keys="e1_ID=n1_ID"} /* Cette table n'existe pas */
30 };
31RUN; QUIT; /* La vue ne sera pas créée. */
32 
33/* Tenter d'afficher des informations sur la vue inexistante (cela générera aussi une erreur) */
34PROC CAS;
35 TABLE.tableInfo / TABLE="error_view";
36RUN; QUIT;
37 
38/* Nettoyage: suppression de la table existante */
39PROC CAS;
40 TABLE.dropTable / caslib="casuser" name="existing_table";
41RUN;
This material is provided "as is" by We Are Cas. There are no warranties, expressed or implied, as to merchantability or fitness for a particular purpose regarding the materials or code contained herein. We Are Cas is not responsible for errors in this material as it now exists or will exist, nor does We Are Cas provide technical support for it.
Copyright Info : Copyright © SAS Institute Inc. All Rights Reserved