2017-08-14 102 views
0

我还是新来的SAS和DB2。我有一个DB2 Table,其中有一列存储编码为时间戳的值。我试图从我的工作目录中的SAS数据集将数据加载到此列上。然而,这些时间戳中的一些对应于01-01-1582之前的日期,并且不能将其作为日期时间值存储在SAS中。它们被存储为字符串。插入到DB2 FOM SAS数据集直通SQL

这意味着如果我想要将这些值加载到DB2表中,我必须首先将它们转换为TIMESTAMP()DB2函数的时间戳,据我所知,该函数需要通过SQL执行一条execute语句(如与SAS ACCESS libname方法相反)。例如,为了写一个值我做到以下几点:

PROC SQL; 
    connect to db2 (user = xxxx database = xxxx password = xxxx); 
    execute (insert into xxxx.xxxx (var) values (TIMESTAMP('0001-01-01-00.00.00.000000'))) by db2; 
    disconnect from db2; 
quit; 

我怎样才能做到这一点在源数据集合的所有值? execute命令中的select ... from语句不起作用,因为据我所知我无法从DB2连接中引用SAS Work目录。

最终我能写,执行上面的PROC SQL块宏并从每个观测数据的步骤中调用它,但我不知道是否有这样做的更简单的方法。更改变量的类型不是一种选择。

在此先感谢。

回答

1

周围工作的令人费解的方式是使用call execute

data _null_; 
set sas_table; 
call execute("PROC SQL; 
       connect to db2 (user = xxxx database = xxxx password = xxxx); 
       execute (
       insert into xxxx.xxxx (var) 
       values (TIMESTAMP('"||strip(dt_string)||"')) 
       ) by db2; 
       disconnect from db2; 
       quit;"); 
run; 

哪里sas_table是包含作为字符串存储在一个名为dt_string变量datetime值的SAS数据集。

这里会发生什么事是,对于数据集中的每个观测,SAS将执行与dt_string当前值每次execute调用程序的参数。

使用宏,而不是调用执行基本上做同样的事情的另一种方法:

%macro insert_timestamp; 
    %let refid = %sysfunc(open(sas_table)); 
    %let refrc = %sysfunc(fetch(&refid.)); 
    %do %while(not &refrc.); 
    %let var = %sysfunc(getvarc(&refid.,%sysfunc(varnum(&refid.,dt_string)))); 

    PROC SQL; 
     connect to db2 (user = xxxx database = xxxx password = xxxx); 
     execute (insert into xxxx.xxxx (var) values (TIMESTAMP(%str(%')&var.%str(%')))) by db2; 
    disconnect from db2; 
    quit; 

    %let refrc = %sysfunc(fetch(&refid.)); 
    %end; 
    %let refid = %sysfunc(close(&refid.)); 
%mend; 
%insert_timestamp; 

编辑:我猜你也可以按原样使用SAS/ACCESS装入表中DB2,然后再转换用sql传递时间戳的字符串。喜欢的东西

libname lib db2 database=xxxx schema=xxxx user=xxxx password=xxxx; 
data lib.temp; 
set sas_table; 
run; 
PROC SQL; 
    connect to db2 (user = xxxx database = xxxx password = xxxx); 
    execute (create table xxxx.xxxx (var TIMESTAMP)) by db2; 
    execute (insert into xxxx.xxxx select TIMESTAMP(dt_string) from xxxx.temp) by db2; 
    execute (drop table xxxx.temp) by db2; 
    disconnect from db2; 
quit; 
+0

您好,感谢的快速答复。当我谈到通过数据步骤调用proc sql时,这也是我的想法。我不知道,但:为什么要使用“”在TIMESTAMP()调用 –

+1

欢迎你,如果你的问题涉及到单或双引号我不能告诉如果单打,那么,在你的代码,时间戳值括?。在单引号中;所以这里的单引号是这样的:dt_string的解析值也被包含在被调用的查询中的单引号中,如果double,那么我不会在timestamp调用中使用它,米只是关闭串到这一点与dt_string'的'值在连接前。 – user2877959

+0

它不是为我工作之前,因为我是用TIMESTAMP(VAR)和TIMESTAMP(“&VAR”)尝试,它也不过上班的时候我试过你的TIMESTAMP(%str(%')&var。%str(%'))。再次感谢!我认为这是可行的,因为DB2需要单引号......是这种情况吗?可以肯定的是,这不能用“简单”的proc sql完成吗? –