473,586 Members | 2,855 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

TOUGH INSERT: Copy Sale Record/Line Items for "Duplicate" Record

I have a client who needs to copy an existing sale. The problem is
the Sale is made up of three tables: Sale, SaleEquipment, SaleParts.
Each sale can have multiple pieces of equipment with corresponding
parts, or parts without equipment. My problem in copying is when I go
to copy the parts, how do I get the NEW sale equipment ids updated
correctly on their corresponding parts?

I can provide more information if necessary.
Thank you!!

Maria
Jul 20 '05 #1
6 2422
You haven't posted much information so I'll have to make some assumptions
about your table structures, keys and constraints. Please include DDL with
your posts so that we don't have to guess:

CREATE TABLE SaleEquipment (seqid INTEGER IDENTITY PRIMARY KEY, orderno
INTEGER NOT NULL /* REFERENCES Sales (orderno) */, eq_partno INTEGER NOT
NULL /* REFERENCES Parts (partno) */, qty INTEGER NOT NULL, UNIQUE
(orderno,eq_par tno))

CREATE TABLE SaleParts (seqid INTEGER NOT NULL REFERENCES SaleEquipment
(seqid), partno INTEGER NOT NULL /* REFERENCES Parts (partno) */, qty
INTEGER NOT NULL, UNIQUE (seqid,partno))

This looks to me like a hirerarchy parts explosion in which case I'm not
sure why two tables are necessary. Is "Equipment" not just an inventory item
that has constituent "Parts" that are also inventory items? If the
constituent parts don't change then it could all reside in a single Parts
table.

Here's what you wanted to do. First, the SaleEquipment for the new sale:

INSERT INTO SaleEquipment (orderno, eq_partno, qty)
SELECT @new_orderno, eq_partno, qty
FROM SaleEquipment
WHERE orderno = @orderno /* The order you are duplicating */

Now insert the parts:

INSERT INTO SaleParts (seqid, partno, qty)
SELECT E2.seqid, P.partno, P.qty
FROM SaleParts AS P
JOIN SaleEquipment AS E1
ON P.seqid = E1.seqid
JOIN SaleEquipment AS E2
ON E1.orderno = @orderno
AND E2.orderno = @new_orderno
AND E1.eq_partno = E2.eq_partno

Note the key on SaleEquipment (orderno,eq_par tno) which I've just assumed.
If you don't have a natural key in your table then you have problems - but
hopefully you knew that anyway.

Hope this helps.

--
David Portas
SQL Server MVP
--

Jul 20 '05 #2
>> The problem is the Sale is made up of three tables: Sale,
SaleEquipment, SaleParts. <<

Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in
your schema are. Sample data is also a good idea, along with clear
specifications.
Each sale can have multiple pieces of equipment with corresponding parts, or parts without equipment. <<

This can be done with an inventory table that has all the items for
sale, both parts and complete units of equipment. Then you have a
separate BOM (bill of materials) table that gives the parts explosion
for the equipment.
... how do I get the NEW sale equipment ids updated correctly on

their corresponding parts? <<

I am not quite sure what you want. It sounds like you take a bunch of
parts, then look for an assembly made from them and return the
inventory number and name for the assembly. Example: I order pants
#1, jacket #3 and vest #2 as separate items with separate prices. The
system looks out for my best interest and sees that such a combination
is available as "Three piece suit #123", replaces my three items with
this one item, and then bills me the lower price of the suit.

The code is a little tricky, but it is basically an exact relational
division done with a nested set model of the parts explosion.

Or did you mean something else?
Jul 20 '05 #3
Thanks for the feedback. Here's the "more information" you requested.
CREATE TABLE [dbo].[Sale] (
[SaleID] [int] IDENTITY (1, 1) NOT NULL ,
[CustomerID] [int] NULL ,
[SaleDate] [datetime] NULL ,

) ON [PRIMARY]
CREATE TABLE [dbo].[SaleLineEquipme ntItem] (
[SaleLineEquipIt emID] [int] IDENTITY (1, 1) NOT NULL ,
[SLSaleID] [int] NOT NULL ,
[SLEquipmentID] [int] NOT NULL ,

) ON [PRIMARY]
CREATE TABLE [dbo].[SaleLinePartIte m] (
[SLPItemID] [int] IDENTITY (1, 1) NOT NULL ,
[SLPSaleID] [int] NOT NULL ,
[SLPPartID] [int] NOT NULL ,
[SLPEquipmentIte mID] [int] NULL ,

) ON [PRIMARY]

These are partials (obviously). This is for a manufacturing company.
The business case is that sometimes a company wants to order the exact
same thing they ordered before. My problem, specifically, is when I
get to Inserting into the SaleLinePartIte m table, how do I get the NEW
SaleLineEquipIt emIDs? If there was just one, I could easily trap it
with a variable, but most of the time, sales include more than one
piece of equipment with different parts that make up that piece of
equipment.

Here's a stored procedure I did going from Quote to Sale. I'm not
even sure if it works, although it seems to in production - I'm just
not sure why. The immediate problem is copying a recordset with in
the same table.

CREATE PROCEDURE [dbo].[spInsertQuoteTo Sale] @intQuoteID int,
@intSaleID int OUTPUT
AS

INSERT INTO Sale (CustomerID, SaleDate, ShippingMethodI D, SaleTypeID,
TotalSaleAmount , JobName, DiscountAmount, FreightAmount, QuoteID,
InvoiceNumber, WONumber)
SELECT dbo.Quote.Custo merID, GETDATE(), dbo.Quote.Shipp ingMethodID,
dbo.Quote.Quote TypeID,
dbo.Quote.Total QuoteAmount, dbo.Quote.JobNa me,
dbo.Quote.Disco untAmount, dbo.Quote.Freig htAmount,
dbo.Quote.Quote ID, (Select InvoiceNumber from InvoiceNumber),
(Select WONumber from WorkOrderNumber ) From Quote Where QuoteID =
@intQuoteID

--DECLARE @intSaleID int
SET @intSaleID = @@IDENTITY

INSERT INTO SaleLineEquipme ntItem(SLSaleID , SLEquipmentID,
SLSerialNumber, SLEquipmentPric e, SLEQuantity, SLDescription)
SELECT @intSaleID, dbo.QuoteLineEq uipmentItem.QLE quipmentID,
dbo.QuoteLineEq uipmentItem.QLS erialNumber,
dbo.QuoteLineEq uipmentItem.QLE quipmentPrice,
dbo.QuoteLineEq uipmentItem.QLE Quantity,
dbo.QuoteLineEq uipmentItem.QLE Description
FROM QuoteLineEquipm entItem Where
dbo.QuoteLineEq uipmentItem.QLQ uoteID = @intQuoteID --order by
dbo.QuoteLineEq uipmentItem.QLE quipmentID

INSERT INTO SaleLinePartIte m(dbo.SaleLineP artItem.SLPSale ID,
dbo.SaleLinePar tItem.SLPPartID , SLPEquipmentIte mID,
dbo.SaleLinePar tItem.SLPStanda rd,
dbo.SaleLinePar tItem.SLPBackor der, dbo.SaleLinePar tItem.SLPUnitPr ice,
dbo.SaleLinePar tItem.SLPPartDe scription,
dbo.SaleLinePar tItem.SLPQuanti ty)
SELECT @intSaleID, dbo.QuoteLinePa rtItem.QLPPartI D,
QLPEquipmentIte mID,
dbo.QuoteLinePa rtItem.QLPStand ard,
dbo.QuoteLinePa rtItem.QLPBacko rder,
dbo.QuoteLinePa rtItem.QLPUnitP rice,
dbo.QuoteLinePa rtItem.QLPPartD escription,
dbo.QuoteLinePa rtItem.QLPQuant ity
FROM QuoteLinePartIt em WHERE dbo.QuoteLinePa rtItem.QLPQuote ID =
@intQuoteID --AND dbo.QuoteLinePa rtItem.QLPEquip mentItemID is null

UPDATE SaleLinePartIte m

SET SLPEquipmentIte mID = dbo.SaleLineEqu ipmentItem.Sale LineEquipItemID
FROM dbo.SaleLineEqu ipmentItem INNER JOIN
dbo.QuoteLineEq uipmentItem ON
dbo.SaleLineEqu ipmentItem.SLEq uipmentID =
dbo.QuoteLineEq uipmentItem.QLE quipmentID AND
dbo.SaleLineEqu ipmentItem.SLEQ uantity =
dbo.QuoteLineEq uipmentItem.QLE Quantity AND
dbo.SaleLineEqu ipmentItem.SLEq uipmentPrice =
dbo.QuoteLineEq uipmentItem.QLE quipmentPrice INNER JOIN
dbo.QuoteLinePa rtItem ON
dbo.QuoteLineEq uipmentItem.Quo teLineEquipItem ID =
dbo.QuoteLinePa rtItem.QLPEquip mentItemID INNER JOIN
dbo.SaleLinePar tItem ON
dbo.QuoteLinePa rtItem.QLPEquip mentItemID =
dbo.SaleLinePar tItem.SLPEquipm entItemID
WHERE (dbo.SaleLineEq uipmentItem.SLS aleID = @intSaleID) AND
(dbo.QuoteLineE quipmentItem.QL QuoteID = @intQuoteID)
GO

Sorry this is so long. Thanks for the help!!!
Maria
Jul 20 '05 #4
Ignore the HUGE message I sent before. The SQL David sent was
PERFECT!!! I worked it through (which I should have done before
replying) and you had it.

I really appreciate it. As you can see if you look at my code, I was
making it too hard (I tend to do that).

Thanks again!!!
Maria
Jul 20 '05 #5
I hope you know that IDENTITY can never be a key, that it has no check
digits so you cannot even validate it. You would never use it for
anything a customer has to see and use.

Can you explain the logical differences among "SaleID" (which, being
IDENTITY, is the physical location in storage of a row), a "SLSaleID"
and a "SLPSaleID" ? Why is "SaleLineEquipI temID" logically different
from "SLEquipmentID" ? Ditto with almost everything else you have posted.
Since they have different names, they **must** be logically different.
Surely, you would never, never name a data element for each table where
it located.

Naming data elements by the file they came from was how we had to locate
COBOL records. I hope that "SalesLine" does not refer to the PHYSICAL
sales form's printed lines on a piece of paper or a screen. The next
worst thing is prefixing the datatypes to data element names -- that is
BASIC programming.

If you had followed ISO-11179 standards for names, used DRI, and had
real keys, would the schema look more like this?

CREATE TABLE Sales
(sale_id INTEGER NOT NULL PRIMARY KEY
CHECK(<< validation code >>),
customer_id INTEGER NOT NULL,
sale_date DATETIME NOT NULL);

CREATE TABLE Equipment
(sale_id INTEGER NOT NULL REFERENCES Sales(sale_id),
equipment_id INTEGER NOT NULL,
PRIMARY KEY (sale_id, equipment_id));

CREATE TABLE Parts
(sale_id INTEGER NOT NULL,
equipment_id INTEGER NULL,
part_id INTEGER NOT NULL,
FOREIGN KEY (sale_id, equipment_id)
REFERENCES Equipment(sale_ id, equipment_id),
PRIMARY KEY (sale_id, equipment_id, part_id));
how do I get the NEW SaleLineEquipIt emIDs? <<


You don't have them in the first, if you know how to design an RDBMS,
instead of a sequential file system.

When get an order for equipment you have assembled before, you look up
the sales for that customer, you get the (sale_id, equipment_id), and
then the parts with that key. When you do the two insertions, you go to
the sales numbers table or routine and use it in both the Equipment and
Parts table.

Now this is a trival insertion procedure. 80% or more of the time that
you have complex DML, it is due to bad DDL. Bad DDL is usually attempts
to imitate a file system or an OO model in an RDBMS.

--CELKO--
=============== ============
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are.

*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #6
Joe -
Again thanks for your help. Although my naming conventions aren't
standard, we are on the same page with design. 1) The key values -
ID's are not used by the client or seen by the client. They are only
used for referential integrity and relational database management. 2)
I did name foreign keys different than their primary key
counterparts, depending on the table they were in. I know what it
means, and for now, that's all that matters because it's in
production. 3) There is a difference, in this business model, from
EquipmentID to SaleEquipmentID . While the SaleEquipmentID does
reference the original EquipmentID, it is stored seperately, because
the manufacturer wanted to be able to change each piece of equipment
as it was sold. Almost all the stuff they do is based on a
"standard", but things are added and subtracted all the time
(individual parts).

I believe the forms of RDMS are wonderful guidelines. But there are
business cases where the rules have to be bent a little to accomodate
business rules. While there is always more I can learn (being
primarily self-taught for the first 10 years of development - am now
an MCSD), I feel very confident in my relational database design
skills.

Thanks for pointing some stuff out. I do appreciate your help!
Maria
Jul 20 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
3277
by: Mark | last post by:
When my form goes to a new record, I have a procedure that copies the last record added to the form's underlying table into the form. The intent is that a series of new records may have the same data in many of the fields so I paste in the same values of the previous record and then edit what needs edited in the new record saving much retyping...
8
20546
by: Ray | last post by:
I have a data input form and need to automatically duplicate the existing record as a new record by clicking a button. The main purpose to duplicate the record is that the new record is very similar to the existing record with minor differences. It will save the data input operator a lot of afford by editing the minor difference only. ...
0
1808
by: Cyberwolf | last post by:
OK, how to explain this. I have a table that will feed into another table using an append query. What I want to do is look at the table I am appending the record to to check for a duplicate record. I would use a key field, but, I will sometimes want to allow the duplicate field. i.e. sometimes it will have a zero (0) value. So how would I...
1
9021
by: 2D Rick | last post by:
Access2003 in XP If I open a form to a specific record and click on a command button with the following code I get a duplcate record: DoCmd.RunCommand acCmdSelectRecord DoCmd.RunCommand acCmdSaveRecord DoCmd.RunCommand acCmdCopy DoCmd.RunCommand acCmdPasteAppend OR DoCmd.DoMenuItem acFormBar, acEditMenu, 8, , acMenuVer70
6
6507
by: planetthoughtful | last post by:
Hi All, I have a C# ASP.NET page that submits back to itself to insert details from a form into a database table. When / if the user refreshes the page (and gets the standard warning that POST data will be resubmitted), the previously submitted record is sumbitted again, and a duplicate record is inserted into the table. In PHP I would...
3
9151
by: Hexman | last post by:
Hello All, How do I catch duplicate record attempted to be added exception? As in: Catch ex As Exception Thanks, Hexman
3
2365
by: ammie65 | last post by:
I have been trying to create a purchase order database in Access, and I have been successful in creating all the tables, queries and reports that I need. I have only one issue: I need to copy the PO - which has a relationship set up as one-to-many with a subform that includes the PO items (Qty, Desc & Price). I want to be able to create a...
6
11996
by: Dave | last post by:
I really don't like the users getting an unhandled expception page, and I'm still to new with ASP.Net and C#. So please accept my appology for the 2 part question. SqlException (0x80131904) 1.) Is an "Cannot insert duplicate key row" exception from a FormView returned as part of the ItemInserting or ItemInserted event? 2.) What is...
6
4535
by: teser3 | last post by:
I have my PHP inserting into Oracle 9i. But how do I prevent duplicate record entries? I only have 3 fields in the insert in the action page: CODE <?php $c=OCILogon("scott", "tiger", "orcl"); if ( ! $c ) { echo "Unable to connect: " . var_dump( OCIError() );
1
2879
by: BenB | last post by:
Hello, A try: I have got an application which runs smoothly under Windows 2003 server with SQLserver 2005. No problems at all... The database is installed on the same server as the application. We are working on redundancy, so we have installed this application under VMWare. This VMWare is running at a dedicated VMWare hardware. In the...
0
7911
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7839
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8200
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
5710
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5390
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3864
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2345
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1448
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1179
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.