I want to update column1 of table1 by checking the condition with column2 of table1 and column2 of table2.
I just get the error of missing right parenthesis.
I just check the ID of both tables (ID is foreign key to another table) and check the activation code came from query string and if they match I just update the value of status as approve
String s = "Approve";
stmt.executeUpdate("UPDATE
( SELECT Approval.STATUS AS st
FROM Approval
JOIN Activity
ON Activity.userid = Approval.id
WHERE Activity.activationcode =
'"+activationcode+"') as up SET up.st = '"+s+"'");
Replace your update table string with below and it should work
UPDATE
(SELECT
Approval.STATUS AS st
FROM
Approval JOIN Activity ON Activity.userid = Approval.id
WHERE
Activity.activationcode = '"+activationcode+"'
) up
SET up.st = '"+s+"'
In your query you are trying to update APPROVAL and UP tables both that is why you are getting an error
Related
I'm using java and I want to insert to mysql database a data if not exist, Also I want to update that data if exist. but I couldn't find mysql command for this.
I found this code for Insert but this is not what I want
INSERT INTO contacts
(contact_id, contact_name)
SELECT supplier_id, supplier_name
FROM suppliers
WHERE EXISTS (SELECT *
FROM orders
WHERE suppliers.supplier_id = orders.supplier_id);
For update, I found this code. but this is not what I want.
UPDATE suppliers
SET supplier_name = (SELECT customers.customer_name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id)
WHERE EXISTS (SELECT *
FROM customers
WHERE customers.customer_id = suppliers.supplier_id);
What I want to do is something like this
UPDATE student SET student_score = 20 where student_id = 1 WHERE EXIST ( select * from student where student_id = 1;
You can use:
insert into table_name (id, name, firstname) values(1, "Sessi", "Brahim") on duplicate key update name=values(name), firstname=values(firstname)
Adapt it to your query.
Im working with SQLite db in android and am stuck making a particular query:
I have a Table 1 with some email ids and I have another Table 2 with email ids and the usernames corresponding to those ids. From Table 2 I need to send only those emailid/usernames which are not present in Table 1. I want to do this using Cursor in android, something like:
Cursor cursor = getReadableDatabase().query(
MY_TABLE,
new String[] {ID},
EMAIL_ID +" = ?",
new String[]{email_id},
null,
null,
null);
The prerequisites are:
I don't want to use delete from Table 2
I don't want to create extra column in Table 2.
Use NOT IN with a subselect to filter out results in your query. For example:
SELECT emailid,username FROM table2 WHERE emailid NOT IN (SELECT emailid FROM table1)
Use rawQuery() for performing such raw SQL queries instead of query() which builds the SQL for you.
Example:
sqlite> create table table2(emailid,username);
sqlite> create table table1(emailid);
sqlite> insert into table1 select 'a#b.c';
sqlite> insert into table1 select 'a#b.c.d';
sqlite> insert into table2 select 'a#b.c.d','abcd';
sqlite> insert into table2 select 'a#b.c.d.e','abcde';
sqlite> SELECT emailid,username FROM table2 WHERE emailid NOT IN (SELECT emailid FROM table1);
a#b.c.d.e|abcde
Since #m0skit0 is insistent in his comments, let's demonstrate his query with the same data:
sqlite> SELECT t2.emailid, t2.username FROM table1 t1, table2 t2 WHERE t1.emailid <> t2.emailid;
a#b.c.d|abcd
a#b.c.d.e|abcde
a#b.c.d.e|abcde
You just need to join both tables over emailid and username field.
SELECT t2.emailid, t2.username FROM table1 t1, table1 t1a, table2 t2 WHERE t1.emailid <> t2.emailid AND t1a.username <> t2.username
This will get you all rows in table2 whose emailid or username does not exist in table1.
Also you need to use rawQuery method instead if more than one table in your SQL query:
private static final String QUERY = "SELECT t2.emailid, t2.username FROM table1 t1, table2 t2 WHERE t1.emailid <> t2.emailid AND t1.username <> t2.usernam";
final Cursor cursor = getReadableDatabase().rawQuery(QUERY, new String[0]);
I have 2 tables (table1, table2) table1 has a field id and table2 has a field id_eid that reference the id field of table1 as foreign key.
I have to delete from table1 all the rows that match a determinated criteria and then if these data are referenced in table2 delete the data from it too.
I do something like that, assuming con is the Connection object and autocommit is set to false on it.
String query1 = "delete from table2 where exists
(select * from table1 where someparameter = ? and table1.id = table2.id_eid)"
then i execute the first query1 using PreparedStatement.
then i have
String query2 = "delete from table1 where someparameter = ?
and exists (select * from table2 where table1.id = table2.id_eid)"
and i executed this with another PreparedStatment.
at the end i have the con.commit().
This doesn't work, i was thinking using autocommit to false the two queries was executed together but it is not, the second query deletes no rows, how can i do this ?
An important note, not all the rows in table1 have a referenced row in table2.
Thanks
You could always query the data to delete first, then delete it second:
1) Select ID from table1 where <criteria>
2) Select ID from table2 where <criteria>
3) Delete from table1 where ID in <results from (1)>
4) Delete from table2 where ID in <results from (2)>
If you
"have to delete from table1 all the rows that match a determinated criteria"
I think String query2 must be
String query2 = "delete from table1 where someparameter = ?"
I am getting this exception about commits and rollbacks but am not sure what exactly is wrong with my Stored Procedure. I have read the answers in other such questions and am unable to find where exactly the commit count is getting messed up.
So, this is the Stored Procedure I use:
-- this is a procedure used for the purge utility. This procedure uses the parameters of a date and lets user select
-- if the leads that should be purge must be closed either before, on or since that date.
-- operator: 0-->less 1-->equal 2-->greater
-- #closed: closing date
-- leadscount: returns the count of leads deleted
IF OBJECT_ID ('LEAD_PURGE', 'P') IS NOT NULL
DROP PROCEDURE LEAD_PURGE
go
CREATE PROCEDURE LEAD_PURGE
#purgextns INT,
#leadscount INT OUTPUT
AS
BEGIN
BEGIN TRANSACTION
CREATE TABLE #ASSIGNMENTS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #MAPRESULTS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #COMMAND_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #PROGRESS_STATUS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #DETAILS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #NEEDS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
insert into #ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM PURGE_LEAD);
SELECT #leadscount = (SELECT COUNT(*) FROM PURGE_LEAD);
INSERT INTO #MAPRESULTS_DELETED
SELECT ID FROM MAPRESULT WHERE ASSIGNMENTSEQ IN (SELECT ID FROM #ASSIGNMENTS_DELETED)
INSERT INTO #COMMAND_DELETED
SELECT ID FROM EXECUTERULECOMMAND WHERE MAPRESULTID IN (SELECT ID FROM #MAPRESULTS_DELETED)
INSERT INTO #PROGRESS_STATUS_DELETED
SELECT PROGRESS_STATUS_ID FROM COMMAND WHERE ID IN (SELECT ID FROM #COMMAND_DELETED)
INSERT INTO #DETAILS_DELETED
SELECT DETAILID FROM LEAD WHERE SEQID IN (SELECT ID FROM PURGE_LEAD)
INSERT INTO #NEEDS_DELETED
SELECT NEEDSID FROM LEAD WHERE SEQID IN (SELECT ID FROM PURGE_LEAD)
DELETE FROM PROGRESS_STATUS WHERE ID IN (SELECT ID FROM #PROGRESS_STATUS_DELETED)
DELETE FROM EXECUTERULECOMMAND WHERE ID IN (SELECT ID FROM #COMMAND_DELETED)
DELETE FROM COMMAND WHERE ID IN (SELECT ID FROM #COMMAND_DELETED)
DELETE FROM SIMPLECONDITIONAL WHERE RESULT IN (SELECT ID FROM #MAPRESULTS_DELETED)
DELETE FROM MAPPREDICATE WHERE ROWBP IN (SELECT ID FROM MAPROW WHERE RESULT IN (SELECT ID FROM #MAPRESULTS_DELETED))
DELETE FROM MAPROW WHERE RESULT IN (SELECT ID FROM #MAPRESULTS_DELETED)
DELETE FROM MAPRESULT WHERE ID IN (SELECT ID FROM #MAPRESULTS_DELETED)
DELETE FROM ASSIGNMENTATTACHMENTS WHERE ASSIGNMENTSEQ IN (SELECT ID FROM #ASSIGNMENTS_DELETED)
DELETE FROM LEADOBSERVER WHERE ASSIGNSEQ IN (SELECT ID FROM #ASSIGNMENTS_DELETED)
DELETE FROM MAPDESTINATIONS WHERE SUGGESTEDASSIGNID IN
(SELECT ID FROM SUGGESTEDASSIGNMENT WHERE ASSIGNMENT_SEQID IN (SELECT ID FROM #ASSIGNMENTS_DELETED))
DELETE FROM SUGGESTEDASSIGNMENT WHERE ASSIGNMENT_SEQID IN (SELECT ID FROM #ASSIGNMENTS_DELETED)
DELETE FROM PRODUCTINTEREST WHERE LEADSEQ IN (SELECT ID FROM PURGE_LEAD)
CREATE TABLE #SALE_DELETED_EX
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
INSERT into #SALE_DELETED_EX SELECT SALEEXSEQ FROM SALE WHERE SEQID IN (SELECT SALEID FROM LEADSALES WHERE LEADID IN (SELECT ID FROM PURGE_LEAD))
DELETE FROM SALE WHERE SEQID IN (SELECT SALEID FROM LEADSALES WHERE LEADID IN (SELECT ID FROM PURGE_LEAD))
DELETE FROM SALEEXTENSIONS WHERE
SEQID IN (SELECT ID FROM #SALE_DELETED_EX)
DELETE FROM LEADSALES WHERE LEADID IN (SELECT ID FROM PURGE_LEAD)
DELETE FROM NOTES WHERE OBJECTID IN (SELECT ID FROM #NEEDS_DELETED) OR OBJECTID IN (SELECT ID FROM #DETAILS_DELETED)
DELETE FROM HISTORYRECORD WHERE OBJECTID IN (SELECT ID FROM #DETAILS_DELETED)
DELETE FROM DETAIL WHERE SEQID IN (SELECT ID FROM #NEEDS_DELETED UNION SELECT ID FROM #DETAILS_DELETED)
DELETE FROM MESSAGES WHERE PROVIDERID IN (SELECT ID FROM PURGE_LEAD)
DELETE FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM PURGE_LEAD)
DELETE FROM LEAD WHERE SEQID IN (SELECT ID FROM PURGE_LEAD)
CREATE TABLE #PURGE_LEAD_E
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
INSERT into #PURGE_LEAD_E Select SEQID FROM LEADEXTENSIONS WHERE
SEQID NOT IN (SELECT LEADEXSEQ FROM LEAD)
if #purgextns = 1 begin
DELETE FROM LEADEXTENSIONS WHERE
SEQID IN (SELECT ID FROM PURGE_LEAD_E)
end
DELETE FROM PURGE_LEAD;
DROP TABLE #ASSIGNMENTS_DELETED
DROP TABLE #MAPRESULTS_DELETED
DROP TABLE #COMMAND_DELETED
DROP TABLE #PROGRESS_STATUS_DELETED
DROP TABLE #DETAILS_DELETED
DROP TABLE #NEEDS_DELETED
DROP TABLE #PURGE_LEAD_E
DROP TABLE #SALE_DELETED_EX
COMMIT
END
go
now I call this procedure in the following code:
try {
c = new ConnectionHelper().getConnection();
String sql = "";
if (shouldPurgeExtns) {
progressModel.makeProgress("progress.deleting.dependents");
purgeMultiselect(c, LEAD, isMSSQL);
}
sql = "{CALL " + TOPLinkManager.getSchemaPrefix()
+ "LEAD_PURGE (?,?)}";
cs = c.prepareCall(sql);
cs.setInt(1, shouldPurgeExtns ? 0 : 1);
cs.registerOutParameter(2, java.sql.Types.INTEGER);
cs.executeUpdate();
int rowcount = cs.getInt(2);
cs.close();
progressModel.makeProgress("progress.recording.history");
recordHistory(c, isMSSQL, LEAD, DateTypeDecorator.CLOSED, date,
rowcount);
done(progressModel);
c.close();
return true;
} catch (Exception e) {
Logs.main.error("Error Purging Leads", e);
throw new Exception(e.getMessage());
}
And I get an exception on the line which say int rowcount = cs.getInt(2);
The Exception is:
com.microsoft.sqlserver.jdbc.SQLServerException: Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1454)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.processResults(SQLServerStatement.java:1083)
at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.getOutParameter(SQLServerCallableStatement.java:112)
at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.getterGetParam(SQLServerCallableStatement.java:387)
Please help me out.
at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.getValue(SQLServerCallableStatement.java:393)
at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.getInt(SQLServerCallableStatement.java:437)
at marketsoft.tools.purge.PurgeUtils.PurgeLeads(PurgeUtils.java:283)
EDIT:
as I have answered this question myself... I would like to change the question a bit now.
Why was no exception thrown in the execute method???
Your COMMIT is not being hit, probably because of an error. The transaction won't be rolled back automatically
The best way (and best practice) is to add some SQL error handling
CREATE PROCEDURE LEAD_PURGE
#purgextns INT,
#leadscount INT OUTPUT
AS
SET NOCOUNT, XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION
CREATE TABLE #ASSIGNMENTS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
...
DROP TABLE #SALE_DELETED_EX
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0
ROLLBACK TRANSACTION
RAISERROR ('it broke', 16, 1)
END CATCH
go
For more details on what is going on here, see my answer here Nested stored procedures containing TRY CATCH ROLLBACK pattern?
Note: you don't need to drop the temp tables as they go out of scope when the stored procedure exits
Try to add in the beginning of procedure
SET XACT_ABORT ON
Or
Wrap your statements with
begin try
BEGIN TRANSACTION
Your TSQL code
COMMIT
end try
begin catch
ROLLBACK
RAISERROR('Gotcha!', 16, 1)
end catch
To check how many uncommitted BEGIN TRAN is opened test the ##TRANCOUNT system variable
This normally happens when the transaction is started and either it is not committed or it is not rollback.
In case the error comes in your stored procedure, this can lock the database tables because transaction is not completed due to some runtime errors in the absence of exception handling
You can use Exception handling like below. SET XACT_ABORT
SET XACT_ABORT ON
SET NoCount ON
Begin Try
BEGIN TRANSACTION
//Insert ,update queries
COMMIT
End Try
Begin Catch
ROLLBACK
End Catch
Sorry Guys! Thanks for all your efforts, In the end, it was a very small mistake on my part in the Stored Procedure:
Look at line:
if #purgextns = 1 begin
DELETE FROM LEADEXTENSIONS WHERE
SEQID IN (SELECT ID FROM PURGE_LEAD_E)
end
It should be #PURGE_LEAD_E
All your answers helped me get a different perspective of store procedure development. Thanks a lot!
How exactly the #leadscount variable contains the count of leads deleted?
This is the only place I see it beeing used:
SELECT #leadscount = (SELECT COUNT(*) FROM PURGE_LEAD);
Anyhow, to test it, why don't you run the above code outside the context of the transaction?
If you really need it to be inside a transaction, try loading the value into a table variable (create a table with only one column). Since they don't participate in transactions you can test if the transaction is your real problem.
i have two tables "Table1" with columns user_name,Password and course ID and another table "course" with columns course_id,course_name.I have used the following code to display the course ID from Table1 according to the user_name received from the login page.using ResultSet rs1.now i want to retrieve the course_name from the table "course" according to the course ID receieve from "Table1".for that in the second query pstmt2.setString(1, ); what parameter i should use to get the course_id value from the previous query
HttpSession sess=request.getSession();
String a=(String)sess.getAttribute("user");
String b=(String)sess.getAttribute("pass");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:ggg");
Statement st = con.createStatement();
String query="select * from Table1 where user_name=?";
PreparedStatement pstmt=con.prepareStatement(query);
pstmt.setString(1,a);
ResultSet rs1=pstmt.executeQuery();
while(rs1.next())
out.println("<h3>COURSE ID: "+rs1.getString("course ID")+"<h3>");
String query2="SELECT * from course where course_id=?";
PreparedStatement pstmt2=con.prepareStatement(query2);
pstmt2.setString(1,);
ResultSet rs2=pstmt2.executeQuery();
while(rs2.next())
{
out.println("<h3>course name: "+rs2.getString("course_name")+"<h3>");
}
why do you go for two turns of database hit, even though you created one time connection object.
modify the query as below
SELECT * from course where course_id = (select course_id from Table1 where user_name=?);
from this query you noneed to give input of courseid also.
No need to hit database twice to get the results that you need. use the query
Select table1.course_id, course.course_name from table1, course where table1.course_id=course_id and table1.user_name=?
This should set the course_id parameter:
pstmt2.setString(1,rs1.getString("course_id"));
Or, as I see the "course_id" column may have a different name in "Table1":
pstmt2.setString(1,rs1.getString("course ID"));
As the other post mentioned there's no need to go to another set of query. Try this example query:
SELECT course.course_id, course.course_name
FROM table1 t1
INNER JOIN course c
ON t1.course_id = c.course_id
WHERE t1.user_name = ?;
Now if you insist your coding the parameter o your pstmt2.setString(1,); is:
pstmt2.setString(1,rs1.getString("course_id")); //or course ID defending on your column name