Search code examples
javasql-serverresultsettemp-tables

Fetch Data from MSSQL DB with temp table over JAVA


I try fetch data from MSSQL DB just like below;

ResultSet rs2;
Statement stmt;
String query2 ="USE DBOne\n" +
"DECLARE @temp_table table (column1 VARCHAR(60))\n" +
"insert into @temp_table (column1)\n" +
"select column1 from real_table (nolock)\n" +
"where date between '2014-08-14 10:00:00.000' and '2014-08-14 10:00:10.000'\n" +
"and column1 not like ''\n" +
"\n" +
"select column1 from @temp_table";

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://192.168.131.10;" + "databaseName=DBOne;" + "user=" + "DBUser" + ";" + "password=" + "userpassword" + ";"; 
Connection con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();

rs2 = stmt.executeQuery(query2);

while (rs2.next()) {

System.out.println(rs2.getString(1)); 

}

But rs2 retun null strangely. I suspect @temp_table creation is problematic over JAVA. Because same query without creation temp table succesfully working.;

String query2 ="USE DBOne\n" +
"select column1 from real_table (nolock)\n" +
"where date between '2014-08-14 10:00:00.000' and '2014-08-14 10:00:10.000'\n" +
"and column1 not like ''";

I dont want create storedprocedure in DB for this simple thing. Any idea how can i solve this problem?


Solution

  • I ask same issue with different style and solved in below question. Sometimes we dont reach right person :)

    Fetch Resultset of created&filled MSSQL temp table over Java