Using UPDATE in complex SQL
I wonder if anyone can help with an update..
Image 2 tables: packagetable and parttable
packagetable has component to part relationships, eg:
Package Part
PACK1 PART1
PACK1 PART2
PACK2 PART6
PACK2 PART7
PACK2 PART9
PACK3 PART3
PACK3 PART7
parttable has parts and their price
Part Price
PART1 10
PART2 8
PART3 15
PART6 1
PART7 5
PART9 10
but packages are also stored here as parts and have a price (total of components)
PACK1 18 (10 + 8)
PACK2 16 (1 + 5 + 10)
PACK3 20 (15 + 5)
The actual tables are more complex and include a site, a discount, a qty per package, etc but you get the gist.
I need to update package parts so that they equate to the total of their parts because some package parts have the wrong price.
So I need to say
PACK1 = price of PART1 + price of PART2
PACK2 = price of PART6 + price of PART7 + price of PART9
PACK3 = price of PART3 + price of PART7
The actual SQL to obtain the resultant price is:
select
spp1.parent_part packpart,
(select sp2.list_price from ifsapp.sales_part sp2 where sp2.catalog_no = spp1.parent_part) Current_price,
sum((sp1.list_price - (round(sp1.list_price*(spp1.discount_perc/100),2))) * spp1.qty_per_assembly) Proposed_price
from
ifsapp.sales_part_package spp1,
ifsapp.sales_part sp1
where
spp1.catalog_no=sp1.catalog_no
and
spp1.contract=sp1.contract
and
spp1.contract='OIAMN'
having
sum((sp1.list_price - (round(sp1.list_price*(spp1.discount_perc/100),2))) * spp1.qty_per_assembly)<9999999
group by
spp1.parent_part
This results in this case are:
Package Part Current Proposed
123 0.00 4911.90
124 0.00 23450.00
126 0.00 23450.00
128 0.00 23950.00
133 0.00 26975.00
134 1200.00 1249.86
140 0.00 9995.00
144 0.00 9995.00
145 0.00 8995.00
150 9021.00 9994.97
151 0.00 9994.97
152 0.00 8994.97
155 0.00 17895.00
168 0.00 17095.00
Clealry the only two values I really need are Package Part and Proposed value... but how can I update the package part prices using a single SQL statement?
If I interpret your question right,
merge works for you in 9i and 10G:
SQL> select * from emps;
ENAME DEPTNO SSAL
SMITH 20
ALLEN 30
WARD 30
JONES 20
MARTIN 30
BLAKE 30
CLARK 10
SCOTT 20
KING 10
TURNER 30
ADAMS 20
JAMES 30
FORD 20
MILLER 10
14 rows selected.
SQL> select * from sals;
ENAME SAL
SMITH 1000
ALLEN 1800
WARD 1450
JONES 2975
MARTIN 1250
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
TURNER 1500
ADAMS 1100
JAMES 1120
FORD 3000
MILLER 1300
14 rows selected.
SQL> /* In 9i */
SQL> merge into emps
2 using (
3 select e.deptno,sum(s.sal) sm from emps e, sals s
4 where e.ename = s.ename
5 group by e.deptno
6 ) src
7 on (src.deptno = emps.deptno)
8 when matched then
9 update set emps.ssal = src.sm
10 when not matched then
11 insert (emps.deptno) values(0)
12 /
14 rows merged.
SQL>/* In 10G */
SQL> merge into emps
2 using (
3 select e.deptno,sum(s.sal) sm from emps e, sals s
4 where e.ename = s.ename
5 group by e.deptno
6 ) src
7 on (src.deptno = emps.deptno)
8 when matched then
9 update set emps.ssal = src.sm
10 /
14 rows merged.
SQL> select * from emps order by deptno;
ENAME DEPTNO SSAL
CLARK 10 8750
KING 10 8750
MILLER 10 8750
SMITH 20 11075
ADAMS 20 11075
FORD 20 11075
SCOTT 20 11075
JONES 20 11075
ALLEN 30 9970
BLAKE 30 9970
MARTIN 30 9970
JAMES 30 9970
TURNER 30 9970
WARD 30 9970
14 rows selected.But it could be better if you changed the structure you were using - you could
pick out package names and price summary in the separate table -
now you packagetable looks as the unnormalized structure which is overloaded
by data.
Rgds.
Similar Messages
-
SQL Bulk Update using Update query in SQL Table
Hello All,
I want to update data in sql table depends on some condition.
I am getting excel sheet from client and want to change value of field say Status = c.
Client is sending excel sheet with 300 field and want to change value for all 300 records with unique fields (field1 and field2) comming in that excel sheet...
How can i write and update records as Bulk.
Instaed updating one one recors ?
Example ( Update Table_Name Set Status = 'c' Where Field1 = Value from Excel for Field1 and
Field2 = Value from Excel for Field2 )
Same needs to do for 300 records...
Any help will wellcome.
Thanks,
Nilesh....
Thanks and Regards, Nilesh Thakur.you can use OPENROWSET for that
http://www.mssqltips.com/sqlservertip/1540/insert-update-or-delete-data-in-sql-server-from-excel/
Another way is to use SSIS with data flow task having Excel source connecting to excel and using OLEDB command to update rows in table using it. You may also use staging table to get data from excel and later use it inexecute sql task to update your table
to make update set based which would be faster.
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
How to use update trigger in sql server 2008 with specific column
Hello friends currently my trigger updates on table update, and I need to change this to only fire when specific column changes.
/****** Object: Table [dbo].[User_Detail] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[User_Detail](
[sno] [int] IDENTITY(1,1) NOT NULL,
[userid] [nvarchar](50) NULL,
[name] [nvarchar](max) NULL,
[jointype] [nvarchar](50) NULL,
[joinside] [nvarchar](50) NULL,
[lleg] [nvarchar](50) NULL,
[rleg] [nvarchar](50) NULL,
[ljoining] [int] NULL,
[rjoining] [int] NULL,
[pair] [int] NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[User_Detail] table data ******/
SET IDENTITY_INSERT [dbo].[User_Detail] ON
INSERT [dbo].[User_Detail] values (1, N'LDS', N'LDS Rajput', N'free', N'Left', N'jyoti123', N'SUNIL', 6, 4, 4)
INSERT [dbo].[User_Detail] VALUES (2, N'jyoti123', N'jyoti rajput', N'free', N'Left', N'mhesh123', N'priya123', 3, 2, 2)
SET IDENTITY_INSERT [dbo].[User_Detail] OFF
/****** Object: Table [dbo].[User_Detail] trigger ******/
CREATE TRIGGER triggAfterUpdate ON User_Detail
FOR UPDATE
AS
declare @userid nvarchar(50);
declare @pair varchar(100);
select @userid=i.userid from inserted i;
select @pair=i.pair from inserted i;
SET NOCOUNT ON
if update(pair)
begin
insert into Complete_Pairs(userid,pair)
values(@userid,1);
end
GO
/****** Object: Table [dbo].[Complete_Pairs] Script Date: 05/22/2014 21:20:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Complete_Pairs](
[Sno] [int] IDENTITY(1,1) NOT NULL,
[userid] [nvarchar](50) NULL,
[pair] [int] NULL
) ON [PRIMARY]
GO
my query is TRIGGER triggAfterUpdate is fired only when pair column in User_Details table is update only and when we update other column like ljoin or rjoin then my trigger is not fired
please any one can suggest us how it can done or provide solution
Jitendra Kumar Sr. Software Developer at Ruvixo Technologies 7895253402>select @userid=i.userid
frominserted i;
select
@pair=i.pair
frominserted i;
The code above assumes a single row UPDATE.
You have to setup the trigger for set processing like when 100 rows are updated in a single statement.
UPDATE trigger example: http://www.sqlusa.com/bestpractices2005/timestamptrigger/
Kalman Toth Database & OLAP Architect
SQL Server 2014 Design & Programming
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012 -
How to check/verify running sql in lib cache is using updated statistics of table
How to check/verify running sql in lib cache is using updated statistics of table used in from clause.
one of my application table is highly busy i.e frequent update/insert/delete.
we gather table stats every 30 min.Hello, "try dynamic sampling" = think "outside the box", maybe hit two birds with same stone.
As a matter of fact, I was just backing up your statement: "30 minutes seems pretty extreme"
cheers -
SQLEception using Complex SQL Query with Java Studio Creator2 Build(060120)
I am evaluating Java Studio Creator2 for a WEB base application project that will be making SQL queries to an Oracle Database but I have stumble into a problem using complex SQL queries.
I am getting an SQLException "org.apache.jasper.JasperException: java.lang.RuntimeException: java.sql.SQLException: [sunm][Oracle JDBC Driver][Oracle]ORA-00923: FROM keyword not found where expected". I looks like it cut my sql.
The SQL that I am trying to execute is
Select part_name
from table1, table2
where table1.part_nbr = table2.part_nbr
and table2.row_add_dt = (select max(table3.row_add_dt)
from table3
where table3.ser_part_id =table2.ser_part_id)
This is a valid query that it is using 2 different selects to get a part number.
If posible, point me to the best solution were I will be able to make complex SQL queries like the one above and bigger.
Is there any way that I can read an SQL query file instead of inserting the SQL query string into the setCommand()?I have read that document looking for some anwsers on how to make this kind of query. If I try the query that I have above in the query editor ,the query editor will cut off from the last select that is between ().
I beleave, there is a work around using the inner joint or outter join command. I will try them to see If I get the corrent result. If not, then I have to keep on asking for possible solutions.
Anyway, someone in the Creator Team should take a note in adding something like a special criteria in the Add Query Criteria Box for cases like the one I have. The special criteria will be like using another select/from/where to get some result that will be compare.
Girish, Are you in the Sun Creator Team? -
Using StreamInsight to pull SQL Server data repeatedly.
I have a typed class as follows:
public class CallEvent
public int CallID { get; set; }
public int CustomerID { get; set; }
public int ContactCenterID { get; set; }
public int CallDurationSeconds { get; set; }
public DateTime CallEventDateTime { get; set; }
I can easily obtain data using a SQL Server stored procedure into a point stream and output with a simple pass-though LINQ query. However, the simple application I created only collects (and aggregates if I use another more complex LINQ query) the dataset
being initially called. My problem is that I have these events being inserted continuously into the database and need to query the database on regular intervals.
I would like to create a repeatable call to the database using StreamInsight. I have the stored procedure that SI uses to collect data and tracks what has been processed. A simple example of the procedure code is as follows:
BEGIN
BEGIN TRANSACTION
SELECT CallID, CustomerID, ContactCenterID, CallDurationSeconds, CallDateTime
FROM CUST.Calls
WHERE Processed = 0
ORDER BY CallID;
UPDATE CUST.Calls
SET Processed = 1
WHERE Processed = 0
COMMIT TRANSACTION
END
I know I need a timer and I will have it fire every 15 seconds, having SI call the stored procedure, process the stream and aggregate the data over that 15 period using tumbling and hopping windows. The LINQ Queries to do this is not my issue. My
issue is that I'm new to SI and I'm trying to determine what part of the SI code; the query, the binding, what; would reside in my timer event process procedure. Currently I'm trying to get away with just using IEnumerable sink. Can I do that or
is a special input adapter going to be needed?
Thanks.You need to create a source for your call events. The adapter model is an older approach to working with StreamInsight. The Rx approach is much simpler. Call it SqlCallEventSource. This class needs to implement the observable pattern by
implementing IObservable<CallEvent>. Inside your SqlCallEventSource, you can setup a timer to call your sproc on a 15 second interval. When your sproc call returns rows, project/map them into CallEvents, and then send the
events to your subscribers. After that, you just need to get the stream of events coming off the source and run it through your query logic before sending the results to a sink for output. -
Using a custom PL/SQL to populate the primary key in a tabular form
I want to use a Custom PL/SQL Function to populate the primary key when I insert a new record into a tabular form. I want to get the value from a hidden page Item. The code I am using for the primary key source is:
BEGIN
INSERT INTO TEAM_MEMBERS(TEAM_ID)
VALUES(:P75_TEAM_ID);
END;
When I try to insert a new record I get the following error:
Error ERR-1904 Unable to compute item default: type = Function Body computation_type= BEGIN INSERT INTO TEAM_MEMBERS(TEAM_ID) VALUES(:P75_TEAM_ID); END; .
ORA-06550: line 5, column 2: PLS-00103: Encountered the symbol ";" when expecting one of the following: begin case declare end exception exit for goto if loop mod null pragma raise return select update while with << close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe The symbol "exit" was substit
Any ideas what I am doing wrong?
Thanks!Brian - Sometimes whitespace at the end of the block causes this. Be sure to trim everything after the last semicolon including tabs and newlines.
Scott -
Using Date objects in SQL statements
Hi, I am wondering if it is possible to use Date objects while trying to retrieve entries from an access database with fields set as "Date/Time" fields, as opposed to "Text"? If so, do I need to reformat it before inserting it into the SQL statement, or can I just leave it as a Date object, and call up the variable name?
For example - "SELECT * FROM database WHERE startDate = ' " + dateObject + ' ". And do i need quotes round this value?
Thanks in advance.I had some problems by just fetching a date and pushing it back to a MS SQL Database.
I used the following reformating step to fix it:
if (o instanceof Timestamp)
String time = o.toString().substring(8,10)+"."+o.toString().substring(5,7)+"."+o.toString().substring(0,4)+" "+o.toString().substring(11,19);
ht.put(columnName, time);
o is the object i receve from the select statement and ht is a Hashtable where i put my data.
To write the data back i now can use:
UPDATE table SET columnname = 'valueOfColumn'
This means i use the value i created above in Quotes to write it back.
Format of Timestamp.toString() is something like yyyy-mm-dd hh:mm:ss.xx
Format used by MS SQL (and i think by Access to) 'dd.mm.yyyy hh:mm:ss' -
Problems using Quick Migrate in SQL Developer 1.5 for MySQL to Oracle 10g
Hi all,
I am trying to use SQL Developer 1.5 migration tools (Quick Migrate) to perform online capture and build source model to migrate from MySQL 5.x to Oracle 10g on Windows platform. I get these errors and the Quick Migrate process fails:
oracle.dbtools.metadata.persistence.PersistableObject.doInsert(PersistableObject.java:238)
I did a search and used the sqldeveloper.cmd script but still fails. Then I created a new database and truncated the repository. I now get the above error plus two new ones listed below:
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
Error loading nls:OALL8 is in an inconsistent state
Error occurred during capture: Protocol violation
It fails during the capture process for MySQL 5.1 database
when it begins to capture the tables from MySQL.
Does anyone know how to resolve these issues when migrating from MySQL to Oracle 10g using Quick Migrate with SQL Developer 1.5 release?
Regards,
Ben Prusinski
Message was edited by:
benprusinski
Message was edited by:
benprusinskiHi all,
I put the following in my sqldeveloper.cmd file:
SET ORACLE_HOME=%CD%
What is very confusing is that with SQL Developer 1.5, there are several levels and several SQL Developer executables! I am really not sure which of these to use:
I created the SQLDeveloper 1.5 directory called SQLDeveloper1_5 on Windows:
1) cd C:\sqldeveloper1_5\sqldeveloper-5338
there exists a sqldeveloper.exe
2) cd c:\sqldeveloper1_5\sqldeveloper-5338\sqldeveloper\sqldeveloper.exe
3) cd c:\sqldeveloper1_5\sqldeveloper-5338\sqldeveloper\sqldeveloer\bin\sqldeveloper.exe
Which SQLDeveloper 1.5 executable should I be using and where should I place the
sqldeveloper.cmd file?
Also I did try to use a different database and schema for the repository with Quick Migrate but it appears a bug exists in SQL Developer 1.5 version that causes errors with Quick Migrate for MySQL to Oracle? Is this correct?
As an update, I ran the following commands:
cd to
c:\sqldeveloper1_5\sqldeveloper-5338\sqldeveloper\sqldeveloper\bin
sqldeveloper.cmd sqldeveloper.exe
Start sqldeveloper.exe
Perform standard capture for MySQL using the new mig2 schema as the new repository
It starts the capture but fails on the errors below:
Error loading nls:OALL8 is in an inconsistent state
UPDATE
============================
I tried this again and it worked with the exception of one error message listed below:
Here are the steps that I followed:
1. Create a Windows cmd script
Put the following entries in the script:
SET ORACLE_HOME=%CD%
save the command windows script as sqldeveloper.cmd
Copy this script to the base installation directory for SQLDeveloper
Example:
1. cd c:\SQLDeveloper1_5\sqldeveloper-5338\sqldeveloper
2. Start SQLDeveloper with the command script that you created earlier
Example:
Open a Windows shell prompt window and execute the following scripts:
a) sqldeveloper.cmd sqldeveloper.exe
b) sqldeveloper.exe
3) In SQL Developer 1.5
From the Migrate menu,
a) Delete current repository and create a new schema in Oracle target database call it mig2.
b) Then create a new repository in SQL Developer 1.5
c) Right mouse click on the MySQL 5.x database and choose capture
It worked with the exception of one error message:
o.jdbc.driver.OracleDriver
Error while registering Oracle JDBC Diagnosability MBean.
So it looks like something is screwed up with my JDBC drivers and configuration for MySQL. How do I diagnose the JDBC driver issue for MySQL?
Thanks!!!
Ben
Thanks
Ben -
Insert and update tables from SQL server to oracle database tables
Hi,
I am having problem while update data from sql server to oracle database tables.
I am doing one way insert +updates that is from SQL Server tables ==> Oracle database tables
I am using tools Sql server Integration service. I can insert data from sql server to oracle but update can't. Please help me how can I update + insert from sql server to oracle database tables easily.
Thanks in advance.Hi,
What about using Oracle SQL Developer for migration
http://www.oracle.com/technetwork/database/migration/sqlserver-095136.html
HTH -
[DW 8.02 + PHP] how to use variables in advanced SQL queries
Hi all,
I can't find a way to use variables in an SQL query after
updating
dreamweaver 8.02.
I always get error messages that says: 'missing variable
type:myvariablename', undefined#myvariablename... and so on.
What is the correct way to use variables?
I usually set a variable in a PHP statement (example: <?
$today=date('Y-m-d'); ?>)
and then I compare this variable in the SQL query.
What is the correct syntax for variable in DW 8.02 in
advanced SQL
queries?
TIA
tonysweetman wrote:
> I'm editing a website created with DW 8.01 and MX
Kollection.
>
> I updated DW to 8.02 and now I can't edit an existing
SQL query.
> I always get an error message 'Missing variable type'
and I can't go
> on.
InterAKT released a new version of Kollection to cope with
the 8.0.2
changes. AFAIK, you should be able to download the updated
version from
your InterAKT account area.
David Powers, Adobe Community Expert
Author, "Foundation PHP for Dreamweaver 8" (friends of ED)
Author, "PHP Solutions" (friends of ED)
http://foundationphp.com/ -
How to use hints in PL/SQL
Hi,
If I want to use hints in PL/SQL procedure, it is valid to write it this way:
begin
update /*+ INDEX(opp DIM_OPP_REFDB_IDX) */
scott.rec_dim_opportunity opp
set opp.mp_opportunity_re ....
endI doubt when I tried it that the optimizer didn't actually use the index.
Thanks in advance.
Oracle 10g R1
Windows 2003 32-bitthe table is of 90MB and when the UPDATE statement is used in SQL, the explain plan output shows that the index is used.
When I execute it from a procedure, the Current Statement show in TOAD doesn't show that the index is used and the update takes forever. Explain plan of the statement (as show in TOAD) shows that full table scan is being used. -
Connecting to datasource and retrieve, insert and update data in SQL Server
hi,
i am trying to retrieve, insert and update data from SQL Server 2000 and display in JSPDynPage and is for Portal Application. I have already created datasource in visual composer. Is there any sample codes for mi to use it as reference???
Thanks
Regards,
shixuanHi,
See this link
https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/6209b52e-0401-0010-6a9f-d40ec3a09424
Regards,
Senthil kumar K. -
Hello,
My question is: I would like to do more complex sql query ( i need to use GROUP BY, HAVING, ORDER BY). Is possible do it with CMP entity bean, or i have to use BMP entity bean or Session bean? Query return about 20-30 items. Can you recommend some design pattern for this situation?
Thanks in advance
Daniel HHello,
My question is: I would like to do more complex sql query ( i need to use GROUP BY, HAVING, ORDER BY). Is possible do it with CMP entity bean, or i have to use BMP entity bean or Session bean? Query return about 20-30 items. Can you recommend some design pattern for this situation?
Thanks in advance
Daniel H -
To find last updated date in sql developer for a procedure or a function
hi
how to to find last updated date in sql developer for a procedure or a function.
i m using sql developer version in 1.2I think you are in the wrong forum...
Anyway you can try
select * from
all_objects o
where o.object_type in ('FUNCTION','PROCEDURE');
you have there the created date, last DDL and timestamp
Maybe you are looking for
-
I deleted my user profile by accident now I can't open firefox, what do I do?
Basically I deleted the file in the Library/Application Support/Mozilla/Profiles folder and all other mozilla folders I could find thinking that I was going to completely remove and reinstall firefox on my computer (I was having issues with add-ons a
-
Installing Solaris 10 from another hard drive
I do more reading and digesting than actually adding content. But I wanted to share my recent experience with a recalcitrant server. I have a V440 server remote to my home location. We needed to rebuild it from scratch - wipe and reload the OS, pat
-
CRIO, FPGA, portability to different I/O module configuration
Hello people! For my student research projekt, I need support. I have to implement the NI-Tutorial:"CompactRIO Control Design and Simulation Tutorial" on another hardware. my cRIO 9004 is no problem and the chassis NI9104 is the same. Problems occure
-
OK, I believe I know how to do this, but give me some tips on proceedure and funtionality. I want a partition for the startup volume, for repairs etc, and one to use as a second storage disk, for documents, photos, art projects, and back ups, as I am
-
Query Regarding transfer of WBS element change data
Hi All, We have a requirement in which we need to transfer the change/create/delete information for WBS element in SAP to a third party system for certain set of specified fields. The problem we are facing is that the change and create information do