Query regarding updating rows in JTable
Query regarding updating rows in JTable
Hello,
I have a JTable with 6 columns and 1000s of rows (which are data read from flat files)
I can select 1 or more rows and change the values of the
columns. each time I do this I need to update the values
in the flat file.
Currently I assign the updated Jtable values to a vector
Vector rowVector = (Vector)defaultModel.getDataVector();
then I iterate over the vector and compare the values with the (old) data
in the JTable.
for(int rowCount = 0; rowCount<rowVector.size(); rowCount++){
Vector v = (Vector)rowVector.elementAt(rowCount);
//smsList is the Vector that contains the old JTable values
for(int i=0; i<smsList.size(); i++){
//If colums values have been changed; add that
//vector value to another vector
selectedsmsList.add(smsList.get(i));
for(int i=0; i<selectedsmsList.size(); i++){
//Update the values in the flat file
}This works fine except that it takes ages to iterate over the updated vecor and un-updated,old vector; is there any way to directly get the list of rows that were updated in the jtable; so that I can directly do an I/O operation to update the jtablke values?
Just a suggestion.
You could add a listener and use a vector of booleans to keep track of the rows that have been changed. You could then iterate through this boolean vector and update the changed rows.
See
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#modelchange
Don't know whether this will be helpful.
Regards, Darryl
Similar Messages
-
Query regarding updation thru a Procedure
Hi,I have a query regarding updation.
1.I invoke a procedure in Oracle called submit thru my Java application.
The submit procedure saves the XML data in the database
and displays this data in a Front End GUI.
2. Now,I make a change in my Java application by adding new elements to the same row.This row now contains additional XML elements.
I would like to display the new row with the new elements in the GUI.
What is a better option for doing the above?
1.Delete the row being shown,save the new row with the changes in the database,and re display it?
2.Or,Update the row dynamically and refresh?
Any suggestions
Thanks,Hi,I have a query regarding updation.
1.I invoke a procedure in Oracle called submit thru
my Java application.
The submit procedure saves the XML data in the
database
and displays this data in a Front End GUI.
2. Now,I make a change in my Java application by
adding new elements to the same row.This row now
contains additional XML elements.
I would like to display the new row with the new
elements in the GUI.
What is a better option for doing the above?
1.Delete the row being shown,save the new row with
the changes in the database,and re display it?
2.Or,Update the row dynamically and refresh?
Any suggestions
Thanks,If you delete (it seems to me yours this process is regular and frequent) and re insert the new updated one record then High water mark will cause to scan yours table which may cause to degrade the performance.AFAIK you should go with update.But hold down dont implement it as i suggested lets see what are others solution here which may be more precious then mine.
Khurram -
Need help regarding updated rows
Dear sir,
need help on this query
how many rows got updated when i execute an update statementIf you are executing update statement from sqlplus session.
Make sure "feedback" is turned on. It'll show numbers of rows updated just after the command;
SQL> update tt1 set col1 = 1;
0 rows updated.
SQL> show feedback
FEEDBACK ON for 1 or more rows
SQL> set feedback off
SQL> update tt1 set col1 = 1;
SQL>Details about this sqlplus system setting:
FEED[BACK] {6|n|OFF|ON}
Display the number of records returned (when rows >= n )
OFF (or n=0) will turn the display off
ON will set n=1
Regards,
Ullhas -
Hello,
After using Bulk Collect & FORALL for updating rows in a table
How to find the total number of rows Affected (Updated) ...
please explain by an example..??Hi Aijaz,
If i'm correct you need to know the number of rows updated after the DML.
This might help.
-- Example Using the RETURNING Clause with a Record
DECLARE
TYPE setRec IS RECORD (key_name settings.settings_key%TYPE,
value_1 settings.settings_date_value%TYPE );
TYPE t_set_info IS TABLE OF setRec;
set_info t_set_info := t_set_info( NULL );
BEGIN
UPDATE settings SET settings_date_value = SYSDATE WHERE settings_key LIKE '%DATE%'
RETURNING settings_key, settings_date_value BULK COLLECT INTO set_info;
DBMS_OUTPUT.PUT_LINE('Total rows ' || set_info.COUNT );
ROLLBACK;
END;
/ -
Query regarding Update the data using application
I have scenario i need to update single record in the the application and insert into a table
for example
SELECT ContactID,FirstName,MiddleName,LastName,Description FROM Contact
Contact table contains 4 columns as explained. in the application there is one tab called Contact where it displays Above information
and description is non editable.
Now the new requirement has come user can update the description information and save information in a new column say 'Description1'
that means new column needs to be added in the db and also necessary changes needs to be done at the application side
For ex :SELECT ContactID,FirstName,MiddleName,LastName,Description,Description1 FROM Contact
Now when user views the contact table it should display description info by default from 'description' table.
If he edits he should see edited data from 'description1' table.
Can any body guide me please and send me sample update query please, and the logic should if updated data is there display that data from
'description1' table other wise display from 'description' table
Smash126Hi Smash126,
You need to fire the update command once you have filled the description record. It should happen on the primary key column of the record.
For Example:
UPDATE Contact
SET Description = 'New Description',
Description1 = 'New Description'
where contactID = <<ContactID from application>>
This way both will updated to same value, and next time you will get the updated value.
Here is some ADO.Net links:
http://www.codeproject.com/Articles/1155/Simple-ADO-NET-Database-Read-Insert-Update-and-Del
http://www.onlinebuff.com/article_step-by-step-select-insert-update-and-delete-using-aspnet-c-and-adonet_32.html
Regards Harsh -
Query Regarding Updation/Migration of ODI 10g To ODI 11g.
Hi All,
Currently I am using ODI 10g Version & Repositories ( Work & Master) have been installed on Oracle database version "Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi"
We are thinking to migrate from ODI 10g to ODI 11g Version 11.1.1.5 & i have some queries which are metioned below.
1. Can we install ODI 11g Version 11.1.1.5 version with Repositories ( Work & Master) on Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi" or do i need to upgrade my database version to 11G?.
2. If yes then, Can i upgrade or use exting Repositoires ( 10g one) for ODI 11g OR i have to create new Repositoires & move/migrate the objects of 10G repositories as mentioned in the Oracle installation doc.
3. Currently I am using OBIEE 10g for reposrting purpose & if i switch to ODI 11g , Do i need to use OBIEE 11g?
ODI gurus, I need your reponse ASAP & i have to share it on urgent basis.
Thanks
Edited by: neeraj_singh on May 15, 2013 9:58 PMneeraj_singh wrote:
Hi All,
Currently I am using ODI 10g Version & Repositories ( Work & Master) have been installed on Oracle database version "Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi"
We are thinking to migrate from ODI 10g to ODI 11g Version 11.1.1.5 & i have some queries which are metioned below.
1. Can we install ODI 11g Version 11.1.1.5 version with Repositories ( Work & Master) on Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi" or do i need to upgrade my database version to 11G?.You can install ODI 11.1.1.5 but you have to upgrade your repositories using upgrade assistant
refer http://docs.oracle.com/cd/E23943_01/upgrade.1111/e12642/tasklist.htm#CIHGIDFG
2. If yes then, Can i upgrade or use exting Repositoires ( 10g one) for ODI 11g OR i have to create new Repositoires & move/migrate the objects of 10G repositories as mentioned in the Oracle installation doc.No need to create new repositories. You just upgrade them. But you need to takecare of certain things as you are a 10g user. Refer below link for the prerequisite
http://docs.oracle.com/cd/E23943_01/upgrade.1111/e12642/prevusers.htm
3. Currently I am using OBIEE 10g for reposrting purpose & if i switch to ODI 11g , Do i need to use OBIEE 11g?Not clear about the question ?
>
ODI gurus, I need your reponse ASAP & i have to share it on urgent basis.
Thanks
Edited by: neeraj_singh on May 15, 2013 9:58 PM -
How can i update rows in a table based on a match from a select query
Hello
How can i update rows in a table based on a match from a select query fron two other tables with a update using sqlplus ?
Thanks Glenn
table1
attribute1 varchar2 (10)
attribute2 varchar2 (10)
processed varchar2 (10)
table2
attribute1 varchar2 (10)
table3
attribute2 varchar2 (10)
An example:
set table1.processed = "Y"
where (table1.attribute1 = table2.attribute1)
and (table1.attribute2 = table3.attribute2)Hi,
Etbin wrote:
Hi, Frank
taking nulls into account, what if some attributes are null ;) then the query should look like
NOT TESTED !
update table1 t1
set processed = 'Y'
where exists(select null
from table2
where lnnvl(attribute1 != t1.attribute1)
and exists(select null
from table3
where lnnvl(attribute2 != t1.attribute2)
and processed != 'Y'Regards
EtbinYes, you could do that. OP specifically requested something else:
wgdoig wrote:
set table1.processed = "Y"
where (table1.attribute1 = table2.attribute1)
and (table1.attribute2 = table3.attribute2)This WHERE clause won't be TRUE if any of the 4 attribute columns are NULL. It's debatable about what should be done when those columns are NULL.
But there is no argument about what needs to be done when processed is NULL.
OP didn't specifically say that the UPDATEshould or shouldn't be done on rows where processed was already 'Y'. You (quite rightly) introduced a condition that would prevent redo from being generated and triggers from firing unnecessarily; I'm just saying that we have to be careful that the same condition doesn't keep the row from being UPDATEd when it is necessary. -
Is there a way to create tables that can't update rows
Hi
I have an application where security is very importante. I have tables that con only be inserted and queried, not updated or deleted. Is there a way I can tell Oracle to prohibit update and delete on that table.
Regards,
Néstor Boscán> Is there a way I can tell Oracle to prohibit update and delete on that table.
Yes. Quite easy in fact. It is called FGAC - Fine Grained Access Control.
You create a FGAC function for those tables. These simply returns 1=2 to be added to an UPDATE or DELETE statement's predicate.
Example:
SQL> -- am able to delete from emp
SQL> delete from emp;
17 rows deleted.
SQL> rollback;
Rollback complete.
SQL>
SQL> -- create policy FGAC function
SQL> create or replace function vpdbPolicy( schema varchar2, object varchar2 ) return varchar2 is
2 begin
3 return( '1=2' );
4 end;
5 /
Function created.
SQL>
SQL> -- create FGAC policy
SQL> begin
2 DBMS_RLS.add_policy(
3 object_schema => USER,
4 function_schema => USER,
5 object_name => 'emp',
6 policy_name => 'PROTECT_EMP',
7 policy_function => 'vpdbPolicy',
8 update_check => FALSE,
9 statement_types => 'UPDATE DELETE'
10 );
11 end;
12 /
PL/SQL procedure successfully completed.
SQL>
SQL> -- no longer able to delete from emp
SQL> delete from emp;
0 rows deleted.
SQL> rollback;
Rollback complete.
SQL> -
How to update row by row in Jdbc Adapter sender ?
Hi friends ,
No i am reading data from a table using select query and resulting data i am keeping in the FTP folder as XML File.
I want to
1. to know how many rows i read ?
2. Update the read completed time in each row of the sender side table .
( I am using <b>select * from a table where tag='n' </b> . I am giving this in <b>Query SQL Statement</b> of JDBC Sender adapter processing parameter .
I am writing update query as update table set tag='y' where tag='n' .
Will it perform row by row ?
3. Insert in to another R3 System table the rows which i read as a log .
Can you please give procedure to do that .
Expecting your reply asap .
Thank you
Best Regards.,
V.RangarajanHi raj ,
Thanks for ur reply . I am new to xi . Just i am doing a scenario . I can able to read the ms-sql server table data using jdbc Sender adapter .
Can i use RFC Adapter to insert the values to R3 table ?
If i have mapped to rfc fields will it store into the table once we read the data from ms_sql server table using select query of JDBC Sender Adapter ?
Best Regards
V.Rangarajan -
Regarding Update querry at JDBC Sender adapter
Dear all
need you help for this requirement
My Select statement is working fine where flag column has some time null value
below is the Select statement and ( EMP_MAXQTY_AUTH_FLAG is Flag field here & EMPLOYEE_MST is table name)
SELECT EMP_ORG_CD,EMP_CD,EMP_NAME,EMP_STATUS,EMP_MAXQTY_AUTH_FLAG FROM EMPLOYEE_MST WHERE EMP_MAXQTY_AUTH_FLAG<>'Y'or EMP_MAXQTY_AUTH_FLAG is null
but update querry is as given below
UPDATE EMPLOYEE_MST SET EMP_MAXQTY_AUTH_FLAG='Y' WHERE ((EMP_MAXQTY_AUTH_FLAG <>'Y') OR (EMP_MAXQTY_AUTH_FLAG is NULL))
Please suggest the exact query
if Flag row ahs some value any thing it is updating , but when there is NULL value ,
problem is coming
Please help.....
Regards
PriyaHi Priya,
I think it is the mistake in query:
SELECT EMP_ORG_CD,EMP_CD,EMP_NAME,EMP_STATUS,EMP_MAXQTY_AUTH_FLAG FROM EMPLOYEE_MST WHERE EMP_MAXQTY_AUTH_FLAG'Y'or EMP_MAXQTY_AUTH_FLAG is null
means select all record whose *EMP_MAXQTY_AUTH_FLAG is 'Y' or Null *
UPDATE EMPLOYEE_MST SET EMP_MAXQTY_AUTH_FLAG='Y' WHERE ((EMP_MAXQTY_AUTH_FLAG 'Y') OR (EMP_MAXQTY_AUTH_FLAG = ' '))
means update those records where *EMP_MAXQTY_AUTH_FLAG is 'Y' or Null * and the new value to be updated is 'Y'
Change your update query to
UPDATE EMPLOYEE_MST SET EMP_MAXQTY_AUTH_FLAG='D' WHERE ((EMP_MAXQTY_AUTH_FLAG 'Y') OR (EMP_MAXQTY_AUTH_FLAG = ' '))
Regards
Suraj -
[Excel] Running a SQL Query to delete rows
Hello Experts,
Background: I am attempting to use a dba of my companies time keeping system and implement it with Power BI tools. Given the file size restrictions within Power Bi itself I need to lower my file size by removing all time logs from
inactive employees.
I have a question regarding whether or not you can use a sql query to delete rows in excel. I have roughly 200,000+ rows in my excel spreadsheet. I am attempting to delete all rows where an employee equals inactive. I have attempted to
delete these rows by sorting them and doing a bulk delete and clear contents, but it seems to crash my excel every time. My thought process is that using a query that does a timed delete might put less of a burden on deleting the massive amount of data.
I would like to use this: DELETE * FROM [Table_(...)_Actual$] WHERE [Current] = "Inactive" (Will add more once I know it is possible to use sql queries in Excel.
Any information on whether or not this is possible would be appreciated.
Regards,
LinkRunning SQL Query in Excel is possible, however, the delete query is not supported in Excel.
You are more restricted in deleting Excel data than data from a relational data source. In a relational database, "row" has no meaning or existence apart from "record"; in an Excel worksheet, this is not true. You can delete values
in fields (cells). Please see:http://support.microsoft.com/kb/257819/en-us
One workaround : Use update query to set the rows as null, then use select query.
e.g.
SQL = "update [sheet2$A1:B5] set name=null,age=null where name='andy'"
cnn.Execute SQL
SQL = "select name,age from [sheet2$A1:B5] where name is not null"
Wind Zhang
TechNet Community Support -
Hi all,
I am trying to update database from Jtable. I added Jtable to scrollpane .
My question is..
after updating the Jtable..I want to save the details to database..when I click save button on my screen...how to do that? Please help me out! Thanks in advance..
Here is the code that I wrote...
public class VasuTest extends JFrame {
private boolean DEBUG = true;
Vector column_list = new Vector();
Vector rows = new Vector();
public VasuTest() {
super("VasuTest");
JToolBar toolBar = new JToolBar();
JButton button = null;
button = new JButton("Send Email");
button.setToolTipText("This is the Exit button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Send Email");
toolBar.add(button);
button = new JButton("Save");
button.setToolTipText("This is the Save button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Save");
toolBar.add(button);
button = new JButton("Exit");
button.setToolTipText("This is the Exit button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
toolBar.add(button);
JPanel ContentPane = new JPanel();
ImageIcon i1 = new ImageIcon("Dongle.gif");
JLabel j1 = new JLabel( i1, JLabel.CENTER);
ContentPane.add(j1,BorderLayout.CENTER);
setContentPane(ContentPane);
JDBCT myModel = new JDBCT();
String q = "select a.email_no,a.email_ln_no,b.cust_no,null customer_name,null cdate,a.batch_no,b.purch_ord_no,a.user_part_no,null part_desc,a.user_upgraded_part_no,null prod_id,a.qty,a.price,a.encrypted_sum_id,a.decrypted_sum_id,a.approval_key,a.status_cd,decode(a.status_cd,'APPROVED','true','ERROR','false','PROCESSED','true') approved,null end_cust,null sales_ord,null so_line,null sales_ord_cust,null shipment ,null sales_end_cust_name ,null shipment_line,a.note,null fromcust from upgrade_req_key_s3 a,upgrade_req_s3 b where a.email_no = b.email_no order by a.email_no,a.email_ln_no";
myModel.setQuery();
final Font f = new Font("SansSerif", Font.BOLD, 10);
JTable table = new JTable(myModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// Container ContentPane = getContentPane();
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
JScrollPane scrollPane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize ( new Dimension ( 770, 400 ) );
ContentPane.add(toolBar,BorderLayout.CENTER);
//Add the scroll pane to this window.
ContentPane.add(scrollPane,BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
public class JDBCT extends AbstractTableModel {
Vector cache; // will hold String[] objects...
int colCount;
int rowHeight;
String [] headers;
Connection db;
Connection conn;
Statement statement;
String currentURL;
// public QueryTableModel() {
// cache = new Vector();
// new oracle.jdbc.driver.OracleDriver();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
System.exit(-1);
String url = "jdbc:odbc:c3-erp,s3,s3";
public String getColumnName(int i) {
if (i == 0) { return "Email No" ; } else
if (i == 1) { return "Email Line No.";} else
if (i == 2) { return "Customer";} else
if (i == 3) { return "Customer Name";} else
if (i == 4) { return "Date";} else
if (i == 5) { return "Batch No";} else
if (i == 6) { return "Customer PO";} else
if (i == 7) { return "Upgrade From Part";} else
if (i == 8) { return "Part Description";} else
if (i == 9) { return "Upgrade To Part";} else
if (i == 10) { return "Product Id";} else
if (i == 11) { return "Quantity";} else
if (i == 12) { return "Price";} else
if (i == 13) { return "Encypted Sum ID";} else
if (i == 14) { return "Decrypted Serial No";} else
if (i == 15) { return "Key";} else
if (i == 16) { return "Status";} else
if (i == 17) { return "Approved";} else
if (i == 18) { return "End Customer";} else
if (i == 19) { return "Sales Order";} else
if (i == 20) { return "SO Line";} else
if (i == 21) { return "Sales Order End Customer";} else
if (i == 22) { return "Sales Order End Customer Name";} else
if (i == 23) { return "Shipment";} else
if (i == 24) { return "Shipment Line";} else
if (i == 25) { return "Errors";} else
if (i == 26) { return "From"; }
else {return headers[i-1] ;}
public int getColumnCount() { return colCount; }
public int getRowCount() { return cache.size(); }
//public Class getColumnClass(int c) {
// return getValueAt(0, c).getClass();
// overloaded isCellEditable method so that it returns true
// in reference to a cell being editable.
public boolean isCellEditable(int row, int col) { return true; }
// overloaded setValyeAt which updates the data Vector and
// calls the fireTableRowsUpdated() to notify any listeners
// that data has changed and they need to redraw.
public void setValueAt(Object value, int row, int col) {
((String[])cache.elementAt(row))[col] = (String)value;
fireTableRowsUpdated(row,row);
public void getInfo () {
System.out.println("Row Count is : " + cache.size());
System.out.println("Value at 0,0 is : " + getValueAt(0,0));
// boolean res = isCellEditable(0,0);
// System.out.println("The value of the Boolean result is : " + res);
public Object getValueAt(int row, int col) {
return ((String[])cache.elementAt(row))[col];
// All the real work happens here!
// In a real application, we'd probably perform the query in a separate thread.
public void setQuery() {
cache = new Vector();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection ("jdbc:odbc:c3-erp","s3","s3");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select a.email_no,a.email_ln_no,b.cust_no,null customer_name,null cdate,a.batch_no,b.purch_ord_no,a.user_part_no,null part_desc,a.user_upgraded_part_no,null prod_id,a.qty,a.price,a.encrypted_sum_id,a.decrypted_sum_id,a.approval_key,a.status_cd,decode(a.status_cd,'APPROVED','true','ERROR','false','PROCESSED','true') approved,null end_cust,null sales_ord,null so_line,null sales_ord_cust,null shipment ,null sales_end_cust_name ,null shipment_line,a.note,null fromcust from upgrade_req_key_s3 a,upgrade_req_s3 b where a.email_no = b.email_no order by a.email_no,a.email_ln_no");
ResultSetMetaData meta = rs.getMetaData();
colCount = meta.getColumnCount();
String[] record = new String[27];
// Now we must rebuild the headers array with the new column name
headers = new String[27];
for (int h=0; h < 27; h++) {
// headers[h-1] = meta.getColumnName(h);
headers[h] = getColumnName(h);
// and file the cache with the record from our query. This would
// be practical if we were expecting a few million records to our
// response query, but we are not so we can do this.
while(rs.next()) {
for (int i=0; i < colCount; i++) {
record[i] = rs.getString(i + 1);
cache.addElement(record);
// Get the FIRST column of the table tableView
// TableColumn column0 = table.getColumn(cache.elementAt(0));
// Set the cell editor as non editable.
// column0.setCellEditor(new EditableCellEditor(new JComboBox(), true));
fireTableChanged(null); // notify everyone the we had a new table.
catch (Exception e) {
cache = new Vector(); // blank it out and keep going.
e.printStackTrace();
public static void main(String[] args) {
VasuTest frame = new VasuTest();
frame.pack();
frame.setVisible(true);
}When you click on the save button, you need to go through the model and retrieve the values getValueAt().
Convert to whatever type you want since getValueAt() returns type Object and update the DB. -
There was an error while updating row count for "SH".."SH".CHANNELS
Hi All,
Am new to OBIEE.Pls help in this regard.
Am building the physical layer as per Repository guide.When am importing the data in to this,am getting the below error.
*"There was an error while updating row count for "SH".."SH".CHANNELS" :"*
channles is the table name and having 5 rows.
but am able to see the data in the sql prompt. like SELECT * FROM SH.CHANNELS then 5 rows data would be displaying..
pls help in this regard and where is the excat problem?
Thanks,what is the error?
Make sure that your connection pool settings are okay..
Make sure that, you are using correct driver in case of if you are using ODBC dsn..
Also make sure that, your oracle server is running... TNS and Oracle server services -
Cursor and Update rows based on value/date
SQL Server 2012
Microsoft SQL Server Management Studio
11.0.3128.0
Microsoft Analysis Services Client Tools
11.0.3128.0
Microsoft Data Access Components (MDAC)
6.1.7601.17514
Microsoft MSXML 3.0 4.0 5.0 6.0
Microsoft Internet Explorer
9.11.9600.16518
Microsoft .NET Framework
4.0.30319.18408
Operating System
6.1.7601
The objective of this is to test the Cursor and use it on a production environment after this is fixed. What I would like to do is update rows in a column i duplicated originally called 'HiredDate' from AdventureWorks2012 HumanResources.Employee table. I
made a duplicate column called 'DateToChange' and would like to change it based on a date I have picked, which returns normally 2 results (i.e. date is '04/07/2003'). The code runs but will not change both dates. It did run however with an error but changed
only 1 of the 2 rows because it said ['nothing available in next fetch'].
The code to add the columns and perform the query to get the results I am running this against:
-- ADD column 'DateToChange'
ALTER TABLE [HumanResources].[Employee] ADD DateToChange Date NOT NULL;
-- Copy 'HireDate' data to 'DateToChange'
UPDATE HumanResources.Employee SET DateToChange = HireDate;
-- Change 'DateToChange' to NOT NULL
ALTER TABLE [HumanResources].[Employee] ALTER COLUMN DateToChange Date NOT NULL;
SELECT BusinessEntityID,HireDate, CONVERT( char(10),[DateToChange],101) AS [Formatted Hire Date]
FROM HumanResources.Employee
WHERE [DateToChange] = '04/07/2003';
Code:
USE AdventureWorks2012;
GO
-- Holds output of the CURSOR
DECLARE @EmployeeID INT
DECLARE @HiredDate DATETIME
DECLARE @HiredModified DATETIME
DECLARE @ChangeDateTo DATETIME
--Declare cursor
-- SCROLL CURSOR ALLOWS "for extra options" to pul multiple records: i.e. PRIOR, ABSOLUTE ##, RELATIVE ##
DECLARE TestCursor CURSOR SCROLL FOR
-- SELECT statement of what records going to be used by CURSOR
-- Assign the query to the cursor.
SELECT /*HumanResources.Employee.BusinessEntityID, HumanResources.Employee.HireDate,*/ CONVERT( char(10),[DateToChange],101) AS [Formatted Hire Date]
FROM HumanResources.Employee
WHERE DateToChange = '01/01/1901'
/*ORDER BY HireDate DESC*/ FOR UPDATE OF [DateToChange];
-- Initiate CURSOR and load records
OPEN TestCursor
-- Get first row from query
FETCH NEXT FROM TestCursor
INTO @HiredModified
-- Logic to tell the Cursor while "@@FETCH_STATUS" 0 the cursor has successfully fetched the next record.
WHILE (@@FETCH_STATUS = 0 AND @@CURSOR_ROWS = -1)
BEGIN
FETCH NEXT FROM TestCursor
IF (@HiredModified = '04/07/2003')/*05/18/2006*/
-- Sets @HiredModifiedDate data to use for the change
SELECT @ChangeDateTo = '01/01/1901'
UPDATE HumanResources.Employee
SET [DateToChange] = @ChangeDateTo --'01/01/1901'
FROM HumanResources.Employee
WHERE CURRENT OF TestCursor;
END
-- CLOSE CURSOR
CLOSE TestCursor;
-- Remove any references held by cursor
DEALLOCATE TestCursor;
GO
This query is run successfully but it does not produce the desired results to change the dates
04/07/2003 to 01/01/1901.
I would like the query to essentially be able to run the initial select statement, and then update and iterate through the returned results while replacing the necessary column in each row.
I am also open to changes or a different design all together.
For this query I need:
1. To narrow the initial set of information
2. Check if the information returned, in particular a date, is before [i.e. this current month minus 12 months or
12 months before current month]
3. Next replace the dates with the needed date
[Haven't written this out yet but it will need to be done]
4. After all this is done I will then need to update a column on each row:
if the 'date' is within 12 months to 12 months from the date checked
NOTE: I am new to TSQL and have only been doing this for a few days, but I will understand or read up on what is explained if given enough information. Thank you in advance for anyone who may be able to help.The first thing you need to do is forget about cursors. Those are rarely needed. Instead you need to learn the basics of the tsql language and how to work with data in sets. For starters, your looping logic is incorrect. You open
the cursur and immediately fetch the first row. You enter the loop and the first thing in the loop does what? Fetches another row. That means you have "lost" the values from the first row fetched. You also do not test the success of
that fetch but immediately try to use the fetched value. In addition, your cursor includes the condition "DateToChange = '01/01/1901' " - by extension you only select rows where HireDate is Jan 1 1901. So the value fetched into @HiredModified will
never be anything different - it will always be Jan 1 1901. The IF logic inside your loop will always evaluate to FALSE.
But forget all that. In words, tell us what you are trying to do. It seems that you intend to add a new column to a table - one that is not null (ultimately) and is set to a particular value based on some criteria. Since you intend the
column to be not null, it is simpler to just add the column as not null with a default. Because you are adding the column, the assumption is that you need to set the appropriate value for EVERY row in the table so the actual default value can be anything.
Given the bogosity of the 1/1/1901 value, why not use this as your default and then set the column based on the Hiredate afterwards. Simply follow the alter table statement with an update statement. I don't really understand what your logic
or goal is, but perhaps that will come with a better description. In short:
alter table xxx add DateToChange date default '19010101'
update xxx set DateToChange = HireDate where [some unclear condition]
Lastly, you should consider wrapping everything you do in a transaction so that you recover from any errors. In a production system, you should consider making a backup immediately before you do anything - strongly consider and have a good reason not
to do so if that is your choice (and have a recovery plan just in case). -
Query regarding the data type for fetcing records from multiple ODS tables
hey guys;
i have a query regarding the data type for fetcing records from multiple ODS tables.
if i have 2 table with a same column name then in the datatype under parent row node i cant add 2 nodes with the same name.
can any one help with some suggestion.Hi Mudit,
One option would be to go as mentioned by Padamja , prefxing the table name to the column name or another would be to use the AS keyoword in your SQL statement.
AS is used to rename the column name when data is being selected from your DB.
So, the query Select ename as empname from emptable will return the data with column name as empname.
Regards,
Bhavesh
Maybe you are looking for
-
How to copy characteristic values from Purchase Order to MIGO Goods Receipt
Dear all, I have a configurable material X, then i create a purchase order for that material and then i input characteristic value in the Purchase Order transaction and save it However when i do the Goods Receipt transaction via MIGO and using the Pu
-
I backed up everything to icloud, wiped my phone, synced to that backup, and only some of my photos are there. How do I get those photos back? I went to apple store and they walked me through this except for the syncing part. I went to sync everythin
-
Do I have to send my old computer bottom back to apple with the prodct replament program?
Do I have to send my old bottom back from my macbook to apple if I got the new one shipped to me from the product replacement program? The shipping label sent with it said there would be no charge if I didn't send it back but also the booklet inside
-
Permissions not being inherited to subfolders
I have recently formatted a 1TB WD drive in Mac OS Extended (Journaled) format. The pemissions are set to read + write for all users on the root of the drive. However when i create a new folder it does not inherit the same permissions! The drive will
-
HT1541 am i able to buy books on i tunes for my kindle
am i able to buy books on i tunes for my kindle