SQLFILE不加載任何數據。它只是執行(並在指定響亮選項時顯示結果),而不會將任何數據加載到Stata中。這有點反直覺,但是是真的。原因在odbc命令的pdf/dead tree手冊條目中有些不明確的解釋。
這是一個更有幫助的答案。假設你有你的SQL文件名爲sqlcode.sql。你可以打開它在Stata(只要它不是太長,其中太長取決於你的味道Stata)。基本上,文件讀取 - 逐行讀取SQL代碼,將結果存儲在名爲exec的本地宏中。然後,你傳遞宏作爲參數傳遞給-odbc負載命令:
更新的代碼來處理一些雙引號問題
剪切&下面的代碼粘貼到一個名爲loadsql.ado文件,該文件你應該把目錄放在Stata可以看到的目錄中(比如〜/ ado/personal)。你可以用-adopath-命令找到這樣的目錄。
program define loadsql
*! Load the output of an SQL file into Stata, version 1.3 ([email protected])
version 14.1
syntax using/, DSN(string) [User(string) Password(string) CLEAR NOQuote LOWercase SQLshow ALLSTRing DATESTRing]
#delimit;
tempname mysqlfile exec line;
file open `mysqlfile' using `"`using'"', read text;
file read `mysqlfile' `line';
while r(eof)==0 {;
local `exec' `"``exec'' ``line''"';
file read `mysqlfile' `line';
};
file close `mysqlfile';
odbc load, exec(`"``exec''"') dsn(`"`dsn'"') user(`"`user'"') password(`"`password'"') `clear' `noquote' `lowercase' `sqlshow' `allstring' `datestring';
end;
/*全部完成! */
的語法在Stata是
loadsql using "./sqlfile.sql", dsn("mysqlodbcdata")
您還可以添加其他所有ODBC加載選項,如透明,以及。顯然,您需要更改文件路徑和odbc參數以反映您的設置。這段代碼應該和-odbc sqlfile(「sqlfile.sql」),dsn(「mysqlodbcdata」)一樣 - 加上實際加載的數據。
我還添加了功能,以指定數據庫憑據這樣的:
loadsql using "./sqlfile.sql", dsn("mysqlodbcdata") user("user_name") password("not12345")
這個工作適合您嗎? –