2012-03-22 81 views
1

我想在一夜之間查詢過去一週添加到Oracle數據庫的情況,並且需要使用宏來填充日期。如果我硬編碼實際日期,我可以運行下面的查詢。我已經嘗試過兩個單引號的宏變量&sd&ed。請指教。適用於Oracle查詢中SAS宏日期的語法

data _null_; 
sd = dhms(today()-7,00,00,00); 
ed = dhms(today()-1,23,59,59); 
call symput("sd", put(sd, datetime20.)); 
call symput("ed", put(ed, datetime20.)); 
run; 
%put &sd &ed; 

proc sql; 
connect to oracle (user=x password=x path=x); 
create table weekly_test as 
select * from connection to oracle 
(select * from x.Estimates 
where state_fips_code = '41' 
and altered_date between 
    to_date('&sd','DDMONYYYY:HH24:MI:SS') 
    and to_date('&ed','DDMONYYYY:HH24:MI:SS')); 
disconnect from oracle; 
quit; 

錯誤

ORACLE execute error: ORA-01858: a non-numeric character was found where a numeric was expected.

,並用雙引號

and altered_date between 
    to_date("&sd",'DDMONYYYY:HH24:MI:SS') 
    and to_date("&ed",'DDMONYYYY:HH24:MI:SS')); 

此錯誤

ERROR: ORACLE prepare error: ORA-00904: " 21MAR2012:23:59:59": invalid identifier. SQL 
statement: select * from X.Estimates where state_fips_code = '41' and altered_date 
between to_date(" 15MAR2012:00:00:00",'DDMONYYYY:HH24:MI:SS') and to_date(" 
21MAR2012:23:59:59",'DDMONYYYY:HH24:MI:SS'). 

回答

1

最好的辦法是與周圍的數值單引號定義宏變量。事實上,我不認爲有必要將其格式化爲日期時間文字;只需構造一個普通的ANSI日期字符串(YYYY-MM-DD),您也可以擺脫TO_DATE函數調用。

例如,嘗試這兩個語句:

%let SD=%str(%')%sysfunc(putn(%sysfunc(intnx(day,%sysfunc(today()) ,-7)),yymmdd10.))%str(%'); 
%let ED=%str(%')%sysfunc(putn(%sysfunc(intnx(day,%sysfunc(today()) ,-1)),yymmdd10.))%str(%'); 

那些定義SD作爲今日() - 7和ED今天() - 1(使用純的宏代碼,而不是一個數據步驟)。然後,在您的查詢中,引用這些宏變量未加引號:

proc sql; 
connect to oracle (user=x password=x path=x); 
create table weekly_test as 
select * from connection to oracle 
(select * from x.Estimates 
where state_fips_code = '41' 
and altered_date between &sd and &ed 
); 
disconnect from oracle; 
quit; 
0

非常感謝鮑勃。我試過你發佈的代碼,並得到ORA-01861:文字不符合格式字符串。無論如何,你讓我在正確的道路上思考。我只是添加了代碼來在數據步驟中將我的日期放在單引號內,並且它工作正常。對於任何有類似問題的人,代碼如下。

data _null_; 
sd = dhms(today()-7,00,00,00); 
ed = dhms(today()-1,23,59,59); 
call symput('sd',"'"|| trim(left(put(sd, datetime20.)))||"'"); 
call symput('ed', "'"||trim(left(put(ed, datetime20.)))||"'"); 
run; 
%put &sd &ed; 

proc sql; 
connect to oracle (user=x password=x path=x); 
create table weekly_test as 
select * from connection to oracle 
(select * from x.Estimates 
where state_fips_code = '41' 
and altered_date between 
    to_date(&sd,'DDMONYYYY:HH24:MI:SS') 
    and to_date(&ed,'DDMONYYYY:HH24:MI:SS')); 
disconnect from oracle; 
quit; 
0

這個工程....

%LET SD = %SYSFUNC(intnx(day,"&SYSDATE9"d,-7,b),date9.) ; 
%LET ED = %SYSFUNC(intnx(day,"&SYSDATE9"d,-1,b),date9.) ; 
%PUT &SD &ED ; 

proc sql ; 
    connect to oracle (user=x password=x path=x); 
    create table weekly_test as 
    select * from connection to oracle 
    (select * from x.Estimates 
    where state_fips_code = '41' 
    and altered_date between %BQUOTE('&SD') and %BQUOTE('&ED') 
); 
    disconnect from oracle ; 
quit ;