【问题标题】:SAS insert value with proc sqlSAS使用proc sql插入值
【发布时间】:2017-07-11 15:54:24
【问题描述】:

所以我有一个相当有趣的问题。我正在尝试以特定格式和样式插入当前日期,但由于某种原因它似乎失败了。我知道这不是格式问题......但我知道如何解决它。数据步骤解决方案也受到欢迎......这就是有效的方法。

proc sql;
create table work.test
(test_Id char(50), test_Name char(50), cur_Mo char(1), cur_Qtr char(1), entered_Date char(8));
insert into work.test 
values('201703','2017 Mar','0','0','24APR17')
values('201704','2017 Apr','0','0','24APR17')
values('201706','2017 Jun','1','0','23JUN17');
quit;

以下是没有的:

proc sql;
    insert into work.test 
    values(catx('',put(year(today()),4.),case when month(today())< 10 then catx('','0',put(month(today()),2.)) else put(month(today()),2.)end) ,catx(' ',[put(year(today()),4.),put(today(),monname3.))],'1','0',put(today(),date7.));
quit;

【问题讨论】:

  • 您不能将函数放在 VALUES 子句中。只是实际值。
  • 我认为会是这样,还有其他方法吗?

标签: sas proc-sql


【解决方案1】:

您可以使用 %SYSFUNC() 宏函数在宏代码中调用大多数其他 SAS 函数。因此,要以 DATE7 格式生成今天的日期,您可以使用:

insert into work.test (date)
  values("%sysfunc(date(),date7)")
;

【讨论】:

  • 我确实有一个跟进 - 我如何结合月份和日期以便它遵循:201701,201702 等等?
  • SAS 有很多日期格式。 YYMMN6 会生成 YYYYMM 格式的日期字符串。
  • 在我的情况下,我的解决方案是在插入语句中使用它:values("%sysfunc(date(),yymmn6.)","%sysfunc(date(),yymon7.)",'1','0',"%sysfunc(date(),date7.)"); 现在这符合我当前问题的要求。谢谢
【解决方案2】:

我可能会这样做的方式是使用数据步骤来制作要插入的数据集,然后插入该数据集。

您可以在 SAS 中使用insert into (...) select (...) from (...) 语法,并且数据步骤更加灵活,允许您定义列。

例如:

proc sql;
  create table class like sashelp.class;
quit;

proc sql;
   insert into class
     select * from sashelp.class;
quit;

或者您可以只指定某些变量:

proc sql;
    insert into class (name, age)
      select name, age from sashelp.class;
quit;



data to_insert;
  name= 'Wilma';
  sex = 'F';
  age = 29;
  height = 61.2;
  weight = 95.3;
run;

proc sql;
  insert into class
    select * from to_insert;
quit;

只需确保您明确列出要插入/选择的变量,或者您的顺序完全正确(如果您像我上面那样使用*,它会按位置匹配)。

【讨论】:

  • 感谢您的建议,如果变量之一涉及日期函数怎么办?我也会试试这个!谢谢!
  • 在数据步骤中这不是问题;日期函数应该在数据步骤中解析(即,不要插入文本“today()”,但 age=today()-birthdate; 应该没问题,因为它在数据步骤中进行计算)。
  • 如果您使用SELECT 从表中插入数据,而不是使用VALUES 的常量,那么您可以使用函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-24
  • 1970-01-01
  • 2023-04-08
  • 2017-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多