简体   繁体   English

SAS-在Proc Sql创建表中添加计算列/变量

[英]SAS - Add Computed Column/Variable in Proc Sql Create Table

In MS SQL Server it is possible to define compute column in create table statement, eg 在MS SQL Server中,可以在create table语句中定义计算列,例如

CREATE TABLE dbo.Products   
(  
    ProductID int
  , QtyAvailable smallint  
  , UnitPrice money  
  , InventoryValue AS QtyAvailable * UnitPrice  
);  

Is there an equivalent option available in SAS proc sql? SAS proc sql中有可用的等效选项吗?

The following throws syntax error: 以下引发语法错误:

proc sql;
CREATE TABLE work.Products   
( 
    ProductID num
    ,QtyAvailable num
    ,UnitPrice num format euro8.2 
  , InventoryValue AS QtyAvailable * UnitPrice  
);  
quit;

It is not possible to define computed columns on a physical table in SAS. 无法在SAS的物理表上定义计算列。 instead, one must create a physical base table for the data, and a view for the computed columns, eg as follows: 相反,必须为数据创建一个物理基表,并为计算列创建一个视图,例如,如下所示:

proc sql; 
create table work.products_base
( 
    ProductID num
    ,QtyAvailable num
    ,UnitPrice num format euro8.2 
);
CREATE view work.Products  as 
  select 
    ProductID 
    ,QtyAvailable 
    ,UnitPrice  
    ,QtyAvailable * UnitPrice as InventoryValue 
  from work.products_base;

insert into work.products
  set productid=1, qtyavailable=2,unitprice=3;  

Trying to add a value for InventoryValue throws a warning: 尝试为InventoryValue添加值会引发警告:

169    set productid=1, qtyavailable=2,unitprice=3, inventoryvalue=4;
WARNING: Cannot provide InventoryValue with a value because it references a derived 
column that can't be inserted into.

Another approach is to use a constraint, which means one physical table, but it does require the developer to ensure the correct value is actually loaded into it (so it's not computed and takes up physical disk space). 另一种方法是使用约束,这意味着一个物理表,但它确实要求开发人员确保将正确的值实际加载到其中(因此,不会计算出该值并占用物理磁盘空间)。

proc sql; drop table work.products;
create table work.products_base
( 
    ProductID num
    ,QtyAvailable num
    ,UnitPrice num format euro8.2 
    ,InventoryValue num
    ,constraint InventoryValue check(InventoryValue = QtyAvailable * UnitPrice)
);
insert into work.products_base set qtyavailable=2,unitprice=2,inventoryvalue=4;
insert into work.products_base set qtyavailable=2,unitprice=2,inventoryvalue=2;

The second insert statement throws an error: 第二条插入语句引发错误:

ERROR: Add/Update failed for data set WORK.PRODUCTS_BASE because data value(s) do not comply
       with integrity constraint InventoryValue.

Of course - if you are actually creating your table in SQL Server then you could use pass through syntax to create your computed column.. 当然-如果您实际上是在SQL Server中创建表,则可以使用传递语法来创建计算列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM