通过JAVA上的临时表从MSSQL DB获取数据

时间:2014-08-14 11:11:55

标签: java sql-server resultset temp-tables

我尝试从MSSQL DB中获取数据,如下所示;

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)); 

}

rs2奇怪地重新归零。我怀疑@temp_table创建比JAVA有问题。因为没有创建临时表的相同查询成功地工作。;

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 ''";

我不想在DB中为这个简单的东西创建storedprocedure。我知道如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我问不同风格的同一问题,并在下面的问题解决。有时我们找不到合适的人:)

Fetch Resultset of created&filled MSSQL temp table over Java