I need to create a temp table in order to store some ids which i will process under a later query. I am receiving error
com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
When i execute my query for the creation of #temp table inside my sql. I don't need any resultset from this execution just need to create a temporary table with records. Please guide.
Code for my main query:
String queryTempTable = "SELECT TOP (2) A.Id INTO #temp\n" +
"FROM SALESDM.dbo.FactSales A\n" +
"INNER JOIN SALESDM2.dbo.FactSales B\n" +
"ON A.Id = B.Id\n" +
"AND (\n" +
" A.sysDateModified = B.sysDateModified\n" +
" OR A.Id = B.Id\n" +
" OR A.ModifiedDatetime = B.ModifiedDatetime\n" +
" )";
System.out.println(queryTempTable);
if (conn == null) {
System.out.println("Unable to create Connection");
} else {
Statement stmtTempTable = conn.createStatement();
stmtTempTable.executeQuery(queryTempTable);
}
You should use executeQuery only when you are retrieving data and want a ResultSet.
If you are modifying data, then you should use execute:
stmtTempTable.execute(queryTempTable);
If possible create a view using the given query? This will act as a temporary table. And call the view later based on your requirement.
Related
I have the following code which is used to retrieve data from multiple tables (using joins) and then mapping every row into a DTOList but I also need to apply filters based on user preferences: per table1.name or table2.name, table3, etc.
So I just want to know what would be the best way to do it in terms of performance and best practices;
retrieving all rows and then apply the filters with lambdas (easier)
change the query to a dynamic query with Criteria or something else?
Any other solution=?
#Repository
public class ArchiveRepository {
#Autowired
EntityManager em;
String queryStr = "select wsr.id as sampleid, s.id as slideid, tb.name as batchname, k.lot_number as kitlot, " +
" 'STRING' as slidetype, tb.worklist_name as worklist, wsr.final_call as results, " +
" wa.final_pattern_ids as patterns, 'edited/yesno' as edited, wsr.last_modified_by as user, wsr.last_modified_date as time " +
" from slide s " +
" left join table2 tb on s.test_batch_id = tb.id " +
" left join table3 k on tb.kit_lot_id = k.id " +
" left join table4 w on s.id = w.slide_id " +
" left join tabl5 pw on pw.well_id = w.id " +
" left join tabl6 cw on cw.well_id = w.id " +
" left join tabl7 wsr on wsr.patient_well_sample_id = pw.id or wsr.control_sample_id = cw.id " +
" left join (select * from *** (other subselect)) wa on wa.well_sample_id = wsr.**id or wa.well_sample_id = wsr.**id " +
"where tb.state = 'STATENEEDED'";
public ArchiveDataListDTO getArchiveData(){
Query query = em.createNativeQuery(queryStr);
ArchiveDataListDTO archiveDataListDTO = new ArchiveDataListDTO();
List<Object[]> resultL = (List<Object[]>)query.getResultList();
for( Object[] o : resultL){
archiveDataListDTO.addArchiveDataRow(
new ArchiveDataDTO((String)o[0], String.valueOf(o[1]), (String) o[2], (String) o[3], (String) o[4], (String) o[5],
(String) o[6], (String) o[7], (String) o[8], (String) o[9], (String) o[10]));
}
return archiveDataListDTO;
}
}
**
note I struggled some with the code cause I wanted to apply #sqlresultsetmapping to avoid manual results mapping but it just didn´t work, most of the examples out there are when you have an entity in the DB but in this case I retrieve from many tables.**
Thanks so much
2 .- change the query to a dynamic query with Criteria or something else?
I ended up creating the query on the fly; depending on the filters I get from UI i assemble the query with Java and send it to DB, it´s easier since this required many tables...
Is it possible to execute an update query then a delete query right after the update one in the same transaction? I'm trying to activate an account based on a token's hash and then remove that token in the same transaction.
transaction.begin();
entityManager
.createNativeQuery(
"UPDATE accounts AS ac "
+ "INNER JOIN account_tokens AS ak ON ac.id = ak.account_id "
+ "SET ac.account_state = "
+ "CASE "
+ "WHEN ac.account_state = 'AWAITING_ACTIVATION' THEN 'ACTIVATED' "
+ "END "
+ "WHERE ak.token_hash = :tokenHash")
.setParameter()
.executeUpdate();
em.createNativeQuery(
"DELETE FROM account_tokens AS ak "
+ "WHERE ak.token_hash = :tokenHash")
.setParameter()
.executeUpdate(); // delete
transaction.commit();
Yes, Use PL/SQL Procedure.
You can't reduce the number of queries - they all do different things - but you could reduce the number of round trips to the database and the number of parses by wrapping it all as a PLSQL function.
CREATE PROCEDURE s_u_d(a)
BEGIN
UPDATE tab_x SET tab_x.avalue=1 WHERE tab_x.another=a;
DELETE FROM tab_y WHERE tab_y.avalue=a;
SELECT *
FROM tab_x
WHERE tab_x.another=a;
END;
I am using JPQL constructor in my code. It involves large results, 5024 data retrieved and objects created when executing this query. It is taking around 2 minutes to complete its execution. There are multiple tables involved to execute this query. I could not go for cache since the DB data will update daily. Is there any way to optimize the execution speed?
My SQL query formation is like this,
String sql = "SELECT DISTINCT "
+ "new com.abc.dc.entity.market.LaptopData(vd.segment.id, vd.segment.segmentGroup, "
+ "vd.segment.segmentName, vd.segment.category, "
+ "vd.product.make, vd.product.model, vd.product.modelYear) "
+ "FROM LaptopData vd, Profile p "
+ "WHERE vd.profile.profileCode = :profileCode "
+ "AND vd.pk.profileId = p.id "
+ "Order By vd.segment.segmentGroup, vd.segment.segmentName, vd.product.make, vd.product.model,"
+ " vd.product.modelYear asc";
Query query = em.createQuery(sql);
query.setParameter("profileCode", profileCode);
#SuppressWarnings("unchecked")
List<LaptopData> results = query.getResultList();
em.clear();
return results;
Well, one option for you is to create separate table which would contain result of this query for all entities and update it daily (every night) and then run your query on this new table, like this:
"SELECT DISTINCT"
+ "new com.abc.dc.entity.market.LaptopData(m.id, m.segmentGroup, "
+ "m.segmentName, m.category, "
+ "m.make, m.model, m.modelYear) "
+ "FROM someNewTable m"
+ "WHERE m.profileCode = :profileCode ";
This way you don't have to do join and ordering every time you execute your query, but only once a day when you generate new table. Ofcourse with this approach to see data updates you'll have to wait until new table is recreated.
Also, you can create indexes on fields you are using in where clause.
I have a problem with getting the alias of the columnnames for my ResultSet.
I made a subquery, where i use the alias function(MAX(...) in SQL) but everytime I execute the Statement, I get java.sql.SQLException because the column name is not valid. And I use the current alias where I call the getString - Function of my ResultSet.
This is my SQL-Statement in Eclipse:
String sql = "SELECT a.steelgrade, a.prod_order_id, a.prod_order_item_pos, "
+"a.prod_order_version, a.strip_thickn_aim, a.strip_width_aim, "
+"a.customer, a.order_weight_plan, b.grund_kommlos, b.coil_weight "
+"FROM (SELECT prod_order_id, prod_order_item_pos, "
+ "MAX (prod_order_version) AS max_version "
+ "FROM production_order "
And in the ResultSet while.next()-Loop:
prod_order_version = AuftraegeProduction.getString("max_version");
This is the whole SQL-Statement( in the Database it works fine!):
SELECT a.steelgrade, a.prod_order_id, a.prod_order_item_pos,
a.prod_order_version, a.strip_thickn_aim, a.strip_width_aim,
a.customer, a.order_weight_plan, b.grund_kommlos, b.coil_weight
FROM (SELECT prod_order_id, prod_order_item_pos,
MAX (prod_order_version) AS max_version
FROM production_order
GROUP BY prod_order_id, prod_order_item_pos) c
JOIN
production_order a
ON a.prod_order_id = c.prod_order_id
AND a.prod_order_item_pos = c.prod_order_item_pos
AND a.prod_order_version = c.max_version
JOIN pps_plan_slab b
ON b.prod_order_id = c.prod_order_id
AND b.prod_order_item_pos = c.prod_order_item_pos
AND b.prod_order_version = c.max_version
WHERE a.strip_thickn_aim > 1.78
AND a.strip_thickn_aim < 3.26
AND a.steelgrade = 'M4R51'
AND a.prod_order_id NOT BETWEEN '0999551' AND '0999599'
AND a.strip_width_aim BETWEEN 1126 AND 1166
AND NVL (a.order_weight_plan, 0) > 0
AND a.order_weight_plan >= b.coil_weight
ORDER BY prod_order_id ASC
Anyone have a suggestion?
Maurice
when using aggregate functions max(),min(),sum(),... you must use group by clause clause.
I'm using the h2 v1.3.176.
I have user-defined function which execute RECURSIVE query.
public static ResultSet getChildCategories(Connection connection, long categoryId) throws SQLException {
String sql =
"WITH RECURSIVE r(CATEGORY_ID, PARENT_ID) AS (\n" +
" SELECT CATEGORY_ID\n" +
" ,PARENT_ID\n" +
" FROM CATEGORY\n" +
" WHERE CATEGORY_ID = " + categoryId + "\n" +
" UNION ALL\n" +
" SELECT CATEGORY.CATEGORY_ID\n" +
" ,CATEGORY.PARENT_ID\n" +
" FROM CATEGORY, r\n" +
" WHERE CATEGORY.PARENT_ID = r.CATEGORY_ID\n" +
")\n" +
"SELECT CATEGORY_ID FROM r";
ResultSet resultSet = connection.createStatement().executeQuery(sql);
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("CATEGORY_ID", Types.INTEGER, 12, 0);
try {
while(resultSet.next()) {
rs.addRow(resultSet.getLong(1));
}
} finally {
resultSet.close();
}
return rs;
}
I have registered this function by following SQL.
create alias GET_CHILD_CATEGORIES for "com.myapp.db.function.Functions.getChildCategories";
My problem is the getChildCategories function will be called many times when I execute the following query.
SELECT DISTINCT B.BOOK_ID
,B.SERIES_ID
,B.TITLE
,B.ISBN
,B.VOLUME
,(
SELECT MAX(SAME_SERIES.VOLUME)
FROM BOOK SAME_SERIES
WHERE SAME_SERIES.SERIES_ID = B.SERIES_ID
AND SAME_SERIES.VOLUME IS NOT NULL
) AS VOLUME_COUNT
,B.PAGE_COUNT
,B.FILE_PATH
,B.SORTABLE_FILE_NAME
,B.SIZE
,B.HASH
,B.COVER_IMAGE_TYPE
,B.COVER_PAGE_NO
,B.COVER_LARGE_IMAGE_URL
,B.COVER_SMALL_IMAGE_URL
,B.COVER_CROP_COORD
,B.IS_ENCRYPT
,B.PUBLISHER_ID
,B.PUBLISHED_DATE
,B.CREATION_TIME
,B.LAST_MODIFIED_TIME
,B.NOTE
,B.IS_ISBN_SEARCH
,S.CATEGORY_ID
,S.TITLE
,BA.AUTHOR_ID
,BT.TAG_ID
FROM BOOK AS B
INNER JOIN SERIES AS S ON S.SERIES_ID = B.SERIES_ID
LEFT OUTER JOIN BOOK_TAG AS BT ON BT.BOOK_ID = B.BOOK_ID
LEFT OUTER JOIN BOOK_AUTHOR AS BA ON BA.BOOK_ID = B.BOOK_ID
WHERE
(
S.CATEGORY_ID IN (SELECT CATEGORY_ID FROM GET_CHILD_CATEGORIES(106))
And
S.IS_COMPLETION = 1
)
ORDER BY BA.AUTHOR_ID
Why do many times would be called this function?
Extracted from H2 documentation
A function that returns a result set can be used like a table.
However, in this case the function is called at least twice: first
while parsing the statement to collect the column names (with
parameters set to null where not known at compile time). And then,
while executing the statement to get the data (maybe multiple times if
this is a join). If the function is called just to get the column
list, the URL of the connection passed to the function is
jdbc:columnlist:connection. Otherwise, the URL of the connection is
jdbc:default:connection.
The first calls are only to retrieve the resultset column types. Then you have to check if the connection url is "jdbc:columnlist:connection". If true you have to return an empty result set with column list.
The connection url test is:
connection.getMetaData().getURL().equals("jdbc:columnlist:connection");