How To Insert Records Into Related Tables?

Sep 24, 2007

Hi,
I have 3 tables:
Employees with the fields:idEmployee and employeeName
Roles with the fields:idRole and roleName.
An employee can have one or many roles.
I created the table EmployeeRoles with the fields: id,idEmployee,idRole.
idEmployee and idRole are foreign keys.
I want to insert a new employee into Employees table, but I have to insert idEmployee field into EmployeeRoles table.

How can I do this?
Thanks

View 6 Replies


ADVERTISEMENT

Delete Records In Two Related Tables?

Jan 30, 2014

I am trying to delete the records in 2 related tables. The 'child' table has a field called [SETA],

I want to delete all the records in this table that contain the same info, as well all the fields in the parent table that is related to this table. They share the [ID] field as key. This is my code:

Code:
DELETE FROM Student a full outer JOIN Qualification b on a.[ID] =b.[ID] WHERE b.[SETA] = @SETA

View 4 Replies View Related

Terminology Question - Set Of Related Records In Multiple Tables

Jul 20, 2005

Terminology question:Is there a term for a set of records related directly or indirectly by keyvalue in several tables? For example, a single invoice record and its lineitem records -or- a single customer, the customer's orders, the order linesfor those orders, the customer's invoices, and the invoice lines for thoseinvoices.I'm thinking the term might be graph, but I'm not at all certain of this.Thanks,Steve J

View 17 Replies View Related

Insert Data Into Related Tables

Mar 2, 2008

i am using ms sql server 2005 express for the following:

T1 = {t1.c1(PK), t1.c2, t2.c1(FK)}

T2 = {t2.c1(PK), t2.c2}

where T1 and T2 are tables from the same database, and tn.cn are CoulmnN of TableN
T1 and T2 are linked by the relationship t2.c1

i need to know how to add records to T1 and T2 using ms sql.

record for T2 needs to be added first then retreive t2.c1 from T2 to add record to T1 with t1.c1, t1.c2 t2.c1

please help, thanks

View 2 Replies View Related

Insert Stored Procedure For Related Tables

Feb 24, 2005

I have two sets of related tables: Quote - QuoteDetail and Order - OrderItem

I need to copy Quote - QuoteDetail records to Order - OrderItem tables

I have the stored procedure up to this point: Insert a Quote in the Order table and get the new Order @@Identity.

I need to insert the QuoteDetail records into the OrderItem table using the new OrderID

Thank you for your help.

View 4 Replies View Related

Can We Insert/Update Into Related Tables In A Single Round Trip ?

Sep 25, 2002

I would like to update/insert data into a Orderhearder Table along with the related details into the corrosponding OrderDetails Tables. Can this be done using a single stored procedure or do we have to make one call to the UpdateOrderHeader Stored Procedure and loop thru all the details and call the UpdateOrderDetails Stored Procedure. How do we handle the Transactions in such a case ?

Thanks

Anurag Agarwal

View 1 Replies View Related

Insert Records From Foxpro Tables To SQL Server Tables

Apr 22, 2004

Hi,

Currently, I'm using the following steps to migrate millions of records from Foxpro tables to SQL Server tables:

1. Transfer Foxpro records to .dat files and then bcp to SQL Server tables in a dummy database. All the SQL tables have the same columns as the Foxpro tables.
2. Manipulate the data in the SQL tables of the dummy database and save the manipulated data into the SQL tables of the real database where the tables may have different structure from the corresponding Foxpro tables.

I only know the following ways to import Foxpro data into SQL Server:

#1. Transfer Foxpro records to .dat files and then bcp to SQL Server tables
#2. Transfer Foxpro records to .dat files and then Bulk Insert to SQL Server tables
#3. DTS Foxpro records directly to SQL Server tables

I'm thinking whether the following choices will be better than the current way:

1st choice: Change step 1 to use #2 instead of #1
2nd choice: Change step 1 to use #3 instead of #1
3rd choice: Use #3 plus manipulating in DTS to replace step 1 and step 2

Thank you for any suggestion.

View 2 Replies View Related

Looping Thru Records To Find Related Records

Oct 31, 2007

Hi, I have had this problem for a while and have not been able solve it.

What im looking at doing is looping thru my patient table and trying to organise the patients in to there admission sequence, so when patient "A" comes in and is treated at my hospital and is discharged and admitted to another Hospital within one day then patient "A" will get a code of 1 being there first admission.

then if patient "A" is admitted again but there admission date is greater than one day they get a code of 2 being for there second admission but will need to loop thru table looking for other admissions and discharges.

The table name is Adm_disc_Match_tbl

Basically what i have 4 fields.
Index_key = which is the patient common link (text)
ur_episode = this wil change for each Hospital (text)
Admission_datetime = patient admission date and time (datetime)
Discharge_datetime = patient discharge date and time (datetime)

example of data


Code: ( text )
Index_key,ur_episode,Admission_datetime,discharge_ datetime
HERBERT-7/1929,513884-1686900,4/07/2006 10:58,17/07/2006 13:37
HERBERT-7/1929,C023092-1698859,17/07/2006 13:20,24/07/2006 0:30
ELSIE-5/1916,G148445-1720874,8/08/2006 11:00,30/08/2006 10:00
STANISLAWA-3/1918 ,G119981-1720045,8/08/2006 13:01,22/08/2006 12:13
FREDA-11/1925,183772-1998910,27/03/2007 9:53,3/04/2007 11:06
FREDA-11/1925,G147858-2007408,3/04/2007 10:49,26/04/2007 12:39
FREDA-11/1925,183772-2037727,28/04/2007 17:05,9/05/2007 11:41
FREDA-11/1925,G147858-2052082,9/05/2007 12:00,25/05/2007 11:17


If anyone could help it would be much appreciated.

View 6 Replies View Related

Insert Multiple Records Into 2 Tables

Aug 29, 2006

I have searched in length and cant seem to find a specific answer.I have a tmptable to hold user "shoppingcart" ( internal supplies)What i want is to take when the user clicks order to take that table pull the records with that user and populate the order and order details tablesThe order table has a PK of orderID and the orderdetails has a FK of orderIDI know how to insert to the main table, but dont know how to populate the details at the same timeI have this.Insert into supplyordersselect requestor from tmpordercart where requestor = &name so how do i also take from the tmpordercart the itemno and quanity and put them into the orderdetails so that it links back to order table?

View 1 Replies View Related

INSERT Records In Multiple Tables

Apr 2, 2004

I need to update two tables. I have created a view and am using the code in the attached file to insert into the two tables.

The page loads without errors, but I get this message that the view is not updatable because the modification affects multiple base tables.

I thought this was the purpose of views?

Does anyone have any suggestions? I am using Dreamweaver MX and SQL Server.

Thanks!
N

View 11 Replies View Related

Need To Insert Records From Multiple Access Tables Into 1

Mar 17, 2014

Using SSE 2012 64-bit.I need to insert records from multiple Access Tables into 1 Table in SSE and ensure no duplicates are inserted.This is executing, but is very slow, is there a faster way?

Code:
INSERT INTO dbTarget.dbo.tblTarget
(All fields)
SELECT
(All Fields)
FROM dbSource.dbo.tblSource
WHERE RecordID NOT IN (SELECT RecordID FROM dbTarget.dbo.tblTarget)

View 6 Replies View Related

Transact SQL :: Insert Records From Multiple Tables

Aug 30, 2015

This is a bit lengthy, but lets say we have three tables

a) tblSaleStatementCustomer
b) tblCreditors
c) tblReceiptDue

which shows records like below

Table 1 - tblSaleStatementCustomer

ID   CustomerName     VoucherType    Outbound     Inbound     CustomerType
----------------------------------------------------------------------------------------------
1     ABC                              Sales                10000              0                   Dealer
2     MNC                             Sales                  9000              0                   Dealer
3     MNC                             Sales                  4000              0                   Dealer

Table 2 -  tblCreditors

ID   Name     OpeningBalance
----------------------------------------------------------------------------------------------
1     ABC          20000  
2     MNC         15000 
3     XBM         18000
4     XYZ          12000

View 2 Replies View Related

Transact SQL :: Insert Records To A Table From Different Tables

Aug 30, 2015

Lets say we are executing this query below to retrieve each customer and the amount associated to a table 

"INSERT INTO tblReceiptDue (Dealer, Amount) SELECT CustomerName, SUM(CASE WHEN VoucherType = 'Sales' then Outbound ELSE  - Inbound END) AS AMOUNT from
tblSaleStatementCustomer  WHERE CustomerType = 'Dealer' GROUP BY CustomerName"

Which display the data like below

DEALER                AMOUNT
------------------------------------------------
ABC                          2000
XYZ                          1000    

However I have one more table TABLE2 which contains two columns

DEALER                OPENING
-------------------------------------------------------
ABC                               5000
XYZ                               7000

I want to modify my query in such a way that AMOUNT column should also add

OPENING from TABLE2 So that I must get the result like below

DEALER                AMOUNT
------------------------------------------------
ABC                            7000
XYZ                             8000    

View 10 Replies View Related

Deleting Related Records.

Oct 17, 2007

Hi
I wanted to do a delete rows from a group of table. These tables have a common column UserID. I heard that there is something called ondelete cascade. But I don't know how to set it up and utilise it. Could someone tell me how to do it. Or point me to a tutorial which shows how to do it.
Thanks

View 4 Replies View Related

Count Of Related Records??

Jul 23, 2005

Hi,I was wondering if it was possible to build a query that will include acolumn that will provide a count related records from another table.Although there is a way to achieve this through programming in thefront end, I would like to know if it possible to achieve the samething through a SQL statement alone.For example, say you have two related tables, Invoices andInvoiceItems. InvoiceID is the primary key of Invoices.Invoices tableInvoiceID PO_Num CompanyID-------------------------------1 37989 32 87302 43 78942 3InvoiceItems tableItemID InvoiceID PartNo Qty---------------------------------------1 1 ABA 32 1 ASLKDJ 23 1 9LF 84 2 IEPOW 185 2 EIWPD 36 2 DSSIO 17 2 EIWP 58 2 DC93 49 3 85LS0 8Then a query that has the Invoices table plus a count of InvoiceItemsfor each InvoiceID would generate this:InvoiceID PO_Num CompanyID ItemCount-------------------------------------------------1 37989 3 32 87302 4 53 78942 3 1Does anyone have any ideas how this would be done?Thank you.

View 1 Replies View Related

Cumulative Related Records From Hierarchy

May 30, 2008

Morning chucky eggsThis is duplicated over at SQLTeam...except I've moved on a bit so my question to you is different:http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=103798SQL 2k5I have a standard hierarchy in an adjacency table modelling business units in an organisation. I have another table associating people with (one single) business unit. I need to return all the people in each business unit in a cumulative manner i.e. a unit will include all people assigned to that unit and assigned to all child units too.Below is1) Set up code (in red)2) Initial query that failed on last data load due to the nature of the data changing and me not considering the ramifications of my initial solution properly3) My new soulution.My question is - is there a better way to accomplish this? I don't rate my code that highly and could do with this being as efficient as possible as at present I can't see it scaling to larger and larger data volumes all that well.USE tempdbgo----------------------------------------------------------------- Set up the structure & data...---------------------------------------------------------------CREATE TABLE dbo.org ( unit_code VARCHAR(10) NOT NULL , parent_code VARCHAR(10) NULL , CONSTRAINT pk_org PRIMARY KEY CLUSTERED (unit_code) WITH (FILLFACTOR = 100) )GO CREATE TABLE dbo.org_peeps ( unit_code VARCHAR(10) NOT NULL , person_code INT NOT NULL , CONSTRAINT pk_org_peeps PRIMARY KEY CLUSTERED (unit_code, person_code) WITH (FILLFACTOR = 100) , CONSTRAINT fk_org_peeps_other_org_peeps FOREIGN KEY (unit_code) REFERENCES dbo.org (unit_code) )GO CREATE VIEW dbo.org_peeps_parents--WITH SCHEMABINDINGAS SELECT org.unit_code , org.parent_code , org_peeps.person_code FROM dbo.org LEFT OUTER JOIN dbo.org_peeps ON org_peeps.unit_code = org.unit_codeGO INSERT INTO dbo.org (unit_code, parent_code)SELECT 'a', 'y' UNION ALLSELECT 'b', 'y' UNION ALLSELECT 'c', 'z' UNION ALLSELECT 'y', 'z' UNION ALLSELECT 'z', NULL--Insert people data (NOTE - the people are in units at the BOTTOM of the structure only)INSERT INTO dbo.org_peeps (unit_code, person_code)SELECT 'a', 1 UNION ALLSELECT 'c', 3 UNION ALL--These data go into intermediate levels of the organisation...SELECT 'y', 4 UNION ALLSELECT 'y', 5 UNION ALLSELECT 'y', 6---------------------------------------------------------------SELECT 'Original query. Because there is data in the intermediate tables --> ' + 'duplicate outputs....'---------------------------------------------------------------;WITH materialised_pathsAS ( SELECT unit_code , parent_code , person_code , unit_path = '/' + CAST(unit_code AS VARCHAR(MAX)) + '/' FROM dbo.org_peeps_parents WHERE parent_code IS NULL UNION ALL SELECT all_people.unit_code , all_people.parent_code , all_people.person_code , mp.unit_path + CAST(all_people.unit_code AS VARCHAR(MAX)) + '/' FROM dbo.org_peeps_parents AS all_people INNER JOIN materialised_paths AS mp ON mp.unit_code = all_people.parent_code )SELECT parents.unit_code , children.person_codeFROM materialised_paths AS childrenCROSS APPLY --Correlated derived table - get the child records per unit ( SELECT unit_code , parent_code FROM dbo.org AS parents_sub WHERE children.unit_path LIKE '%/' + parents_sub.unit_code + '/%' ) AS parentsWHERE children.person_code IS NOT NULLORDER BY person_code , unit_code-----------------------------------------------------------------SELECT 'This query returns the correct results but man it is ugly. '+ 'Can it be refined optimised?'-----------------------------------------------------------------;WITH materialised_pathsAS ( SELECT unit_code , parent_code , unit_path = '/' + CAST(unit_code AS VARCHAR(MAX)) + '/' FROM dbo.org WHERE parent_code IS NULL UNION ALL SELECT all_orgs.unit_code , all_orgs.parent_code , mp.unit_path + CAST(all_orgs.unit_code AS VARCHAR(MAX)) + '/' FROM dbo.org AS all_orgs INNER JOIN materialised_paths AS mp ON mp.unit_code = all_orgs.parent_code )SELECT all_orgs.unit_code , org_peeps.person_codeFROM dbo.org_peepsINNER JOIN ( SELECT org.unit_code , mp.unit_path FROM materialised_paths AS mp CROSS APPLY ( SELECT unit_code , parent_code FROM dbo.org WHERE mp.unit_path LIKE '%/' + org.unit_code + '/%' ) AS org ) AS all_orgsON all_orgs.unit_path LIKE '%/' + org_peeps.unit_code + '/'ORDER BY person_code , all_orgs.unit_code--Clean upIF EXISTS (SELECT NULL FROM sys.views WHERE object_id = OBJECT_ID('dbo.org_peeps_parents')) BEGIN DROP VIEW dbo.org_peeps_parentsENDIF EXISTS (SELECT NULL FROM sys.tables WHERE object_id = OBJECT_ID('dbo.org_peeps')) BEGIN DROP TABLE dbo.org_peepsENDIF EXISTS (SELECT NULL FROM sys.tables WHERE object_id = OBJECT_ID('dbo.org')) BEGIN DROP TABLE dbo.orgENDAs ever kudos and lavish thanks to anyone that can help :DOh - I nearly forgot - accounting for the Rudy clause - desired output:unit_code person_code---------- -----------a 1y 1z 1c 3z 3y 4z 4y 5z 5y 6z 6

View 14 Replies View Related

Cumulative Related Records From Hierarchy

May 29, 2008

Oh hai

This is closely related to this problem where Ryan & Peter helped me out loads (thanks again guys):
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=101989

I now have a slightly different problem. Instead of returning the cumulative counts of people related to a business unit in the hierarchy I now need to return the actual people records. I had some code, derived from the above, that worked fine until I loaded some new data. It took a while but eventually I figured out the (now obvious) reason for the error. I have tried several changes to the query and not got anywhere. Please could someone have a look and see if you can suggest the required alteration(s)?

USE tempdb
go

---------------------------------------------------------------
--Set up the structure & data...
---------------------------------------------------------------
CREATE TABLE dbo.org
(
unit_codeVARCHAR(10)NOT NULL
, parent_codeVARCHAR(10)NULL
, CONSTRAINT pk_orgPRIMARY KEY CLUSTERED (unit_code) WITH (FILLFACTOR = 100)
)
GO

CREATE TABLE dbo.org_peeps
(
unit_codeVARCHAR(10)NOT NULL
, person_codeINTNOT NULL
, CONSTRAINT pk_org_peepsPRIMARY KEY CLUSTERED (unit_code, person_code) WITH (FILLFACTOR = 100)
, CONSTRAINT fk_org_peeps_other_org_peepsFOREIGN KEY (unit_code) REFERENCES dbo.org (unit_code)
)
GO

CREATE VIEW dbo.org_peeps_parents
--WITH SCHEMABINDING
AS
SELECT org.unit_code
, org.parent_code
, org_peeps.person_code
FROMdbo.org
LEFT OUTER JOIN
dbo.org_peeps
ONorg_peeps.unit_code= org.unit_code
GO

INSERT INTO dbo.org (unit_code, parent_code)
SELECT 'a', 'y'UNION ALL
SELECT 'b', 'y'UNION ALL
SELECT 'c', 'z'UNION ALL
SELECT 'y', 'z'UNION ALL
SELECT 'z', NULL

--Insert people data (NOTE - the people are in units at the BOTTOM of the structure only)
INSERT INTO dbo.org_peeps (unit_code, person_code)
SELECT 'a', 1UNION ALL
SELECT 'c', 3

---------------------------------------------------------------
SELECT'This works great....'
---------------------------------------------------------------
;WITHmaterialised_paths
AS
(
SELECTunit_code
, parent_code
, person_code
, unit_path= '/' + CAST(unit_code AS VARCHAR(MAX)) + '/'
FROMdbo.org_peeps_parents
WHEREparent_code IS NULL
UNION ALL
SELECTall_people.unit_code
, all_people.parent_code
, all_people.person_code
, mp.unit_path + CAST(all_people.unit_code AS VARCHAR(MAX)) + '/'
FROMdbo.org_peeps_parents AS all_people
INNER JOIN
materialised_paths AS mp
ONmp.unit_code= all_people.parent_code
)

SELECTparents.unit_code
, children.person_code
, children.unit_path
FROMmaterialised_paths AS children
CROSS APPLY--Correlated derived table - get the child records per unit
(
SELECTunit_code
, parent_code
FROMdbo.orgAS parents_sub
WHEREchildren.unit_path LIKE '%/' + parents_sub.unit_code + '/%'
) AS parents
WHEREchildren.person_code IS NOT NULL
ORDER BY person_code
, unit_code


--Add data to INTERMEDIATE levels of organisation
INSERT INTO dbo.org_peeps (unit_code, person_code)
SELECT 'y', 4UNION ALL
SELECT 'y', 5UNION ALL
SELECT 'y', 6

---------------------------------------------------------------
SELECT'Since there is now data in the intermediate tables there are ' +
'duplicate outputs....'
---------------------------------------------------------------
;WITHmaterialised_paths
AS
(
SELECTunit_code
, parent_code
, person_code
, unit_path= '/' + CAST(unit_code AS VARCHAR(MAX)) + '/'
FROMdbo.org_peeps_parents
WHEREparent_code IS NULL
UNION ALL
SELECTall_people.unit_code
, all_people.parent_code
, all_people.person_code
, mp.unit_path + CAST(all_people.unit_code AS VARCHAR(MAX)) + '/'
FROMdbo.org_peeps_parents AS all_people
INNER JOIN
materialised_paths AS mp
ONmp.unit_code= all_people.parent_code
)
SELECTparents.unit_code
, children.person_code
, children.unit_path
FROMmaterialised_paths AS children
CROSS APPLY--Correlated derived table - get the child records per unit
(
SELECTunit_code
, parent_code
FROMdbo.orgAS parents_sub
WHEREchildren.unit_path LIKE '%/' + parents_sub.unit_code + '/%'
) AS parents
WHEREchildren.person_code IS NOT NULL
ORDER BY person_code
, unit_code

---------------------------------------------------------------
SELECT'This is the output I want - but I can''t simply apply distinct - the volumes of data preclude this'
---------------------------------------------------------------
;WITHmaterialised_paths
AS
(
SELECTunit_code
, parent_code
, person_code
, unit_path= '/' + CAST(unit_code AS VARCHAR(MAX)) + '/'
FROMdbo.org_peeps_parents
WHEREparent_code IS NULL
UNION ALL
SELECTall_people.unit_code
, all_people.parent_code
, all_people.person_code
, mp.unit_path + CAST(all_people.unit_code AS VARCHAR(MAX)) + '/'
FROMdbo.org_peeps_parents AS all_people
INNER JOIN
materialised_paths AS mp
ONmp.unit_code= all_people.parent_code
)
SELECTDISTINCT
parents.unit_code
, children.person_code
, children.unit_path
FROMmaterialised_paths AS children
CROSS APPLY--Correlated derived table - get the child records per unit
(
SELECTunit_code
, parent_code
FROMdbo.orgAS parents_sub
WHEREchildren.unit_path LIKE '%/' + parents_sub.unit_code + '/%'
) AS parents
WHEREchildren.person_code IS NOT NULL
ORDER BY person_code
, unit_code


--Clean up
IF EXISTS (SELECT NULL FROM sys.views WHERE object_id = OBJECT_ID('dbo.org_peeps_parents')) BEGIN
DROP VIEW dbo.org_peeps_parents
END

IF EXISTS (SELECT NULL FROM sys.tables WHERE object_id = OBJECT_ID('dbo.org_peeps')) BEGIN
DROP TABLE dbo.org_peeps
END
IF EXISTS (SELECT NULL FROM sys.tables WHERE object_id = OBJECT_ID('dbo.org')) BEGIN
DROP TABLE dbo.org
ENDJust paste and run the code and hopefully it should be reasonably clear. If you need any further info please let me know

View 5 Replies View Related

How To Trace The Records That Have Been Related To The Child Table

Aug 23, 2007

 
The problem of mine is, I have a datagrid, Which displays data from a Employee(parent) table.
Now I want to delete some records based on the user selected checkbox,only those records which has no related records in the EmployeeProject(child) can be deleted.I want to know which are all the record that cannot be deleted?
How can I achieve this?
 

View 3 Replies View Related

Running Total Of Records Related To Hierarchy

Apr 15, 2008

Hi guysI'm mulling over the best way to do something and would like your input. Forgive me if this is a bit 101 - I haven't ever had to do this in SQL before!Fairly standard set up - Hierarchy table modelling the structure of an organisation.Related table associating members of staff to the hierarchy.I want to return all levels of the hierarchy and for each level I would like to know the total number of people in the level (so for a division it would be the sum of all people in the child teams).Parameters - This table will be modelling many organisations' structures - I cannot guarentee anything like "there will never be more than n levels". As such - I would strongly prefer to have something that is iterative recursive. I can change the schema to suit the method I use if necessary. Database is not transactional - I am not concerned about updating speed. SQL Server 2K5.I've tried CTE but it turns out you cannot use group by in CTEs (even in derived tables). I have not yet tried feeding it a view or similar.I have not tried nested sets, materialised paths, accumulator table - I thought I would see if there is something obvious before I start piddling around with those.Ta!

View 11 Replies View Related

Running Total Of Records Related To Hierarchy

Apr 30, 2008

SQL Server 2005.
Schema is not fixed at this stage - small project, schema can be adapted if neccessary.
This needs to be produced in SQL Server - there is no client application.

Hi

I am really struggling to write the SQL for the following requirement and have got to the stage where I think I need someone to give me some pointers. I can't believe this is a novel requirement but I haven't had to do this before nor can find anything similar when googling.

I have a hierarchy detailing an organisation structure. Eventually the table will store many structures and these may one day be "pseudo structures" to enable really granular reporting. As such I cannot really say "there will never be more than N levels to this hierarchy". Currently I'm using a standard adjacency design. From now on I'll call the items in the table "business units".

There is a further table with a related FK declared which associates people with business units.

Requirement: Return all business units and cumulative total total of employees for each of these units (i.e. the total for each business unit will be the number of people in that unit plus the sum of the people in all the child units).

I've asked this question on dbforums but ended up a blind alley despite Peter's attempt to help. I'm starting again from scratch but feel free to review the (now dead) thread here:
http://www.dbforums.com/showthread.php?t=1629366

To summarise - I tried the CTE route but of course this evaluates the hierarchy from the top down. To fulfill the requirement, the bottom of the structure needs to be the starting point. I also tried reversing the hierarchy so that children, rather than the parent, are stored but my query fails if there are 3+ levels.

Code to reproduce problem (note - I expect that I will need to get the employee count per business unit prior to working with the hierarchy so I have flattened the schema to reflect this - I think I can handle the SQL to get the non-cumulative count per business unit ):
DECLARE @table TABLE
(
unit_codeTINYINT
, parent_codeTINYINT
, headcountINT
, PRIMARY KEY CLUSTERED (unit_code)
)

INSERT INTO @table (unit_code, parent_code, headcount)
SELECT 1, 4, 10 UNION ALL
SELECT 2, 4, 130 UNION ALL
SELECT 3, 10, 93 UNION ALL
SELECT 4, 10, 7 UNION ALL
SELECT 10, NULL, 1

Required output:

unit_codecumulative_headcount
------------------------------------
110
2130
393
4147
10241

Many thanks

View 5 Replies View Related

Transact SQL :: How To Get Time Span Across Several Related Records

Nov 19, 2015

I need a boost to understand how to get started on solving this SQL Query.

TicketId Seq StatusDateTime

T10001 1 2015-05-04 15:54:00.000
T10001 2 2015-05-04 16:35:00.000
T10001 3 2015-05-04 16:42:00.000
T10001 4 2015-05-05 08:19:00.000
T10002 1 2015-05-04 15:56:00.000
T10002 2 2015-05-04 15:57:00.000

I need to find the total StatusDateTime for each TicketId
I need to find the average StatusDateTime for all TicketIDs
Ex. TicketId, "T10001", has 4 records based on the Seq column.

By using this, I should be able to find the amount of time between the first Seq and the last Seq to get a total time span for Ticket.

Expanding on this, I should be able to add up all of the Ticket's calculated time spans and divide by the number of tickets to get the average time span.

View 6 Replies View Related

SQL Server 2012 :: Getting Related Records Set Based Results

Sep 29, 2015

I have a table that has multiple transactions for stock items.

This table holds all records relating to items that are inducted onto the system and there movement. For each stock item i am interested in getting the drop destination, if it has one, and only when it follows the sequential order of "Inducted>OnTransport>Dropped" (this sequence isn't always the case). Also note the CreatedDate for the Inducted and OnTransport records for the valid sequences are always the same. Below is a valid sequence for a stock item so i would want to return 'Lane01' for the Destination of this occurrence of the stock item, if this item didn't have a valid drop location then destination would be blank. Also note each stock item can be inducted more than one time per-day.

I think i have managed to build the below sql but it will only do one item at a time, so would have to wrap it in a function. Is there a way of writing a set based select statement that gets all the inducted items and for the ones that do follow the "Inducted>OnTransport>Dropped" return the destination it was dropped at? I've attached scrips below:

DECLARE @StockItemID nVarchar(128)
DECLARE @CreateDate DATETIME

Set @StockItemID='8cbe17da-6079-4170-b27a-41c0d38830f6'
Set @CreateDate = CAST('2015-08-31 13:52:39.890' AS datetime)

[Code] ....

View 9 Replies View Related

How To Calculatesave A Parent Status Based On Related Child Records

Sep 24, 2007

Thanks for your time,
How to calculate & save a Parent status [qcStatus varchar(30)] and Alert [alertFlag bit] in dbo.a1_qcParent
based on comparison of its Child records in dbo.a3_qcItems2Fix columns [itemComplete bit] and [alertFlag bit]
Where a1_qcParent[a1_id] = a3_qcItems2Fix[a1_ID]

- Parent CLOSED: if all children [itemComplete] are True
- Parent OPEN: if any child [itemComplete] is False

- Parent ALERT: True if any child row [alertFlag bit] is True

Using sql_Datasource in webpage, but more comfortable in sql... After-Trigger?
Can Parent columns have calculated formula referencing the child table? Please help.

View 1 Replies View Related

Related Tables

Jul 23, 2005

Is it possible to retrieve all tables that a given one is related tovia foreign keys?

View 2 Replies View Related

T-SQL (SS2K8) :: Delete All Rows Satisfying Certain Condition From Table A And Related Records From B And C

Apr 14, 2015

I have around 3 tables having around 20 to 30gb of data. My table A related to table B by a FK and same way table B related to table C by FK. I would like to delete all rows satisfying certain condition from table A and all corresponding related records from table B and C. I have created a query to delete the grandchild first, followed by child table and finally parent. I have used inner join in my delete query. As you all know, inner join delete operations, are going to be extremely resource Intensive especially on bigger tables.

What is the best approach to delete all these rows? There are many constraints, triggers on these tables. Also, there might be some FK relations to other tables as well.

View 3 Replies View Related

Inserting Into Related Tables

Mar 24, 2004

Hi all,

I am trying to insert user's input from a web form into the tables. For example,

PURCHASE TABLE(PurchaseID, PurchaseNo, Date, PartID)

PART TABLE(PartID, PartDescription,MachineID)

MACHINE TABLE(MachineID, MachineName)

On the web form I have textboxes for the Purchase No., date and part description, and a drop down list for the machine name. How do I insert them into the different tables?

I've just start learning ASP.NET and I am using Web Matrix for this. The examples I've seen so far only shows how to insert into a single table.

Thanks!

View 2 Replies View Related

Setting Up FTS On Related Tables

Sep 12, 2005

I have 2 related tables I want to include in a single full text search. How would I go about setting this up?

View 1 Replies View Related

Select 2 Related Tables

May 25, 2006

hi this is probably a dumb question with an easy answer but does anyone know how to do this...

2 tables, one is a supplier list (id, supplier_name) and the other is an order list (id, order_name, supplier_id... etc)

basically i need to join the 2 tables together (id=supplier_id) but i need to display the results without the supplier_id and the supplier table id, only the supplier name?

do i have select only the specific fields I want? or can I exclude the supplier_id and the id from the supplier table?

View 10 Replies View Related

Joining Not Related Tables

Mar 6, 2007

Hi all. how could i join unrelated tables?
for example:
table1: employee
dcno name address telno
1 sarah philippines 111
2 john india 222
3 joy usa 333

table2: hospital
hospname location owner
hosp1 loc1 billgates
hosp2 loc2 ann
hosp3 loc3 love
hosp4 loc4 vic

table3: student
studname load
kim 10

Is it possible to join unrelated tables?

Thanks
-Ron-

View 17 Replies View Related

Indexes On Related Tables...

Jun 17, 2007

Hi,

I have 2 tables with this design: one has ArticleID as primary key and multiple other fields and one has GroupID as primary key and multiple other fields. Each article can belong in multiple groups so I created a new table called articleGroups with only 2 fields: ArticleID and GroupID to show the groups associated with each article. There is a relation between this table and each of the main 2 tables. My question is, in the articleGroup table, does it make any sense to create an Index on ArticleID, GroupID or both? Since the group is needed for each article the Groups will always be queried everytime the article is queried. So, I am not sure if an index is needed?

Thank you,


Regards,

Iulian

View 5 Replies View Related

Select All From Two Many-to-many Related Tables

Oct 11, 2007

Hello, everyone!

Please give your ideas about how to create a query from two tables, which have many-to-many relationship. For example, we have table Book and table Author and consider, that one author had wroten several books and one book had being wroten by several authors. So we have many-to-many relationship of these two tables.
Usually this sutuation resolves by maens of creating the third table AuthorBook, which consist of key fields from the Author table and key fields from the Book table. So that the Author table is the parent table to AuthorBook, and the Book table is the parent table to AuthorBook. So we have two relations one-to-many. Now the question is how to get all related values from both tables, using JOIN operation and the conjunctive table?

I would greatly appreciate any answers

View 9 Replies View Related

Need Help On How To Do A Simple Insert SQL Script That Is Related??

Mar 28, 2008

I am trying to figure out what SQL script on how can I do this........I want to insert a record in a table by using the text fieds instead of using a primary key to recognize where it relates to.  Fro example, I have two tables:
table Make---------------Make ID- Interger (PK)   1 description - text            Honda
table model----------------Model ID - integer (PK)   1desc.--text                     AccordMake ID - interger (FK)    1
I am trying to figure out A way to do something like this.........  INSERT into model (Model ID which is an auto #, description, Make ID) VALUES (txtmodelID.text, txtdescripton.text, instead of doing MakeID here; I want to use the descripton from the Make table to insert thiis MakeID field) I badly need some help with this logic or syntax as it relates to most of the way I need to insert through out my site.  Thanks in advance.
In other words I want the user to select a Make from a drop down list not a Make ID# such as Honda that will insert under that Make ID number related to that description..... such as a type of car ; Accord's description into the model table.

View 3 Replies View Related

How Do I Select All Records In One Table That Have NO Related Records In Another Table?

Jul 20, 2005

I can't get my head around this:I want to select all IDs from table A that do not have a related record intable B according to some condition:Table A contains, say, Parents and table B contains Children. I want toselect all Parents that have no children called "Sally" (this is a noddyexample, reminds me of being at Uni again :) ).Any ideas?Thanks

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved