stata odbc sqlfile

可紊 提交于 2019-12-02 04:17:26

sqlfile doesn't load any data. It just executes (and displays the results when the loud option is specified), without loading any data into Stata. That's somewhat counter-intuitive, but true. The reasons are somewhat opaquely explained in the pdf/dead tree manual entry for the odbc command.

Here's a more helpful answer. Suppose you have your SQL file named sqlcode.sql. You can open it in Stata (as long as it's not too long, where too long depends on your flavor of Stata). Basically, -file read- reads the SQL code line by line, storing the results in a local macro named exec. Then you pass that macro as an argument to the -odbc load- command:

Updated Code To Deal With Some Double Quotes Issues

Cut & paste the following code into a file called loadsql.ado, which you should put in directory where Stata can see it (like ~/ado/personal). You can find such directories with the -adopath- command.

program define loadsql
*! Load the output of an SQL file into Stata, version 1.3 (dvmaster@gmail.com)
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;

/* All done! */

The syntax in Stata is

loadsql using "./sqlfile.sql", dsn("mysqlodbcdata") 

You can also add all the other odbc load options, such as clear, as well. Obviously, you will need to change the file path and the odbc parameters to reflect your setup. This code should do the same thing as -odbc sqlfile("sqlfile.sql"), dsn("mysqlodbcdata")- plus actually load the data.

I also added the functionality to specify your DB credentials like this:

loadsql using "./sqlfile.sql", dsn("mysqlodbcdata") user("user_name") password("not12345") 
akavalar

For "--XYZ" style comments, do something like this (assuming you don't have "--" in your SQL code):

if strpos(`"``line''"', "--") > 0 {;
    local `line' = substr(`"``line''"', 1, strpos(`"``line''"', "--")-1);
    };

I had to post this as an answer otherwise the formatting would've been all messed up, but it's obviously referring to Dimitriy's code. (You could also define a local macro holding the position of the "--" string to make your code a little cleaner.)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!