How Do I Recursively Query A Table?
Jun 28, 2007
Hi,
I'm building an application where items are part of hierarchical "chain" consisting of chain segments.
Here are the relevant tables.
Chains:
Id (int)
UserId (Guid)
ChainSegments:
Id (int)
ChainId (int - foreign key to Chains table)
ParentId (int - foreign key to Id column in same table)
UserId (Guid)
There are more columns in ChainSegments but they are not relevant in this context.
You can see here that ChainSegments belong to Chains and ChainSegments can have other ChainSegments as children.
I'm trying to write a recursive Sql query that finds a ChainSegment for a given ChainId and recursively selects its "child" ChainSegments for a given number of iterations. Hope this is making sense so far :-)
Here's what I've got:
GO
WITH ChainSegmentTree (Id, ParentId, Level)
AS
(
-- Anchor member definition
SELECT a.Id, a.ParentId,
0 AS Level
FROM ChainSegments AS a
INNER JOIN ChainSegments AS b
ON a.Id = b.ParentId
WHERE a.ParentId IS NULL
UNION ALL
-- Recursive member definition
SELECT a.Id, a.ParentId,
Level + 1
FROM ChainSegments AS a
INNER JOIN ChainSegments AS b
ON a.Id = b.ParentId
INNER JOIN ChainSegmentTree AS c
ON a.Id = c.ParentId
)
-- Statement that executes the CTE
SELECT e.Id, e.ParentId, Level
FROM ChainSegmentTree AS e
INNER JOIN ChainSegments AS f
ON e.Id = f.Id
WHERE Level = 0;
GO
I've based this on an example I found here:
http://technet.microsoft.com/en-us/library/ms186243.aspx
Unfortunately this only returns one row, the "root" ChainSegment (ParentId = null) and nothing else.
I'm admittedly rubbish at Sql and would really appreciate any help that could be offered here.
Many thanks,
Ed
View 7 Replies
ADVERTISEMENT
Feb 12, 2001
Hi !
I have an EMPLOYEE table as below.
Table - EMPLOYEE
Id (Int) (P)
EmployeeName Varchar(30)
Parent_Id (Int) (Reference to EMPLOYEE.Id)
I want to retrieve all the Employees of any given Manager.
For eg: Given a CEO, I want to retrieve all the Managers and Sub Managers and Sub Sub Managers ... under it.
This is a typical example of a Self join Table. How can I do that.
Can anyone help ??
Regards.
View 3 Replies
View Related
May 19, 2006
I have a Table that contains Items of the Type "Step". The primary keyis "StepID". Each step can have have a target step, wich represents asubsequent step. So I have a Foreign key relationship within the sametable:Primary Key: StepID --> Foreign Key: TargetStepIDNow if I want to insert a group of new Steps into the table, I can onlyinsert steps whose target step is already insterted to the table. Howwould I solve this problem ? Do I need to write my own client side (Iam using ADO.NET / C#) that loops through the targetsteps and insertsthe targetsteps first ? Or is there a more celver way to do this ?
View 4 Replies
View Related
Oct 18, 2005
I have found the Common Table Expressions described in SQL 2005 and Iam not sure if it applies to this situation.Here are the tables<PRE><B>ManagedServer Table</B>--IdManagedServer (PK, int, not Null)--Name (nvarchar(256), not null)<B>ManagedServerToManagedServer Table</B>--IdParentManagedServer (PK, int, not null)--IdChildManagedServer (PK, int, not null)</PRE>The following will give you the parent-- Get Managed Server Group NamesLEFT OUTER JOIN ManagedServerToManagedServer mstms ONms.IdManagedServer = mstms.IdChildManagedServerLEFT OUTER JOIN ManagedServer msg ON mstms.IdParentManagedServer =msg.IdManagedServerHow would you go about getting all of the "parents" in the tree?Can this be done with CTEs? Unfortuately all of the examples found arejoining on itself.
View 1 Replies
View Related
Aug 16, 2015
I want to recursively select all records within a hierarchy, using the main parentid and a textvalue on level 1 OR level 2 of the subcategories.
My data:
CREATE TABLE [dbo].[articlegroups](
[id] [int] NOT NULL,
[parentid] [int] NOT NULL,
[catlevel] [tinyint] NOT NULL,
[slug_en] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_globos_articlegroups] PRIMARY KEY CLUSTERED
[Code] ...
When selecting rows I always have the main parentId (so catlevel 0) and the slug_en value.
In my example case I have id 129 and slug_en='cradles'.
I want my query to then return:
idparentidcatlevel
12900
1301291
1361302If I have id 129 and slug_en='pillows'.
I want my query to then return:
idparentidcatlevel
12900
1391291
How can I do this? I'm new to SQL Server. I was reading here [URL] .... on recursive SQL, but how to implement this as I just have one table and I also have 2 selection criteria (main category id and a text value on either level 1 or 2).
View 9 Replies
View Related
Nov 10, 2006
I have a table within a table that contains descriptions of work done as strings. Some of these need to be edited after a report is generated so it needs to be exported to Excel.
As everyone knows Excel can't process a table within a table so I need a way to concatenate all the separate row entries in the nested table to one Field entry so the nested table is no longer necessary.
Is there a way to recursively concatenate strings from the report designer?
The number of rows that need to be concatenated is variable so it has to be flexible.
View 2 Replies
View Related
Jul 20, 2005
Hi all.If my table looks like the followingEMPLID NAME BU SAL ELIG_CONFIG11001 Tom 10 500001002 Sarah 10 490001003 John 20 450001005 Jane 10 67000Now I would like to populate ELIOG_CONFIG with the value that is inBU. How is this done recursively so that Tom's ELIG-CONFIG1 = 10 andJohn's ELIG_CONFIG1 = 20 etc.EMPLID NAME BU SAL ELIG_CONFIG11001 Tom 10 50000 101002 Sarah 10 49000 101003 John 20 45000 201005 Jane 10 67000 10update PS_JOB set ELIG_CONFIG1 = (select BU from PS_JOB where.........)How is this done recursively thorugh the whole table?Does this make sense. Assume for example that EMPLID is KEY.John
View 2 Replies
View Related
Jun 26, 2015
how do I get the variables in the cursor, set statement, to NOT update the temp table with the value of the variable ? I want it to pull a date, not the column name stored in the variable...
create table #temptable (columname varchar(150), columnheader varchar(150), earliestdate varchar(120), mostrecentdate varchar(120))
insert into #temptable
SELECT ColumnName, headername, '', '' FROM eddsdbo.[ArtifactViewField] WHERE ItemListType = 'DateTime' AND ArtifactTypeID = 10
--column name
declare @cname varchar(30)
[code]...
View 4 Replies
View Related
Jun 25, 2007
Hi, all experts here,
I am wondering if tempdb stores all results tempararily whenever I query a large fact table with over 4 million records which joins another dimension table? Since each time when I run the query, the tempdb grows to nearly 1GB which nearly runs out all the space on my local system drive, as a result the performance totally down. Is there any way to fix this problem? Thanks a lot in advance and I am looking forward to hearing from you shortly for your kind advices.
With best regards,
Yours sincerely,
View 11 Replies
View Related
Jul 19, 2012
I don't know if it's a local issue but I can't use temp table or table variable in a PP query (so not in a stored procedure).
Environment: W7 enterprise desktop 32 + Office 2012 32 + PowerPivot 2012 32
Simple example:
declare @tTable(col1 int)
insert into @tTable(col1) values (1)
select * from @tTable
Works perfectly in SQL Server Management Studio and the database connection is OK to as I may generate PP table using complex (or simple) queries without difficulty.
But when trying to get this same result in a PP table I get an error, idem when replacing table variable by a temporary table.
Message: OLE DB or ODBC error. .... The current operation was cancelled because another operation the the transaction failed.
View 11 Replies
View Related
Oct 30, 2006
I have successfully execute a union query. How can i create a make-table query to accomodate the resultset of the union query?
View 2 Replies
View Related
Mar 9, 2006
Hi,
Does anyone has query to give all table sizes on a database?
Appreciate your help.
Thanks
View 2 Replies
View Related
Oct 23, 2014
I need to name make the name of a column the same as the name of a table from the result of a sql query.. here is the assignment question below..I can't figure out how to get the name of the table to be inputed as the column name..
Write a script that uses dynamic SQL to return a single column that represents the number of rows in the first table in the current database. The script should automatically choose the table that appears first alphabetically, and it should exclude tables named dtproperties and sysdiagrams. [highlight=#ffff11]Name the column CountOfTable, where Table is the chosen table name.[/highlight]
Hint: Use the sys.tables catalog view.
I can figure out the rest. and actually have alredy done it, but i cannot figure out how to do the part that is highlighted above. I looked at lots of things on google to figure it out but no luck..Can some just give me some directlon or an example..
View 14 Replies
View Related
Jul 22, 2015
I am trying to optimize a stored procedure in SQL 2008. When I look at an actual execution plan generated from when I run it in SSMS it shows a table being used in the plan that has no relation to what is actually in the query script and this is where the biggest performance hit occurs.
I've never seen a table show up before that wasn't part of the query. why this might occur and how to correct it? I can't just change the query script because the table in question isn't there.
View 10 Replies
View Related
Nov 28, 2006
I want to make a query, stored procedure, or whatever which will only display the primary key where there does no exist a foreign key in linked table.For example. If I had two tables with a one to many relationship.A [Computer] has one or more [Hard Drives]. I want to select only those computers which do not have a Hard Drive(s) associated with them. That is, show all computers where the Computer_ID field in the [Hard Drives] table does not exist. This seems simple but I'm drawing a blank here.
View 1 Replies
View Related
Dec 20, 2007
I have set up a 'Parameters' table that solely stores all pre-assigned selection values for a webform. I customized a stored query to Select the values from the Parameters table. I set up the webform. The result is that the form1.apsx automatically populates each DropDownList task with the pre-assigned values from the 'Parameters' table (for example, the stored values in the 'Parameters' table 'Home', 'Business', and 'Other' populate the drop down list for 'Type').
The programming to move the selected data from form1.aspx to a new table in the SQL database perplexes me. If possible, I would like to use the form1.aspx to Postback (or Insert) the "selected" data to a *new* column in a *new* table (such as writing the data to the 'CustomerType' column in the 'Customers' table; I clearly do not want to write back to the 'Parameters' table). Any help to get over this hurdle would be deeply appreciated.
View 1 Replies
View Related
Jun 18, 2004
Strange one here - I am posting this in both SQL Server and Access forums
Access is telling me it can't append any of the records due to a key violation.
The query:
INSERT INTO dbo_Colors ( NameColorID, Application, Red, Green, Blue )
SELECT Colors_Access.NameColorID, Colors_Access.Application, Colors_Access.Red, Colors_Access.Green, Colors_Access.Blue
FROM Colors_Access;
Colors_Access is linked from another MDB and dbo_Colors is linked from SQL Server 2000.
There are no indexes or foreign contraints on the SQL table. I have no relationships on the dbo_ table in my MDB. The query works if I append to another Access table. The datatypes all match between the two tables though the dbo_ tables has two additional fields not refrenced in the query.
I can manually append the records using cut and paste with no problems.
I have tried re-linking the tables.
Any ideas?
Thanks,
Brad
View 4 Replies
View Related
Jan 28, 2012
I need to add a child table that will tell us who the participants counselor is, what I did was I did a Make Table query based off the primary key of the Parent table and made that the link (foreign key) for the People_tbl and the Counselor_tbl, so if the counselor changes then the user adds the record to the counselor tbl and then puts in the Effective date. The problem is that when I run a report it doesn't show the present counselor always shows the old counselor?
Code:
SELECT Student_ind.StudentFirstName, Student_ind.StudentLastName, Student_ind.[Student ID], People_tbl.[Family ID], People_tbl.FirstName,
People_tbl.LastName, People_tbl.[Parent ID]
FROM People_tbl RIGHT OUTER JOIN
Student_ind ON People_tbl.[Family ID] = Student_ind.[Family ID]
WHERE (People_tbl.LastName = @Enter_LastName) AND (People_tbl.FirstName = @Enter_FirstName)
View 5 Replies
View Related
Feb 13, 2008
I have two tables that share a common identity row. I need to build a query where data that exists in one table does not contain data in the other table. For example, table 1 has columns of Owner_ID, LastName, FirstName and table 2 has columns Auto_ID, Owner_ID, AutoMake. Both tables are joined by the Owner_ID column. I need a query that provides all owners from table 1 who do not have an entry in table 2.
Thanks in advance,
Mark
View 5 Replies
View Related
May 21, 2015
convert my table(like picture) to hierarchical structure in SQL. actually i want to make a table from my data in SQL for a TreeList control datasource in VB.net application directly.
ProjectID is 1st Parent
Type_1 is 2nd Parent
Type_2 is 3rd Parent
Type_3 is 4ed Parent
View 13 Replies
View Related
Aug 5, 2007
I have the following query in sql 2005:
PROCEDURE [dbo].[uspInsert_Blob] (
@fName varchar(60),
@fType char(5),
@fID numeric(18, 0),
@bID char(3),
@fPath nvarchar(60)
)
as
DECLARE @QUERY VARCHAR(2000)
SET @QUERY = "INSERT INTO tblDocTable(FileName, FileType, ImportExportID, BuildingID, Document)
SELECT '"+@fName+"' AS FileName, '"+@fType+"' AS FileType, " + cast(@fID as nvarchar(18)) + " as ImportExportID, '"+@bID+"' AS BuildingID, * FROM OPENROWSET( BULK '" +@fPath+"' ,SINGLE_BLOB)
AS Document"
EXEC (@QUERY)
This puts some values including a pdf or .doc file into a table, tblDocTable.
Is it possible to change this so that I can get the values from a table rather than as parameters. The Query would be in the form of: insert into tblDocTable (a, b, c, d) select a,b,c,d from tblimportExport.
tblImportExport has the path for the document (DocPath) so I would subsitute that field, ie. DocPath, for the @fPath variable.
Otherwise I can see only doing a Fetch next from tblIportExport where I would put every field into a variable and then run this exec query on these. Thus looping thru every row in tblImportExport.
Any ideas how to do this?
View 1 Replies
View Related
Jan 9, 2008
This program gets the values of A and B passed in. They are for table columns DXID and CODE. The textbox GET1 is initialized to B when the page is loaded. When I type another value in GET1 and try to save it, the original initialized value gets saved and not the new value I just typed in. A literal value, like "222" saves but the new GET1.TEXT doesn't.
View 1 Replies
View Related
Jul 22, 2012
All, Using access 2003 frontend and sql server 2008 backend. I have an append query to insert 80000 from one table to an empty table. I get an error:
"Microsoft Office Access set 0 field(s) to Null due to a type conversion failure, and didn't add 36000 record(s) to the table due to key violations, 0 record(s) due to lock violations, and 0 record(s) due to validation rule violations."
I know this error normally comes if there are dups in a field that doesnt allow.
View 1 Replies
View Related
Dec 14, 2007
hi all,
is there any query to move certain data from a sql data to access table through query. i am having a requirement where i have to fetch the records from a sql table that falls within a specified range to a ms access table. is this possible through a query.
thanks
View 5 Replies
View Related
Jun 7, 2012
I have a database that has 370 tables that match %_REF_% naming. All of these tables have a column call ds_name.
I need to get a list of all values of ds_name for each table.
View 3 Replies
View Related
Jul 29, 2015
To avoid locking/blocking, or in transaction scope, we are trying make a common practice of writing coide for update commands in our all SPs based on primary key columns in where clause. I have a following scenario...
UPDATE [dbo].[TL_CST_Locker_Issuance] SET
[isActive] = 0
WHERE
LockerIssuanceId IN (SELECT LockerIssuanceId
[Code] ...
What is the better approach and should be followed to avoid locks and gain performance or best approach.
View 7 Replies
View Related
Mar 25, 2004
I want to use a Make Table Query to generate a new read-only Table. This I can do but my problem is that I want to be able to name the new Table containing only the records from a calendar year; e.y. Rents2001 and the next year another new table would be created and called Rents2002 and next year Rents2003 ...............
I require the Table to be generated yearly. I know I could do this in other ways but I really require the Table as once I have it I will be doing other things with it to give the final report.
Any suggestions how I can generate the Table with the YEAR being in the Table Name as part of running the Make Table Query? Thanks
View 4 Replies
View Related
Feb 4, 2008
I have recently moved jobs and have come across an unusual database setup that is not ideal for the resolution of my task at hand.
I need to query table A, which will return 1 and only 1 tablename as a result. there are various tablenames on table A but the query will always return a unique result. (from Table B-G for example)
My problem is now, how do i run my next query on the table i have returned from my first query. I need to be able to reference the value.
Making sense?
Ideal scenario would be if tables B-G were on a single table and had a unique identifier, but this architecture cannot be changed for numerous reasons and a workaround needs to be established. your help is much appreciated,
View 19 Replies
View Related
Aug 24, 2007
This is what I wan to do: If I, for example, have a table containing articles, and I want to allow users to return any article that matches a filter, which is defined by any number of keywords, located in another table.
My tables:
Article table: [ArticleID, Headline, Content]
Filter table: [FilterID, Name]
Keyword table: [KeywordID, Word]
FiltersKeywords table: [FilterID, KeywordID]
(The FiltersKeywords table serves as a many-to-many relation table between the Keyword table and the Filter table)
In other words, a filter, which is used to selected articles with, can be made up of any number of keywords. The users would thus be able to build on the filters, adding new keywords as time goes, removing old none relevant etc. I suspect some filters could end having anywhere from 100 to 1000 keywords associated with them.
Using SQL 2005, is there anyway to query for articles in an efficient manner? How would the code look?
Thanks, Egil.
View 3 Replies
View Related
Nov 6, 2006
Hi all,
I am querying a table in oracle, the server connection to the Oracle database is determined by a criteria. Though how can I put the results from the oracle query into a temp table ?
This is the code i'm using for the query:
DECLARE @cmd VARCHAR(500)
declare @Year varchar(25)
set @Year = '2006'
DECLARE @Link VARCHAR(100)
DECLARE @Table VARCHAR(100)
select @Link = Server from tbl_Conn where Area='Floor'
select @Table = Target_Table from tbl_Conn where Area='Floor'
SET @cmd =
'
select * from OPENQUERY
(
' + @Link + ',
''
UPDATE '+ @Table +'
SET TARGET_VALUE = '+@Value+'
WHERE Date = '+@Year'
''
)
'
EXEC (@cmd)
How do I put the executed results into a TEMP table ?
Rgds,
View 2 Replies
View Related
Jun 27, 2014
I am trying to run a UNION ALL query in SQL SERVER 2014 on multiple large CSV files - the result of which i want to get into a table in SQL Server. below is the query which works in MSAccess but not on SQL Server 2014:
SELECT * INTO tbl_ALLCOMBINED FROM OPENROWSET
(
'Microsoft.JET.OLEDB.4.0' , 'Text;Database=D:DownloadsCSV;HDR=YES',
'SELECT t.*, (substring(t.[week],3,4))*1 as iYEAR,
''SPAIN'' as [sCOUNTRY], ''EURO'' as [sCHAR],
[Code] ....
What i need is:
1] to create the resultant tbl_ALLCOMBINED table
2] transform this table using PIVOT command with following transformation as shown below:
PAGEFIELD: set on Level = 'Item'
COLUMNFIELD: Sale_Week (showing 1 to 52 numbers for columns)
ROWFIELD: sCOUNTRY, sCHAR, CATEGORY, MANUFACTURER, BRAND, DESCRIPTION, EAN (in this order)
DATAFIELD: 'Sale Value with Innovation'
3] Can the transformed form show columnfields >255 columns i.e. if i want to show all KPI values in datafield?
P.S: the CSV's contain the same number of columns and datatype but the columns are >100, so i dont think it will be feasible to use a stored proc to create a table specifying that number of columns.
View 9 Replies
View Related
Feb 13, 2006
We have the following two tables :
Link ( GroupID int , MemberID int )
Member ( MemberID int , MemberName varchar(50), GroupID varchar(255) )
The Link table contains the records showing which Member is in which Group. One particular Member can be in
multiple Groups and also a particular Group may have multiple Members.
The Member table contains the Member's ID, Member's Name, and a Group ID field (that will contains comma-separated
Groups ID, showing in which Groups the particular Member is in).
We have the Link table ready, and the Member table' with first two fields is also ready. What we have to do now is to
fill the GroupID field of the Member table, from the Link Table.
For instance,
Read all the GroupID field from the Link table against a MemberID, make a comma-separated string of the GroupID,
then update the GroupID field of the corresponding Member in the Member table.
Please help me with a sql query or procedures that will do this job. I am using SQL SERVER 2000.
View 1 Replies
View Related
Dec 20, 2013
this is my first table
CID-----BID---EID-----Ename-------------Phone---------CELL NO
1--------1----7--------A---------------5047183-----03138236415
1--------1----15-------B---------------5045107-----03212634704
this is my second table
CID-----BID---EID-----Ename-------------Phone---------CELL NO
1--------1----7---------A------------------------------------
1--------1----15--------B------------------------------------
i want a query to update my second table from first table. like this after execute query my second table look like this
CID-----BID---EID-----Ename-------------Phone---------CELL NO
1--------1----7--------A---------------5047183-----03138236415
1--------1----15-------B---------------5045107-----03212634704
View 1 Replies
View Related