Incrementing with an update statement in MySQL
Hi,
Disclaimer: I'm very new to this whole thing.
I have a very simple DB, one with names in it and one with a numberOfTimesAccessed. As you'd imagine, each time a name is accessed I want to increment the associated numberOfTimesAccessed field. Is there a way to do this, without first getting what was in the numberOfTimesAccessed field before? Is this overcomplicating things?
Thanks in advance,
elmicko
for example, if you have columns name, numberOfTimesAccessed in table access_log,
try (for updating name='foobar')
UPDATE access_log SET numberOfTimesAccessed=numberOfTimesAccessed+1 WHERE id='foobar';hope this helps
Similar Messages
-
Update multiple columns with single update statement..
HI all,
i am reading the columns value from different table but i want to update it with signle update statement..
such as how to update multiple columns (50 columns) of table with single update statement .. is there any sql statement available i know it how to do with pl/sql..As I understood, may be this. Here i am updating ename,sal, comm columns all at once.
SQL> select * from emp where empno=7369;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17/12/1980 12:00:00 800 20
SQL> UPDATE emp
2 SET ename = lower (ename),
3 sal = sal + 1000,
4 comm = 100
5 WHERE empno = 7369;
1 row updated.
SQL> select * from emp where empno=7369;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 smith CLERK 7902 17/12/1980 12:00:00 1800 100 20
SQL> UPDATE emp
2 SET ename = (SELECT 'ABCD' FROM DUAL),
3 sal = (SELECT 1000 FROM DUAL),
4 comm = (SELECT 100 FROM DUAL)
5 WHERE empno = 7369;
1 row updated. -
Help with this update statement..
Hi everyone,
I am trying to update a column in a table .I need to update that column
with a function that takes patient_nbr and type_x column values as a parameter.
That table has almost "300,000" records. It is taking long time to complete
almost 60 min to 90 min.
Is it usual to take that much time to update that many records?
I dont know why it is taking this much time.Please help with this update statement.
select get_partner_id(SUBSTR(patient_nbr,1,9),type_x) partner_id from test_load;
(it is just taking 20 - 30 sec)
I am sure that it is not the problem with my function.
I tried the following update and merge statements .Please correct me if i am wrong
in the syntax and give me some suggestions how can i make the update statement fast.
update test_load set partner_id = get_partner_id(SUBSTR(patient_nbr,1,9),type_x);
merge into test_load a
using (select patient_nbr,type_x from test_load) b
on (a.patient_nbr = b.patient_nbr)
when matched
then
update
set a.partner_id = get_partner_id(SUBSTR(b.patient_nbr,1,9),b.type_x);
there is a index on patient_nbr column
and the statistics are gathered on this table.Hi Justin,
As requested here are the explain plans for my update statements.Please correct if i am doing anything wrong.
update test_load set partner_id = get_partner_id(SUBSTR(patient_nbr,1,9),type_x);
"PLAN_TABLE_OUTPUT"
"Plan hash value: 3793814442"
"| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |"
"| 0 | UPDATE STATEMENT | | 274K| 4552K| 1488 (1)| 00:00:18 |"
"| 1 | UPDATE | TEST_LOAD | | | | |"
"| 2 | TABLE ACCESS FULL| TEST_LOAD | 274K| 4552K| 1488 (1)| 00:00:18 |"
merge into test_load a
using (select patient_nbr,type_x from test_load) b
on (a.patient_nbr = b.patient_nbr)
when matched
then
update
set a.partner_id = get_partner_id(SUBSTR(b.patient_nbr,1,9),b.type_x);
"PLAN_TABLE_OUTPUT"
"Plan hash value: 1188928691"
"| Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)| Time |"
"| 0 | MERGE STATEMENT | | 274K| 3213K| | 6660 (1)| 00:01:20 |"
"| 1 | MERGE | TEST_LOAD | | | | | |"
"| 2 | VIEW | | | | | | |"
"|* 3 | HASH JOIN | | 274K| 43M| 7232K| 6660 (1)| 00:01:20 |"
"| 4 | TABLE ACCESS FULL| TEST_LOAD | 274K| 4017K| | 1482 (1)| 00:00:18 |"
"| 5 | TABLE ACCESS FULL| TEST_LOAD | 274K| 40M| | 1496 (2)| 00:00:18 |"
"Predicate Information (identified by operation id):"
" 3 - access("A"."patient_nbr"="patient_nbr")"Please give some suggestions..
what's the best approach for doing the updates for huge tables?
Thanks -
What is wrong with this update statement
Hi all,
I am trying to create a simple update program that allows user to enter table name, key fields and one field to update and its value.
But report goes into dump at update statement?
Here is the code:
REPORT ZTABLE_UPDATE.
parameters: tabname(18).
PARAMETERS: key1(15),"use at where condition
key1val(20),
key2(15),"use at where condition
key2val(20),
field2(15)."field to be updated
PARAMETERS: yenideg1(20),
yenideg2(20).
CONDENSE: tabname, field2,
yenideg1, yenideg2,
key1val, key2val,
key1, key2.
data: wa like tabname.
*update (tabname) SET field2 = yenideg1*
*WHERE key1 like key1val and key2 like key2val.*if sy-subrc eq 0.
SELECT SINGLE * FROM (tabname) INTO wa
WHERE key1 like key1val
and key2 like key2val.
WRITE / wa. "to test whether replacement is ok.
endif.
Thanks in advance.
DenizHi:
follows is ok:
DATA: dy_table TYPE REF TO data,
dy_line TYPE REF TO data,
ifc TYPE lvc_t_fcat,
xfc TYPE lvc_s_fcat.
DATA: it_clrs_fields LIKE TABLE OF dfies WITH HEADER LINE.
DATA: cond(72) TYPE c,
itab LIKE TABLE OF cond,
itab2 LIKE TABLE OF cond.
FIELD-SYMBOLS: <dyn_table> TYPE STANDARD TABLE,
<dyn_wa>,
<dyn_field>,
<fs>.
PARAMETERS: tabname TYPE ddobjname OBLIGATORY.
PARAMETERS: key1(15) OBLIGATORY,"use at where condition
key1val(20) OBLIGATORY,
key2(15),"use at where condition
key2val(20),
field2(15)."field to be updated
PARAMETERS: yenideg1(20),
yenideg2(20).
***START
CONDENSE: tabname, field2,
yenideg1, yenideg2,
key1val, key2val,
key1, key2.
CALL FUNCTION 'DDIF_FIELDINFO_GET'
EXPORTING
tabname = tabname
TABLES
dfies_tab = it_clrs_fields[]
FIXED_VALUES =
EXCEPTIONS
not_found = 1
internal_error = 2
OTHERS = 3
LOOP AT it_clrs_fields .
MOVE-CORRESPONDING it_clrs_fields TO xfc.
APPEND xfc TO ifc.
CLEAR: xfc.
ENDLOOP.
CALL METHOD cl_alv_table_create=>create_dynamic_table
EXPORTING
it_fieldcatalog = ifc
IMPORTING
ep_table = dy_table.
ASSIGN dy_table->* TO <dyn_table>.
CREATE DATA dy_line LIKE LINE OF <dyn_table>.
ASSIGN dy_line->* TO <dyn_wa>.
CLEAR COND.
CONCATENATE key1 ' = ''' key1val '''' 'AND' INTO cond.
APPEND cond TO itab.
CLEAR COND.
CONCATENATE key2 ' = ''' key2val '''' INTO cond.
APPEND cond TO itab.
SELECT *
INTO <dyn_wa>
FROM (tabname)
WHERE (itab).
ENDSELECT.
IF sy-subrc <> 0.
WRITE / 'no this data in dbtab'.
EXIT.
ENDIF.
CLEAR COND.
CONCATENATE field2 ' = ''' yenideg1 '''' INTO cond.
UPDATE (tabname) SET (cond)
WHERE (itab).
IF sy-subrc EQ 0.
SELECT SINGLE * FROM (tabname) INTO <dyn_wa>
WHERE (itab).
WRITE / <dyn_wa>. "to test whether replacement is ok.
ENDIF.
you alse can use:
FM: VIEW_MAINTENANCE_CALL can used to do table maintenance.
note:
1.to do Table Maintenance Generator.
2.be authorized to to use tansaction sm30.
好运,
启明星 -
Deadlocks with simple UPDATE statement
I have in a C# program a dictionary and in SQL Server a stored procedure with a simple UPDATE statement. I process the dictionary in parallel. For each entry in my dictionary I call this stored procedure and I am getting deadlocks.
This is the UPDATE statement:
ALTER PROCEDURE [dbo].[UpdateImages]
@ICRTCode nvarchar(max),
@ICRTImage nvarchar(max)
AS
BEGIN
UPDATE Images SET processed = '1', Image = @ICRTImage, ProcessDate = GETDATE() WHERE IDICRT = @ICRTCode
END
Can someone give me a hint as to why this would cause deadlocks? There are no other processes writing to this table. This is a table in a staging database.http://blogs.msdn.com/bartd/archive/2006/09/09/747119.aspx
http://blogs.msdn.com/bartd/archive/2006/09/25/770928.aspx
Try change the statement a little bit
UPDATE Images SET processed = '1', Image = @ICRTImage, ProcessDate = GETDATE()
FROM
Images
WITH (TABLOCK) WHERE IDICRT = @ICRTCode
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
HELP! With parsing Update statement
I am stuck and need help! The teacher has not gone over parsing with us and it is not on his scheduled topics list. But, I am a person that likes to scope out and learn new things. For our final project, we have to allow updates, delete and inserts into the 5 main tables of the Premiere Products database. I have done everything except for the updates. I can achieve the updates of the entities by pretty much hardcoding them and that is okay by the teacher, but I want to learn about parsing because Barbara from this site mentioned this to me.
This is what I was able to write and I am getting errors:
CREATE OR REPLACE PROCEDURE updatecust_proc (
v_cust_num IN customera.cust_num%TYPE,
v_attributetoupdate VARCHAR2 ,
v_updatedvalue VARCHAR2 )
AS
e_invalidcustnum_error EXCEPTION;
BEGIN
v_isvalidcustnum := iscust(v_cust_num);
IF (v_isvalidcustnum = FALSE) THEN
RAISE e_invalidcustnum_error;
END IF;
PARSE(
'UPDATE customer
SET' | | v_attributetoupdate | | '=' | | v_updatedvalue | |
'WHERE cust_num =' | | v_cust_num
END;
EXCEPTION
WHEN e_invalidcustnum_error THEN
DBMS_OUTPUT.PUT_LINE('Cannot be updated. Invalid customer number');
END;
Any help would be useful. I went to the Oracle help site but their examples are a little too complicated for me to understand, plus, I am not using any C code.
Thanks in advance!
BobI will try putting in spaces to the areas that you mentioned to me. Thanks!
I will try to explain the function just in case some other poeple don't understand what I am trying to do.
This procedure is supposed to update the CUSTOMER entity. This entity has 7 attributes and I don't want to write out 7 UPDATE statements to changes a value. Instead, I want the name of the attribute to be passed to the proceudre so that the UPDATE statement can know which attribute to use. Barbara mentioned something about parsing and I attempted to try it out, but I am getting errors. Can someone help me with the procedure. BTW, function iscust() returns TRUE if the customer number is valid, otherwise, it returns false.
Thanks,
Bob -
Problem with CFQUERY update statement
I'm having trouble getting an SQL Update statement to work
correctly and I'm scratching my head as to why.
The output i get is the following:
Syntax error in UPDATE statement
SQLSTATE 42000
SQL UPDATE companies SET CompanyName = 'Insight Data Ltd',
Address1 = '5 Boulevard', Address2 = '', Address3 = '', City =
'Weston-super-Mare', County = 'North Somerset', Postcode =
'BS231NN', OfficeBranch = 'BR', contacttitle1 = 'Mr', contactname1
= 'Andrew', contactsurname1 = 'Scott', contactposition1 = 'Owner',
mail1 = 'yes', TelNumber = '01934 123456', TPS = 'no', FaxNumber =
'',FPS = 'no',MobileNumber = '',MPS = 'no',email =
'[email protected]', EPS = 'no', WebAddress = '
http://www.insightdata.co.uk',
contacttitle2 = 'Mr', contactname2 = 'David', contactsurname2 =
'Lewis', contactposition2 = 'Office Manager', mail2 = 'no',
contacttitle3 = 'Mr', contactname3 = '', contactsurname3 = '',
contactposition3 = 'Owner', mail3 = 'no', contacttitle4 = 'Mr',
contactname4 = '', contactsurname4 = '', contactposition4 =
'Owner', mail4 = 'no', wPVCUfab = 'yes', wALUinst = 'yes', WHERE
companyid = 33415
VENDORERRORCODE -3503
DATASOURCE idv6
I've checked that all the data fields are in the correct
format, and I can't see why I am getting a syntax error. Any help
on this would be appriciatedAgreed, but it looks like you already have the sql. Take the
query from the error message above and run it in your database.
Though I did notice have an extra comma between the last column and
there WHERE clause.
wALUinst = 'yes' , WHERE companyid = 33415
For the optional columns, put the commas first to prevent
errors due to trailing or too many commas
UPDATE Table
SET Column1 = 'value'
<cfif SomeValueExists>, Column2 = 'other value'
</cfif>
WHERE ID = 123
Two other things to consider: use cfqueryparam and consider
normalizing your table. Column names like Contact1, Contact2,
Contact3 ... are usually a sign its time to normalize. -
Unable to create updatable statement for MySQL?
The following code fragment prints 'Read only', even though the updatable flag is being set for the createStatement function. Can anyone give me an idea of what I am doing wrong here? I'm able to read stuff OK, but not update anything.
Connection conn = DriverManager.getConnection("jdbc:mysql:[removed]");
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String query = "select * from foo";
rs = stmt.executeQuery(query);
int concurrency = rs.getConcurrency();
if (concurrency == ResultSet.CONCUR_READ_ONLY)
System.out.println("Read only");
else
if (concurrency == ResultSet.CONCUR_UPDATABLE)
System.out.println("Updatable");
else
System.out.println("Unknown concurrency - " + concurrency);Not all databases support all the listed resultSetType and resultSetConcurrency values; usually, if you try to use an unsopported type, you still get a connection but it's type os downgraded.
You can usually find out if a type is supported by reading the documentation, or querying the database, using DataBaseMetaData.supportsResultSetConcurrency()
Sadly, the only thing in the MySQL documentation that I'm aware of on this topic is a note in the changelog for the 3.0.2-dev version of MySQL
- Fixed DBMD.supportsResultSetConcurrency() so that it returns true
for ResultSet.TYPE_SCROLL_INSENSITIVE and ResultSet.CONCUR_READ_ONLY or
ResultSet.CONCUR_UPDATABLEI did a quick search and might have missed something:
http://dev.mysql.com/doc/mysql/en/index.html
I suspect TYPE_SCROLL_SENSITIVE is not supported and your connection is being downgraded; you might try testing the DBMD to see what the database says is supported... -
Java.lang.NullPointerException with and update statement
Hello,
I'm getting this exception:
java.lang.NullPointerException
phaseone.AlbumModel.updateImageTrackerAlbums(AlbumModel.java:313)
phaseone.AlbumModel.processRequest(AlbumModel.java:228)
phaseone.AlbumModel.doGet(AlbumModel.java:522)
javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
I have an open method called before this one that connects me to the database. It works fine and have it working with a bunch of other methods but this one gives me this exception. i've even hard coded the variable 'user' and 'albumNumber' with information that exists in the database. i can't see where this logical error is coming from. I appreciate the help. I've been on this for 3 1/2 hour going blind. thanks!!
public boolean updateImageTrackerAlbums(String user, int albumNumber){
PreparedStatement pstmt = null;
boolean pass = false;
String query = "update imagetracker set totalalbums = ? where username = ?";
try{
pstmt = conn.prepareStatement(query);
pstmt.setInt(1, albumNumber);
pstmt.setString(2, user);
int x = pstmt.executeUpdate();
if (x >= 1){
pass = true;
}catch(SQLException e){
e.printStackTrace();
return pass;
}finally{
DBUtil.closePreparedStatment(pstmt);
return pass;
}code3 wrote:
The exception is pointing to this:
pstmt = conn.prepareStatement(query);
Do you understand anyway when a NullPointerException would be thrown? It will be thrown if you try to access/invoke an object reference which is actually null.
Connection conn = null;
pstmt = conn.prepareStatement(query); // Throws NPE because conn is null. -
PL/SQL cursor with FOR UPDATE STATEMENT
Welcome,
I have some troubles with cursors. When I try update values in table using cursor i receive ORA-01410 Error : "INVALID ROWID".
I use code as below:
ALTER SESSION SET CURRENT_SCHEMA=TEST_SCHEMA;
DECLARE
TYPE LogTable_typ IS TABLE OF ADMIN_FILE_LOG%ROWTYPE;
v_ModuleId KTIMS.ADMIN_FILE_LOG.MODULE_ID%TYPE;
v_CDR KTIMS.ADMIN_FILE_LOG.CDR_SUCCESS%TYPE;
CURSOR c1 IS
SELECT MODULE_ID, cdr_success FROM ADMIN_FILE_LOG
FOR UPDATE OF CDR_SUCCESS NOWAIT;
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO v_ModuleId,v_CDR;
IF v_ModuleId = 'LOAD' THEN
UPDATE ADMIN_FILE_LOG SET CDR_SUCCESS = 70 WHERE CURRENT OF c1;
END IF;
EXIT WHEN c1%NOTFOUND;
END LOOP;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM || SQLCODE);
END;
When I use ROWID in cursor declaration all works fine.Working code is:
ALTER SESSION SET CURRENT_SCHEMA=KTIMS;
DECLARE
TYPE LogTable_typ IS TABLE OF ADMIN_FILE_LOG%ROWTYPE;
v_ModuleId KTIMS.ADMIN_FILE_LOG.MODULE_ID%TYPE;
v_CDR KTIMS.ADMIN_FILE_LOG.CDR_SUCCESS%TYPE;
v_id ROWID;
CURSOR c1 IS
SELECT MODULE_ID, cdr_success, ROWID FROM ADMIN_FILE_LOG
FOR UPDATE OF CDR_SUCCESS NOWAIT;
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO v_ModuleId,v_CDR,v_id;
IF v_ModuleId = 'LOAD' THEN
UPDATE ADMIN_FILE_LOG SET CDR_SUCCESS = 70 WHERE ROWID = v_id;
END IF;
EXIT WHEN c1%NOTFOUND;
END LOOP;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM || SQLCODE);
END;
What is difference in this two cases ?
I try to find this in Oracle documentation "Database PL/SQL User's Guide and Reference" ( http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/sqloperations.htm#i45288 ).
Please help.Hi,
I think the USE of NOWAIT clause in cursor for update is, to remove the lock immediately after the transaction is over.
In the second example where you are fetching the rowid explicitly and use the same id in loop to make the update, so there should not be any problem in this case.
In the first example when you are using CURRENT OF to do the update, it is basically work on basis of latest fetched row from cursor and do the update (but i think implicitly it use the reference of row id also).
I am not sure about it , but still try once by removing the NOWAIT clause from your cursor for update and try once , see whether you are still facing the error or not. -
Immediate help required with this update statement
update holds set area = (select newarea from stagesteps)
where holds.stage= stagesteps.stagename and holds.step = stagesteps.STEPNAME and holds.area is not null
When I do this, it says stagesteps.stepame is an invalid name..
Any helps on this highly appreciated.. btw Advance thanx for your help.update holds h
set area = (select ss.newarea
from stagesteps ss
where ss.stagename = h.stage
and ss.stepname = h.step)
where area is not null
and exists (select null
from ss.newarea
from stagesteps ss
where ss.stagename = h.stage
and ss.stepname = h.step);You can leave off the EXISTS clause if there will be a guaranteed matching row in stagesteps for each row in holds, or if you don't care if area is set to null if there is no match. -
Can this be done with one update statement?
update test_tbl
set clob_col = replace(clob_col,str1,'')
where str1 is not null
and update_flag = 'F';
update test_tbl
set clob_col = replace(clob_col,str2,'')
where str2 is not null
and update_flag = 'F';
update test_tbl
set clob_col = replace(clob_col,str3,'')
where str3 is not null
and update_flag = 'F';
update test_tbl
set clob_col = replace(clob_col,str4,'')
where str4 is not null
and update_flag = 'F';
commit;Hi,
As stated in previous reply:
REPLACE ( char , search_string, replacement_string)
If search_string is null then char (the original) string will be returned.
This means you do not have to check on the search_string being null.
You may want to add to the where clause is any of the str1 .. str4 is not null.
update test_tbl
set
clob_col = replace(
replace(
replace(
replace(clob_col
,str1,'')
,str2,'')
,str3,'')
,str1,'')
where
update_flag = 'F'
and str1 || str2 || str3 || str4 is not null -- select only one of these
and COALESCE (str1, str2, str3, str4 ) is not null -- select only one of these
commit;Regards,
Peter -
Emergency: problem with update statement!
hello guys, i have a very serious problem with an update statement in pl/sql.
i had an application written in sybase, where i had the following update statement:
update mis_dik_adeia
set trexon_etos_days = days_per_year
from mis_dik_adeia, mis_plafon_adeivn
where mis_dik_adeia.adeia_id = mis_plafon_adeivn.adeia_id
and mis_dik_adeia.adeia_id between :aapo and :aews
and mis_dik_adeia.employee_id = :erg
and mis_dik_adeia.etos = :etos
and mis_plafon_adeivn.years_yphr = ( select max( a.years_yphr ) from mis_plafon_adeivn a where a.adeia_id = mis_plafon_adeivn.adeia_id and a.years_yphr <= :eth ) using sqlca;
This is working properly in sybase. When i copied this code in pl/sql it displayed me error and it's impossible to work. Then i thought to make a nested select statement like this:
update mis_dik_adeia
set trexon_etos_days = (select days_per_year
from mis_dik_adeia, mis_plafon_adeivn
where mis_dik_adeia.adeia_id = mis_plafon_adeivn.adeia_id
and mis_dik_adeia.adeia_id between aapo and aews
and mis_dik_adeia.employee_id = erg
and mis_dik_adeia.etos = etos1
and mis_plafon_adeivn.years_yphr = (
select max( a.years_yphr )
from mis_plafon_adeivn a
where a.adeia_id = mis_plafon_adeivn.adeia_id
and a.years_yphr <= eth )
but as you can understand, it is working, but it doesn't produce the same results as the update statement in Sybase!
It is very important for me to solve this problem , which is a very big trouble for me for a long time.
Please if anyone can help me i would appreciate it a lot!
Regards ,
Bill...Bill,
folowing the logic of your original query by Sybase
(it's embedded SQL in Power Builder, isn't it ?):
update mis_dik_adeia
set trexon_etos_days = (select days_per_year
from mis_plafon_adeivn
where mis_dik_adeia.adeia_id = mis_plafon_adeivn.adeia_id
and mis_plafon_adeivn.years_yphr = (
select max( a.years_yphr )
from mis_plafon_adeivn a
where a.adeia_id = mis_plafon_adeivn.adeia_id
and a.years_yphr <= eth )
where
mis_dik_adeia.adeia_id between aapo and aews
and mis_dik_adeia.employee_id = erg
and mis_dik_adeia.etos = etos1
and
exists (select 1
from mis_plafon_adeivn
where mis_dik_adeia.adeia_id = mis_plafon_adeivn.adeia_id
and mis_plafon_adeivn.years_yphr = (
select max( a.years_yphr )
from mis_plafon_adeivn a
where a.adeia_id = mis_plafon_adeivn.adeia_id
and a.years_yphr <= eth )
In 9i you can also try the following:
megre into mis_dik_adeia
using (
select
days_per_year,
mis_dik_adeia.rowid rid
from mis_dik_adeia, mis_plafon_adeivn
where mis_dik_adeia.adeia_id = mis_plafon_adeivn.adeia_id
mis_dik_adeia.adeia_id between aapo and aews
and mis_dik_adeia.employee_id = erg
and mis_dik_adeia.etos = etos1
and mis_plafon_adeivn.years_yphr =
(select max( a.years_yphr )
from mis_plafon_adeivn a
where a.adeia_id = mis_plafon_adeivn.adeia_id
and a.years_yphr <= eth)
) src
on (mis_dik_adeia.rowid = src.rid)
when matched then
update set mis_dik_adeia.trexon_etos_days = src.days_per_year
when not matched then
insert (mis_dik_adeia.adeia_id) values(0);
In 10G it can be easily:
megre into mis_dik_adeia
using (
select
days_per_year,
mis_dik_adeia.rowid rid
from mis_dik_adeia, mis_plafon_adeivn
where mis_dik_adeia.adeia_id = mis_plafon_adeivn.adeia_id
mis_dik_adeia.adeia_id between aapo and aews
and mis_dik_adeia.employee_id = erg
and mis_dik_adeia.etos = etos1
and mis_plafon_adeivn.years_yphr =
(select max( a.years_yphr )
from mis_plafon_adeivn a
where a.adeia_id = mis_plafon_adeivn.adeia_id
and a.years_yphr <= eth)
) src
on (mis_dik_adeia.rowid = src.rid)
when matched then
update set mis_dik_adeia.trexon_etos_days = src.days_per_year;
I have to notice I didn't check it carefully, so I can miss...
Rgds.
Corrected a mistake in the table name
Message was edited by:
dnikiforov -
Help with a update,select statement
Hi all please can you help me with a update statement i am struggling with.
I have 2 tables
Holiday and data
In the Holiday table i have columns for
Machine_ID NUMBER,
date_from DATE,
date_to DATE,
ID NUMBER
Machine column represents a type of machine, the two dates represent the start and end date of a holiday and ID represents the ID of the machines that the holiday effects (as you can have many machines that are the same, so the ID unique field to seperate them.
i.e.
996 25-DEC-08 00:00:00 27-DEC-08 00:00:00 91
996 25-DEC-08 00:00:00 27-DEC-08 00:00:00 92
100 28-DEC-08 00:00:00 29-DEC-08 00:00:00 1
100 28-DEC-08 00:00:00 29-DEC-08 00:00:00 2
In the data table i have the following columns:
DATE DATE
Machine NUMBER
SHIFT1S DATE
SHIFT1F DATE
SHIFT2S DATE
SHIFT2F DATE
CALS DATE
CALF DATE
CAP NUMBER
CALCAP NUMBER
total_hrs_up NUMBER
In here i have data for every date in the calendar. The machines are cross references with the machine in holidays table.
I run two shifts so have shift 1 start, finish. shift 2 start, finish. These are dates with times, so shift1s could be 01-01-08 09:00:00 shift1f could be 01-01-08 17:00:00.
shift2S could be 01-01-08 21:00:00 shift2f could be 01-01-08 23:59:00.
so that machine would be up between them hours of the day.
Other columns include
CALS, ,CALF = calendar start, finish, - This needs to be populated from the holiday table. currently null. So if the date is the 26 DEC and the machine is the same as what is in the holiday table then these two columns should be populated with them data
CAP is the total number of these machines i have available.
CALCAP is the no of machines the holiday affects -currently null
total_hrs_up is the number of hours this machine is up and running -currently null.
So what i need to do is populate the cals, calf calcap, total_hrs_up columns.
total_hrs_up is the important one, this needs to work out based on the two shift patterns the number of hours that the machine is available and then take off the holiday hours to give a final value.
so current data example in data is
date machine shifts shiftf shift2s shift2f cals, calf, cap, calcap, total_hrs
16-JUL-08 100 09:00:00 17:00:00 12:00:00 00:00:00 '','','',1 ,''
16-JUL-08 105 09:00:00 17:00:00 12:00:00 00:00:00 '','','',1 ,''
16-JUL-08 107 09:00:00 17:00:00 12:00:00 00:00:00 '','','',1 ,''
id like to see based on the holiday table if there is a holiday then this data is updated as such and a total_hrs machine is available populated on that date.
Any help is very much appreciated!
ThanksHi,
The following query does what you requested.
It makes the following assumptions:
(a) in data, shift1start <= shift1finish
(b) in holiday, hol_start <= hol_finish
(b) in data, the combination (machine, shift1start) is unique
(c) in holiday, hol_start <= hol_finish
(d) in holiday, rows for the same machine and id never have overlapping dates (including times). For example:
INSERT INTO holiday (machine, id, date_from, date_to)
VALUES (200, 1, '26-DEC-08 07:00:00', '26-DEC-08 09:59:59');
INSERT INTO holiday (machine, id, date_from, date_to)
VALUES (200, 1, '26-DEC-08 09:00:00', '26-DEC-08 09:59:59');will cause a probem. Multiple rows for the same machine and day are okay, however, if the times do not overlap, like the following:
INSERT INTO holiday (machine, id, date_from, date_to)
VALUES (200, 1, '26-DEC-08 07:00:00', '26-DEC-08 08:59:59');
INSERT INTO holiday (machine, id, date_from, date_to)
VALUES (200, 1, '26-DEC-08 09:00:00', '26-DEC-08 09:59:59');Here's the UPDATE statement:
UPDATE data m
SET ( hol_start
, hol_finish
, no_of_available_minutes
) =
( SELECT MIN (date_from)
, MAX (date_to)
, ( MAX (shift1finish - shift1start) -- Total from data
- ( NVL ( SUM ( LEAST (date_to, shift1finish)
- GREATEST (date_from, shift1start)
, 0
) -- Total from holiday
/ MAX (total_no_of_machines) -- Average
) * 24 * 60 -- Convert days to minutes
FROM data d
LEFT OUTER JOIN holiday h ON h.machine = d.machine
AND NOT ( date_from > shift1finish
OR date_to < shift1start
WHERE d.machine = m.machine
AND d.shift1start = m.shift1start
);The subquery has to use its own copy of data (that is, in needs d, not m), since the subquery has to return a non-NULL number of minutes when no rows in h match m. -
Update statement with CASE and banding
Hello Folks,
I am stuck and am going nowhere.
I have two tables
MinuteCategory
Minute
MinuteCategory
MinuteLookup
MinuteCategoryId (surrogate key)
MinuteLow
MinuteHigh
MinuteCategory
Sample from Minute Lookup table ..
1 1
15 <15 min
2 16
30 <30 min
3 31
45 <45 min
4 46
60 <60 minutes
5 61
75 <1 hour 15 minutes
I am trying to update the MinuteCategory column in the MinuteCategory table using the MinuteLookup table.
For example if the minute = 33 then the corresponding lookup value would be 3 (from the lookup table), because the
33rd minute falls in between 31 min and 45 min and the corresponding surrogate key is 3
Is this possible with an Update statement in SQL? The only thing i can think of is use case statement as the join key between
the two tables but i don't think it's going to work :(
UPDATE
SET MinuteCategory = ml.MinuteCategoryId
FROM MinuteCategory mc join MinuteLookup ml on mc.Minute =
CASE WHEN mc.Minute between ml.MinuteLow and ml.MinuteHigh THEN ml.MinuteCategoryId ELSE NULL
END
Would appreciate any help.
SSPlease post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums.
>> I have two tables <<
Have you read any book on data, so you have some idea what a “<something>_category” means? THINK!! A minute is unit of temporal measurement. By definition, it cannot be a category.
There is no such thing as a “<something>_category_id”; a data element is a “<something>_category” or a “<something>_id”, as per basic data modeling.
Use a table of time slots set to one more decimal second of precision than your data. You can now use temporal math to add it to a DATE to TIME(1) get a full DATETIME2(0). Here is the basic skeleton.
CREATE TABLE Timeslots
(slot_start_time TIME(1) NOT NULL PRIMARY KEY,
slot_end_time TIME(1) NOT NULL,
CHECK (start_time < end_time));
INSERT INTO Timeslots --15 min intervals
VALUES ('00:00:00.0', '00:14:59.9'),
('00:15:00.0', '00:29:59.9'),
('00:30:00.0', '00:44:59.9'),
('00:45:00.0', '01:00:59.9'),
('23:45:00.0', '23:59:59.9');
Here is the basic query for rounding down to a time slot.
SELECT CAST (@in_timestamp AS DATE), T.start_time
FROM Timeslots AS T
WHERE CAST (@in_timestamp AS TIME)
BETWEEN T.slot_start_time
AND T.slot_end_time;
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL
Maybe you are looking for
-
I am running Win7 home Premium 64bit SP1. When I start up in the morning usually the PC loads OK. However, often it hangs on the Windows screen and I have to reboot and sometimes it is OK and other times I have to go via the HP srart-up screen. This
-
HT204150 iCloud Contacts with iOS devices
I've tried each step under "Troubleshooting iCloud Contacts update or setup issues with iOS devices" several times to no avail. I can't get icloud to update Contacts on my iPhone 4. Any suggestions will be greatly appreciated.
-
My mum has bought me the Ipad 2 for christmas and i asked for the Ipad 3/4 and she bought it from comit and its now in liquidation. Is there any chance i can upgrade with apple i am happy to pay the difference.
-
Hi Experts I have a situation where a customer projects has two sale orders attached to the same project. - Sale order for the services - Sale order for the expense on the project The reason being is that the customer issues two separate purchase or
-
How to identify what columns are being suppressed
Hi, I have a database that may be masking some columns via a VPD. I'd like to identify the policies and the columns that are masking it. I have checked ALL_POLICIES (and DBA_POLICIES) but (I think) it doesnt show the columns that are being masked. Wh