This section describes how to create a table and insert data rows with a special SELECT statement.
SQL Server supports a special SELECT statement with an INTO clause, referred as SELECT INTO statement sometimes.
It combines SELECT, CREATE TABLE and INSERT operations in a single statement.
This statement should be treated as an update statement from the JDBC point of view, since it will not return any result set.
In this section, I want to use this SELECT INTO statement to build a new table with data
from the existing sample table Customer. The new table will be called, Profile, in my schema, Herong.
Here is the Java program that execute this SELECT INTO statement:
/**
* SelectInto.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
public class SelectInto {
public static void main(String [] args) {
Connection con = null;
try {
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1269;"
+ "user=sa;password=HerongYang;"
+ "database=AdventureWorksLT");
Statement sta = con.createStatement();
// creating new table and insert data in a single statement
int count = sta.executeUpdate(
"SELECT TOP 10 CustomerID UserID, FirstName, LastName,"
+ " ModifiedDate LastAccessDate"
+ " INTO Herong.Profile FROM SalesLT.Customer");
System.out.println("Number of rows inserted: "+count);
// getting the data back
ResultSet res = sta.executeQuery(
"SELECT * FROM Herong.Profile");
System.out.println("List of Profiles: ");
while (res.next()) {
System.out.println(
" "+res.getInt("UserID")
+ ", "+res.getString("FirstName")
+ ", "+res.getString("LastName")
+ ", "+res.getDate("LastAccessDate"));
}
res.close();
sta.close();
con.close();
} catch (java.lang.ClassNotFoundException e) {
System.err.println("ClassNotFoundException: "
+e.getMessage());
} catch (SQLException e) {
System.err.println("SQLException: "
+e.getMessage());
}
}
}
The output confirms that the SELECT INTO statement worked correctly: