T-SQL (SS2K8) :: Removing Not Necessary Joins In Child Query?
May 23, 2014
I am building a application, which will generates a MASTER query with 15 fields & 5 tables joins.Now, the user selects only some fields from that master fields and generates the CHILD query. This is creating a performance issue.
To minimize this, i would like to remove the not necessary joins in the child query.
I’ve never written a query with multiple APPLY joins before and I’m running into some troubles with my first one. The below SQL statement runs within 10 seconds if I comment out either one of the APPLY joins and its corresponding field columns. However, when I try to execute with both APPLY joins, the query runs indefinitely. The longest I’ve waited before cancelling it is 90 minutes.
Now, I know there are probably other ways I could write this query to get me the results I’m looking for. I’m posting this on the board because I’m curious about finding out why multiple APPLY joins could cause SQL Server to run away. I’m hoping to gain some insight so that I can better understand how APPLY joins work so that in case I have a big need to do this again in the future (without suitable workarounds) I can code it correctly.
Here are some things I’ve tried so far…
1.Changed the States table into a subquery that only returns a single state 2.Change all the references inside the APPLY subqueries so that they had different aliases (just in case they were conflicting with each other). 3.Changed the CROSS applies to OUTER applies. States has 50 records and only 32 have matching permit data so the 18 extra iterations using OUTER APPLY don’t impact performance any when an APPLY is used by itself.
SELECT s.state_name , COUNT(DISTINCT DUPS.PermitNumber) AS NumOfDupPermits , SUM(DistinctPermits) AS DistinctPermits FROM States S CROSS APPLY (SELECT w.StateID, COUNT(*) as DistinctPermits
I have this query I need for a report. Originally it was 4 queries to be used in Crystal Reports. Now I want to create the same report with SSRS and therefore I incorporated all queries in one in order not to use subreports [URL].....
Tempdb fills up to nearly 90 GB. I am running SQL Server on a local box, so I am sure there is no other traffic. Here is the query:
SELECT AdHaupt.NSprache_ID ,AdHaupt.mengentext AS mengentextHaupt ,AdHaupt.Einzelpreis ,AdHaupt.Anzeigebezeichnung ,AdHaupt.Gesamtpreis
[Code] ...
I ran it with TOP 10 as well, just to see if it will finish at all, but it never did (ran for an hour now).
I was wondering if someone could help me with the results on this query, at the moment I am getting values repeated and I was wondering if it was possible to have some of the columns grouped, I have tried to have grouping at the end of the query but this still did not group the rows.
Thanks in advance for your answer - Sean
The structure that i'm trying to acheive is like the following: with each colour having multiple quantitys for each size:
colourdesc| sizedesc | xs | s | m | l ----------- black |qoh| | 0 | 2 | 0 | 7 ----------- white |qoh| | 0 | 0 | 0 | 0 -----------
I have a query which contains 12 left outer join. I remove some of the joins that don't have parameters. The result is coming same but usually when we remove joining it should take less exec time but for me it is taking more time. What could be the reason?
Employee table - This table has EmployeeID, Name, DOB.
EmployeeDesignation table - 1 Employee can have many designations with each having an effective date. There is no flag to indicate which among multiples is the current entry. You can only figure it out by the newest/oldest EffectiveDate. I want to get the most recent and the oldest for each employee.
EmployeeSalaryHistory table - Structure/Design is similar to EmployeeDesignation table. I want to get the starting salary and current salary for each employee.
I want my query to output me the following fields...
Currently, I have a query to get this done which looks as below. Since I have more than 8K employees with each having multiple Designation and Salary entries, my query is taking forever.
selecte.EmployeeID, e.EmployeeName, e.EmployeeDOB, (select top 1 Designation from @EmployeeDesignation ed where ed.EmployeeID = e.EmployeeID Order By EffectiveDate) EmployeeStartingDesignation, (select top 1 Designation from @EmployeeDesignation ed where ed.EmployeeID = e.EmployeeID Order By EffectiveDate Desc) EmployeeCurrentDesignation,
Below is my sample data of my table named "Groups"
with Groups as ( select 1 as GroupId,'Oracle' as GroupName,0 as IdParentGroup union all select 2 as GroupId,'Microsoft' as GroupName,0 as IdParentGroup union all select 3 as GroupId,'IBM' as GroupName,0 as IdParentGroup union all select 4 as GroupId,'SunMicrosystem' as GroupName,1 as IdParentGroup union all
[Code] ....
Expected result:
with ExpectedResult as ( select 'Oracle' as GroupName,'SunMicrosystem' as SubGroup union all select '' as GroupName,'peoplesoft' as SubGroup union all select '' as GroupName,'mysql' as SubGroup union all
[Code] ....
How to achieve this parent-child has the same table.
tblServer represents a server, tblInstance represents any SQL Server instances present on the server. They're related thru srvID.
I'd like to write a query that gives me servers with all instances, on one row. This dataset will populate a List in an SSRS report.
I have this but it's clunky and does not provide for more than 2 instances on the server. I'd like this to account for any number of instances all on one row without having to hard code multiple joins:
with serverInfo as ( select srv.srvType as Type ,srv.srvName as ServerName ,srv.srvIP as ServerIP ,ins.instNetName as InstanceNetName
I have a database with many tables. I would like to Delete all rows with practiceID=55 from all Parents tables and all corresponding rows from its child tables. Tables are linked with foreign key constraints (but there is no ON DELETE CASCADE).
How to write a generalized code for removing rows from both parent and child tables.
Query should pick parent table one by one and delete rows with practiceID=55 and all corresponding rows from its child tables
I have used Aasim Abdullah's (below link) stored procedure for dynamically generate code for deletion of child tables based on parent with certain filter condition. But I am getting a output which is not proper (Query 1). I would like to have output mentioned in Query 2.
Link:
[URL]
--[Patient] is the Parent table, [Case] is child table and [ChartInstanceCase] is grand child
--When I am deleting a grand child table, it should be linked to child table first followed by Parent
--- query 1
DELETE Top(100000) FROM [dbo].[ChartInstanceCase] FROM [dbo].[Patient] INNER JOIN [dbo].[Case] ON [Patient].[PatientID] = [Case].[PatientID] INNER JOIN [dbo].[ChartInstanceCase] ON [Case].[CaseID] = [ChartInstanceCase].[CaseId] WHERE [Patient].PracticeID = '55';
--Query 2
DELETE Top(100000) [dbo].[ChartInstanceCase] FROM [dbo].[ChartInstanceCase] INNER JOIN [dbo].[Case] ON [ChartInstanceCase].[CaseId]=[Case].[CaseID] INNER JOIN [dbo].[Patient] ON [Patient].[PatientID] = [Case].[PatientID] WHERE [Patient].PracticeID = '55';
how to modify the SP 'dbo.uspCascadeDelete' to get the output as Query 2.
Hi all,Just after some help with a query (Stored Procedure) I've managed to get wrapped round my head.The DB is as such:
COMPANY Company_id Company_name COMPANY_GROUP Group_id Group_name USER User_id User_name Bridging tables
COMPANY_GROUP_BRIDGE company_id group_id
USER_COMPANY_BRIDGE user_id company_id Basically, the only parameter I have for the query is a User_id.I need to get the Group linked to the User and return all the companies within that group. I've tried reading up on all the join types again but have just got this completely wrapped round my neck. I keep thinking along the lines of SELECT all the companies linked to all the groups linked to all the companies linked to the User_id :s I must be able to do this without using two Company tables...? Any help much appreciated,Pete
I have Categories table with CategoryID, Title, CategoryParentID columns Questions table with QuestionID, Text columns CategoriesQuestions table with CategoryID, QuestionID columns Now I want to make the query which takes QuestionID and return all Categories of that provided QuestionID. I already have made that query in 2 different styles. First I make an Inner Join to retrieve the results Select Categories.* from Categories Inner Join CategoriesQuestiosn on Categories.CategoryID = CategoriesQuestions.CategoryID where CategoriesQuestions.QuestionID = 1 Second I make a sub query to retrive the results. Select * from Categories where CategoryID In (Select CategoryID From CategoriesQuestions where QuestionID = 1) Now I am asking what is the better one in respect to performance. And please provide any other query if you have.
Iwrote a query right, and need to get further information out of another table, so did a Join, but then also need to get further information out of another table..So, I need to add this query:
SELECT PERSONNUM as EmployeeCode ,[FIRSTNM] as Firstname ,[LASTNM] as LastName ,[HOMELABORLEVELDSC1] as Site ,[HOMELABORLEVELNM1] as SiteID FROM [tkcsdb].[dbo].[VP_ALLPERSONV42]where USERACCOUNTSTATUS = 'active' and homelaborlevelnm1 in ('11', '13', '32') order by SiteID, LastName
select ad.bank,ad.account_number,ad.account_short_name, p.security_id,isnull(b.NAME,isnull(tw.name,ms.name)) as SecurityDescription, p.security_price,mc.classcode, sum(case when p.security_price = 9999999.99900 then 0 when mc.classcode between '000'and'299' then (p.quantity * p.security_price) / 100 when mc.classcode between '950'and'999' then (p.security_price * p.quantity) * -1 when mc.classcode between '300' and '324' or mc.classcode between '330' and '399'then p.acm_ctf_mtf_price * p.quantity when p.security_price = '0' then p.cost else (p.security_price * p.quantity) end) as MV,p.position_date,p.quantity,p.cost,p.acm_ctf_mtf_price from positions p left join BloombergEquityData b on p.security_id = b.ID_CUSIP left join account_detail ad on p.account_id = ad.account_id left join metavanteclasscodes mc on p.security_id = mc.cusip left join MacgregorSecurityMaster ms on p.security_id = ms.cusip left join TobaSecurityWarehouse tw on p.security_id = tw.cusip where p.position_date = '03/05/2008' and ((ad.investment_authority_id in ('2','3') and ad.bank in ('98','7R')) or ad.bank = '9W')-- and ad.account_number = '41G006012' group byad.account_number,ad.account_short_name,p.security_id, ms.name,b.NAME,p.security_price,p.position_date,ad.bank,mc.classcode,p.quantity,p.cost,p.acm_ctf_mtf_price,isnull(b.NAME,isnull(tw.name,ms.name)) order by ad.account_number,p.security_id
For a given day, in this example 3/5 if I were to just select all the records I would get back around 550,000. If I put the filter on where I tell it to just show me one account its snappy. If I remove that filter and have it show me all the accounts it take forever. Here is the layout of my positions table where i am pulling the majority of the information:
CREATE TABLE [dbo].[positions]( [account_id] [int] NOT NULL, [security_id] [varchar](50) NOT NULL, [position_date] [smalldatetime] NOT NULL, [quantity] [decimal](18, 5) NOT NULL, [cost] [decimal](18, 5) NULL, [security_price] [decimal](18, 5) NULL, [acm_ctf_mtf_price] [decimal](18, 9) NULL, CONSTRAINT [PK_positions] PRIMARY KEY CLUSTERED ( [account_id] ASC, [position_date] ASC, [security_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
GO SET ANSI_PADDING OFF
My questions is if you can identify any reason why the query might take more than 10 minutes (actually still running after 10 minutes) to complete when I have it bring me back all the records, not sure if its a lack of indexes or what, but was hoping for some suggestions on what I might be missing. I apologize if I havent included enough information, still learning how to troubleshoot the performance side of things.
-- declared variables declare @database_name varchar(100), @table_name varchar(100), @primary_key_field varchar(100) declare @list varchar(8000) -- set values to variables set @list = '' set @database_name = 'data200802_dan' set @table_name = 'other02' set @primary_key_field = 'callid'
use database
select @list = @list + column_name + ', ' from information_schema.columns where table_name = @table_name --table name and column_name != @primary_key_field --unique identifier select @list = substring(@list, 1, len(rtrim(@list)) - 1)
--above 5 lines btw came from a helper in the msdn forum. thanks
SELECT DISTINCT @list INTO '#' + @table_name FROM @table_name @table_name + ':' IF (SELECT COUNT(*) FROM @database_name + '.dbo.' + @table_name) = 0 BEGIN INSERT INTO @database_name + '.dbo.' + @table_name + '(' + @list + ')' SELECT @list FROM '#' + @table_name END ELSE BEGIN DELETE @database_name + '.dbo.' + @table_name +' ( ' + @list + ')' GOTO @table_name END DROP TABLE '#' + @table_name
the query above is basically.. selecting all the fields from a table in database W/OUT their primary key. then putting them in a temp table.. delete all the records in the original table. then paste the records from the temp table into the original table.
is there a way for this to work? i don't know how to use the variables w/ this script. please help me correcting this query..
Request ID Parent ID Account Name Addresss 1452 1254789 Wendy's Atlanta Georgia 1453 1254789 Wendy's Norcross Georgia 1456 1254789 Waffle House Atlanta Georgia
Not sure if this is right place to ask but here is our problem. We are getting records from more than one table. Table1 and Table2 for example Both Tables haveid, value table11, 201, 30 Table 21, 501, 40 here is the queryselect table1.id, table1.value, table2.value from Table1inner join Table2on Table1.id = table2.idproblem is this returns 4 rows like this1, 20 , 501, 30 , 501, 20 , 401, 30 , 40 When we need it to return1, 20 , null1, 30, null1, null, 401, null , 50 any help on this would be appreciated.Thank You in advance.
Hi all.I want to use the following query in a sp to enable paging using ObjectDataSource.The problem (being EXTREMELEY slow) arises when I add these joins and where statements. SELECT r.RID AS ReqID, r.Name AS ReqName, r.Family AS ReqFamily,t3.Name AS DistName, t4.Name AS RurName,t5.Name AS VilName, n.Name+' '+n.Family AS NazerName ,ROW_NUMBER() over (order by r.Family) AS RowRankFROM Requests rLEFT OUTER JOIN Nazeran n ON r.nazerID = n.ID LEFT OUTER JOIN t1States t1 ON t1.ID = r.StateID LEFT OUTER JOIN t2Provinces t2 ON t1.ID = t2.StateID AND r.ProvID = t2.ID LEFT OUTER JOIN t3Districts t3 ON t2.ID = t3.provID AND t1.ID = t3.stateID AND r.DistID = t3.ID LEFT OUTER JOIN t4RuralDistricts t4 ON t3.ID = t4.distID AND t2.ID = t4.provID AND t1.ID = t4.stateID AND r.RurID = t4.ID LEFT OUTER JOIN t5Villages t5 ON t4.ID = t5.rurID AND t3.ID = t5.distID AND t2.ID = t5.provID AND t1.ID = t5.stateID AND r.VilID = t5.IDWHERE r.stateid=(case when @StateID is null or @StateID='' then r.stateid else @StateID end) and r.provid=(case when @provID is null or @provID='' then r.provid else @provID end) and r.rID=(case when @ReqID is null or @ReqID='' then r.rID else @ReqID end) and isnull(r.nazerID,'')=(case when @nazerID is null or @nazerID='' then isnull(r.nazerID,'') else @nazerID end) and r.name+' '+r.family like (case when @ReqName is null or @ReqName='' then r.name+' '+r.family else '%'+@ReqName+'%' end) **there are 1million rows in [Requests] table ,200000 rows in [t5villages], and about total 5000 rows in other tables.As you can see, this is for a GridView showing list of people requesting a loan allowing users to make alternative searches based on Name, Familyname ,ID ,... would you please help me optimize and make fast this query.Many thanks..
I wrote a SQL query that firstly do an outer-join for two table and after I add another table with outer-join as well. I'm getting the following message: Server: Msg 301, Level 16, State 1, Line 1 Query contains an outer-join request that is not permitted. May be someone knows what is it? If I remove the second join- it work....
Ok I have a complex query that works great, but now I need to join yet another table but the problem is, the value that links it to the rest of the query is a value that is returned from a case statement earlier in the query...
For Example...
SELECT var1, var2, var3, CASE T1.Number WHEN 0 THEN T2.Result ELSE T3.Result END as var4 FROM TABLE1 T1 LEFT OUTER JOIN TABLE2 T2 on T2.Value=T1.Value LEFT OUTER JOIN TABLE3 T3 on T3.Value=T1.Value2
Above is a generalized, much smaller example of my working Query. Now what I need to do is join TABLE4 but the value I need to connect it to the rest of the query is var4, which can come from 2 different places depending on the value of T1.Number
Basically the logic I need to make it work is to either have a case statement in my JOIN. Like, 'LEFT OUTER JOIN TABLE4 on T4.Value=(CASE T1.Number WHEN 0 THEN T2.Result ELSE T3.Result END)'
Is this even possible and if so, how? I need to keep the logic in the main query to preserve performance...
Daily_Time_Entry Fields are: dl_id,dt_id,project_type,project_id,time_st Data in table Daily_Time_Entry
dl_id dt_id project_type project_id time_st 1 03/23/08 AB Corporate 1 1.20 2 03/23/08 AB Corporate 2 3.25 3 03/21/08 AB Corporate 1 2.25 4 03/23/08 AB Plant 1 4.35 5 03/23/08 AB Plant 2 4.50 6 03/23/08 Other Project 1 3.24 7 03/23/08 Other Project 2 4.35
I want to show records as per date from Daily_Time_Entry table and detail data to be displayed as follows
dl_id dt_id project_type project_id time_st exp1 exp2 exp3 owner_name 1 03/23/08 AB Corporate 1 1.20 3 -- -- tmw 2 03/23/08 AB Corporate 2 3.25 2 -- -- hologa 3 03/21/08 AB Corporate 1 2.25 3 -- -- tmw 4 03/23/08 AB Plant 1 4.35 -- 1 -- henry 5 03/23/08 AB Plant 2 4.50 -- 2 -- hologa 6 03/23/08 Other Project 1 3.24 -- -- 2 hologa 7 03/23/08 Other Project 2 4.35 -- -- 3 tmw
Also in project_type AB Corporate for AB_Corporate_Project, AB Plant for AB_Plant_Project , Other Project for Other_Project
I write query for this is as follows
Select dl. dl_id,dl.dt_id,dl.project_type,dl. project_id,dl.time_st,ac.owner_rep_id as exp1,ab. owner_rep_id as exp2,op. owner_rep_id as exp3,ow. owner_name From Daily_Time_Entry dl left outer join AB_Corporate_Project ac on dl. project_id = ac. ab_crp_id and dl. project_type=’ AB Corporate’ left outer join AB_Plant_Project ab on dl. project_id =ab. ab_plant_id and dl. project_type=’ AB Plant’ left outer join Other_Project op on dl. project_id = op. other_proj_id and dl. project_type=’ Other Project’ inner join Owner_Rep ow on (ow. owner_rep_id = ac. owner_rep_id) or(ow. owner_rep_id = ab. owner_rep_id)or (ow. owner_rep_id = op.owner_rep_id)
So how can I write query to show output as follows or any other way or how to create Sql cursors for to show output Plz help to solve this query to show output as specified.
Hi all,I have the following tables:A1==HostID Name RunID------ ---- -----1 host1 NULL2 host2 13 host3 NULLA2==RunID SessionID----- ---------1 42 2A3==SessionID Name--------- ----4 Session12 Session3I want to show every record from A1 with SessionName from A3, unlessthe field RunID in A1 is NULL and then I want to see NULL, like this:HostID Name RunID Name------ ---- ----- ----1 host1 NULL NULL2 host2 1 Session13 host3 NULL NULLwhen I try the following query:select A1.*, A3.Namefrom A1, A2, A3where A1.RunId *= A2.RunId and A2.SessionID = A3.SessionIDI get the following error:The table 'A2' is an inner member of an outer-join clause. This is notallowed if the table also participates in a regular join clause.How can I overcome this problem. Please help. (I use this syntax isteadof joins since I have to supprt also Oracle DB and this syntax issimpler to translate).Thanks in advance,Yaron
Hi,I have a view(A) and I am trying to do a join on another table (B) toinclude only rows where date values in view A is greater than in tableB. I also want the view to pick up rows in viewA based on date values.Here is what I have so far:SELECT *FROM viewA vwleft JOIN tableB tb ONvw.id = tb.id and(vw.date1 > tb.date1 orvw.date2 > tb.date2 orvw.date3 > tb.date3)WHERE vw.date4 > getdate()-1Not matter what kind of join I use I can get both the rows from theview where dateA > getdate()-1 AND where date1-3 are greate than intableB. Dates 1 - 4 seperate date fields. Could someone please tellme what I am doing wrong.Thanks.
HelloLet me explain the problem I am having:I have two tables, data_t and a_data_ta_data_t is the archive table of data_tThe two tables are exactly the same.In the table values are stored:Value (A numeric value)Code (A text code to identify a report with data)Line (The line number)Col (The Col Number)EDate (The date of entry)Grp (A number of a group the data belongs to)I want to get the value from data_t minus the value from a_data_t withthe same Code, Line and Col but with a different EDate (To view thevariance).Here is my statement:select d1.line, d1.col, (IsNull(d1.value,0) - IsNull(d2.value,0)) asvalue from data_t d1full outer join a_data_t d2 on d1.Code = d2.Code and d2.line = d2.lineand d1.col = d2.colwhered1.Code = 'XC001' and d1.line between 1 and 20 and d1.grp = 26and d1.EDate = '2006/06' and d2.grp = 26 and d2.EDate = '2006/05'order by d1.line, d1.colIt works fine EXCEPT when there is a value in either of the tables thatisn't in the other one, then a value is not given.Example:data_t doens't have a value for line=1 and col=2 and grp=26 and Code ='XC001' and EDate = '2006/06'a_data_t has the value of 50000 for the same details (Except Edate of'2006/5')Instead of returning -50000 it doesn't return anything.I hope I could explain it correctly.Any help will be greatly appreciated.Thanks.
Daily_Time_Entry Fields are: dl_id,dt_id,project_type,project_id,time_st Data in table Daily_Time_Entry
dl_id dt_id project_type project_id time_st 1 03/23/08 AB Corporate 1 1.20 2 03/23/08 AB Corporate 2 3.25 3 03/21/08 AB Corporate 1 2.25 4 03/23/08 AB Plant 1 4.35 5 03/23/08 AB Plant 2 4.50 6 03/23/08 Other Project 1 3.24 7 03/23/08 Other Project 2 4.35
I want to show records as per date from Daily_Time_Entry table and detail data to be displayed as follows
dl_id dt_id project_type project_id time_st exp1 exp2 exp3 owner_name 1 03/23/08 AB Corporate 1 1.20 3 -- -- tmw 2 03/23/08 AB Corporate 2 3.25 2 -- -- hologa 3 03/21/08 AB Corporate 1 2.25 3 -- -- tmw 4 03/23/08 AB Plant 1 4.35 -- 1 -- henry 5 03/23/08 AB Plant 2 4.50 -- 2 -- hologa 6 03/23/08 Other Project 1 3.24 -- -- 2 hologa 7 03/23/08 Other Project 2 4.35 -- -- 3 tmw
Also in project_type AB Corporate for AB_Corporate_Project, AB Plant for AB_Plant_Project , Other Project for Other_Project
I write query for this is as follows
Select dl. dl_id,dl.dt_id,dl.project_type,dl. project_id,dl.time_st,ac.owner_rep_id as exp1,ab. owner_rep_id as exp2,op. owner_rep_id as exp3,ow. owner_name From Daily_Time_Entry dl left outer join AB_Corporate_Project ac on dl. project_id = ac. ab_crp_id and dl. project_type=€™ AB Corporate€™ left outer join AB_Plant_Project ab on dl. project_id =ab. ab_plant_id and dl. project_type=€™ AB Plant€™ left outer join Other_Project op on dl. project_id = op. other_proj_id and dl. project_type=€™ Other Project€™ inner join Owner_Rep ow on (ow. owner_rep_id = ac. owner_rep_id) or(ow. owner_rep_id = ab. owner_rep_id)or (ow. owner_rep_id = op.owner_rep_id)
So how can I write query to show output as follows or any other way or how to create Sql cursors for to show output Plz help to solve this query to show output as specified.
............child |parent|.............a1 |a | .............a2 |a |.............a11 |a1 |.............b1 |b |.............b11 |b1 |.............b111 |b1 |............. Here is my table I want to get all childs of "a" ie {a1,a11,a2}I mean recursivelyie child,chid of child ,child of child of child ........etc up to any extentet the table containHow can i for mulate the select querry?
Hi. How can I display output from a simple SQL query in Query Analyzer so that the column heading/broken underline appearing above the column values is not displayed? Something akin to "set heading off".
hi all, can anyone help me?I am a relative newbie to sql server and I am more familiar withEnterprise Manager than QA. I have made many many access databasesthough. I am making an asp.net application where by there are a setnumber of users, about 80, each one logs in and manages informationwithin their department.To get them started a manager has written 10 different hazards thatwill apply to all of the departments, and he has written consequencesand controls for the hazards. Each department must have thisinformation as each will manage and deal with them differentlyThe hazard information is stored in a main 'hazards' table, and theconsequences and controls are stored in related tables linked by the'hazardID' from the main table to a foreign key 'hazardID' in therelated tablesWhat i want to know is if there is a relatively simple way of using aquery to populate the 10 hazards to each department, and to alsoinclude the related table links, i dont mind renaming the departmentsnames to match each hazard, but i do not want to have to relink therelated tables manuallyIf anyone can give me any advice to get me started i will be incrediblygratefulthank youTable information is belowHazards------------HazardID - identity key fieldHazard - varcharDepartment - varcharConsequences----------------------ConsequenceID - identity key fieldHazardID - FKConsequence - varcharControls------------ControlID - identity key fieldHazardID - FKControl - varchardwight
1. to display all parent with ORDER BY ItemOrder (no need to sort by ItemDate) 2. display all child row right after their parent (ORDER BY ItemOrder if ItemDate are same, else ORDER BY ItemDate) 3. display all grand child row right after their parent (ORDER BY ItemOrder if ItemDate are same, else ORDER BY ItemDate)