Path Query In Cyclic Graph? --recursive CTE

Jun 11, 2006

Hi

I wrote a simple sql query to get the shortest path length from node 1 to all the other nodes. Since there's a loop in the graph, I want to prevent it from going back to some nodes it has expanded before.

I got the following error:

Msg 253, Level 16, State 1, Line 2
Recursive member of a common table expression 'CTE_Sample' has multiple recursive references.

It is referring to "and Table1.t NOT IN (select fr from CTE_Sample)"

Can somebody help me to solve it?

btw. How to use the UNION, EXCEPT or INTERSECT operators when doing the recursive join? It seems I must use UNION ALL.



Thanks!

drop table Table1
CREATE TABLE Table1 ( fr int, t int)
INSERT Table1 VALUES (1, 2)
INSERT Table1 VALUES (2, 3)
INSERT Table1 VALUES (3, 4)
INSERT Table1 VALUES (1, 3)
INSERT Table1 VALUES (1, 4)
INSERT Table1 VALUES (4, 5)

INSERT Table1 VALUES (4, 2)

GO

WITH CTE_Sample (fr, t, level) AS
(
SELECT Table1.fr, Table1.t, 1 AS level
FROM Table1
WHERE fr=1
UNION ALL
SELECT Table1.fr, Table1.t, level+1
FROM Table1
INNER JOIN CTE_Sample ON Table1.fr = CTE_Sample.t
and Table1.t NOT IN (select fr from CTE_Sample)
)
SELECT CTE_Sample.t, min(CTE_Sample.level)
FROM CTE_Sample
group by CTE_Sample.t

View 2 Replies


ADVERTISEMENT

Finding All Minimal Cyclic Paths In The Graph

Oct 1, 2003

Here a code for finding all minimal loops (cyclic paths) in a graph
with vertexes of degree >= 3. Almost obviously that before seeking
for loops we should eliminate from the graph all its vertexes of degree < 3
(degree of a vertex is the number of edges outcoming from the vertex).
Note: there are no any 'parent' - 'child' nodes here. All vertexes are
absolutely equitable.
if object_id('g3')>0 drop table g3
if object_id('g3x')>0 drop table g3x
if object_id('g3y')>0 drop table g3y
if object_id('g3l')>0 drop table g3l
GO
create table g3y(v1 int, v2 int) -- ancillary table
GO
create table g3x(n int, v1 int, v2 int) -- ancillary table
GO
create table g3l(nl int, v1 int, v2 int)
-- table for storing of 'detected' loops
GO
create table g3(v1 int, v2 int)
-- table of test data with pairs of adjoining vertexes
-- each vertex is named by an arbitrary number
GO
insert into g3
select 2, 3 union all
select 2, 4 union all
select 1, 4 union all
select 3, 5 union all
select 5, 6 union all
select 1, 6 union all
select 4, 7 union all
select 6, 8 union all
select 3, 9 union all
select 1, 7 union all
select 2, 7 union all
select 1, 8 union all
select 5, 8 union all
select 2, 9 union all
select 5, 9 ----union all
/*
select 2, 13 union all
select 3, 13 union all
select 13, 14 union all
select 12, 14 union all
select 12, 15 union all
select 11, 15 union all
select 11, 13 union all
select 10, 11 union all
select 10, 12 union all
select 10, 14 union all
select 10, 15
*/
GO
insert into g3 select v2, v1 from g3

declare @i int, @n int, @v1 int, @v2 int
set @i=1

while 0=0
begin
set @n=1
truncate table g3x truncate table g3y
select top 1 @v1=g3.v1, @v2=g3.v2 from g3 left join g3l on
(g3.v1=g3l.v1 and g3.v2=g3l.v2)or(g3.v1=g3l.v2 and g3.v2=g3l.v1)
where g3l.nl is null if @@rowcount=0 break
insert into g3x select @n, @v1, @v2

while @v1<>(select top 1 v2 from g3x order by n desc)
begin
set @n=@n+1
insert into g3x select top 1 @n, v1, v2 from g3 where v2=@v1
and v1<>@v2 and v1=(select top 1 v2 from g3x order by n desc)

if @@rowcount=0
begin
insert into g3x select top 1 @n, v1, v2 from g3 where
v2 not in (select v1 from g3x union all select v2 from g3x) and
v1=(select top 1 v2 from g3x order by n desc) and not exists
(select 0 from g3y where g3y.v1=g3.v1 and g3y.v2=g3.v2)
if @@rowcount=0
if @n>2
begin
insert into g3y select v1, v2 from g3x where n=@n-1
delete from g3x where n=@n-1
set @n=@n-2
end
else
begin insert into g3l select 0, v1, v2 from g3x break end
end
else
begin
insert into g3l select @i, v1, v2 from g3x set @i=@i+1
end
end
end
select * from g3l order by nl
Below is what we get:

nl v1 v2
----------- ----------- -----------
1 2 3
1 3 5
1 5 6
1 6 8
1 8 1
1 1 4
1 4 2

2 1 6
2 6 8
2 8 1

3 4 7
3 7 1
3 1 4

4 3 9
4 9 2
4 2 3

5 2 7
5 7 4
5 4 2

6 5 8
6 8 6
6 6 5

7 5 9
7 9 3
7 3 5
Of course, in general case not all found by the code loops are minimal.
But this is exactly my approach:
firstly find any possible loops (avoiding excessiveness!!),
then, in WHILE loop, try to mark out minimal loop(s) from intersection of
two non-minimal loops... seems it will be an interesting t-sql job.

View 17 Replies View Related

SQL Server 2012 :: Using Recursive Query To Find Path Between Assembly And Parts?

Jul 2, 2014

I'm trying to use a recursive query to find path between assembly and parts.

The BOM is similar to(I've limited the number of rows and lines):

BOM NumberMat Number
20000222001770
20000222003496
20000222001527
20000222003495
20002462002005
20005062000246

[code]....

How should I modify it so that is returns the 4 path?

View 1 Replies View Related

Recursive Complete Path On SQL SERVER 2005 ???

Apr 18, 2008

Dear,

I'm having this table:

PathIDParentPathIDPath
1 NULL D:
2 1 Sections
3 2 Bin
4 3 Data
5 4 FinancialReport.doc
6 4 DebtReport.doc
7 3 db.dll

I would like to create a store procedures that will return me a full path by passing a PathID

I started with this code:

DECLARE @path_id int
SET @path_id = 5;
WITH fullPath (PathID, ParentPathID, Path)
AS
(
SELECT PathID, ParentPathID, Path
FROM tblPath WHERE PathID = @path_id
UNION ALL
SELECT tblPath.PathID, tblPath.ParentPathID, tblPath.Path AS Path
FROM tblPath
JOIN fullPath ON tblPath.PathID = fullPath.ParentPathID
)
SELECT * FROM fullPath

This code will return this:
1 NULL D:
2 1 Sections
3 2 Bin
4 3 Data
5 4 FinancialReport.doc

What I would like to get is something like this:
D:/Sections/Bin/Data/FinancialReport.doc

Any help would be really appreciated. Lost too much time on it already.
Thanks,
pharvey

View 9 Replies View Related

Need To Go Down Path To Find If Everything Is Settled (recursive Possibly)

May 1, 2007

I have the following table.GO/****** Object: Table [dbo].[itTransactionProcess] Script Date:05/01/2007 10:42:31 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[itTransactionProcess]([TransactionID] [int] IDENTITY(1,1) NOT NULL,[LotNumber] [int] NOT NULL,[CurrentProcessStepID] [int] NOT NULL,[NextProcessStepID] [int] NULL,[CategoryID] [int] NULL,[ProductID] [int] NULL,[ProductVariantID] [int] NULL,[ParentTransactionID] [int] NULL,[TransactionDateEntered] [datetime] NULL,[TransactionDateExit] [datetime] NULL,[Settlement] [money] NULL,[Completed] [int] NULL,CONSTRAINT [PK_itTransactionProcess] PRIMARY KEY CLUSTERED([TransactionID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY= OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]Sample data is as followsBasically what I need to do is return the lotid where all path have asettlement date.this is my current procedure/****** Object: StoredProcedure [dbo].[getPendingSettlementDetails] Script Date: 05/01/2007 10:47:47******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[getPendingSettlementDetails]ASdeclare @LotNumbersTable table(LotNumber int)insert into @LotNumbersTable EXEC GetPendingSettlementsLotNumbersDeclare @ResultsTable table(LotNumber int, Company varchar(150),Contact varchar(150), DateReceived datetime, DateComplete datetime,SettlementLength int)Declare @LotNumber intDeclare @DateRecieved datetime, @DateComplete datetimeDeclare @NumberOfDaysForSettlement intDeclare @Company varchar(150)Declare @Contact varchar(150)select @LotNumber = min(LotNumber) from @LotNumbersTablewhile @LotNumber is not null beginSelect @DateRecieved = min(TransactionDateEntered) fromitTransactionProcess where LotNumber = @LotNumberSelect @DateComplete = max(TransactionDateExit) fromitTransactionProcess where LotNumber = @LotNumber and Settlement isnot nullSET @NumberOfDaysForSettlement = DATEDIFF(DAY, @DateRecieved,@DateComplete)Select @Company = Company from SP_Active_Lot_Deliveries where LotID =@LotNumberSelect @Contact = ContactName from SP_Active_Lot_Deliveries whereLotID = @LotNumberINSERT INTO @ResultsTable (LotNumber, DateReceived, DateComplete,SettlementLength, Company, Contact) Values(@LotNumber, @DateRecieved, @DateComplete,@NumberOfDaysForSettlement, @company, @contact)select @LotNumber = min(LotNumber) from @LotNumbersTable whereLotNumber @LotNumberendSelect * From @ResultsTable where SettlementLength is not nullhere is sample data"TransactionID","LotNumber","CurrentProcessStepID","NextProcessStepID","CategoryID","ProductID","ProductVariantID","ParentTransactionID","TransactionDateEntered","TransactionDateExit","Settlement","Completed""628","47","1","2","5","","","","","2007-05-0110:23:15.747000000","","""629","47","1","3","17","","","","","2007-05-0110:23:15.747000000","0.25","""630","47","1","4","34","","","","","2007-05-0110:23:15.747000000","-0.15","""631","47","1","3","38","","","","","2007-05-0110:23:15.747000000","-0.15","""632","47","1","4","33","","","","","2007-05-0110:23:15.747000000","-0.35","""633","47","1","3","15","","","","","2007-05-0110:23:15.747000000","10","""634","47","2","3","86","","","628","2007-05-0110:23:15.747000000","2007-05-01 10:32:41.320000000","-0.35","""635","47","3","","17","","","629","2007-05-0110:23:15.747000000","","","""636","47","4","","34","","","630","2007-05-0110:23:15.747000000","","","""637","47","3","","38","","","631","2007-05-0110:23:15.747000000","","","""638","47","4","","33","","","632","2007-05-0110:23:15.747000000","","","""639","47","3","","15","","","633","2007-05-0110:23:15.747000000","","","""640","47","2","3","85","","","628","2007-05-0110:24:47.983000000","2007-05-01 10:32:41.320000000","0.05","""641","47","2","4","88","","","628","2007-05-0110:24:56.343000000","2007-05-01 10:32:41.333000000","0.8","""642","47","2","4","9","","","628","2007-05-0110:25:07.517000000","2007-05-01 10:32:41.333000000","-0.15","""643","47","2","4","100","","","628","2007-05-0110:25:22.470000000","2007-05-01 10:32:41.333000000","-0.35","""644","47","2","4","90","","","628","2007-05-0110:25:44.297000000","2007-05-01 10:32:41.333000000","-0.35","""645","47","2","4","12","","","628","2007-05-0110:25:59.347000000","2007-05-01 10:32:41.333000000","-0.15","""646","47","2","4","26","","","628","2007-05-0110:26:12.610000000","2007-05-01 10:32:41.333000000","-0.35","""647","47","2","3","94","","","628","2007-05-0110:26:29.523000000","2007-05-01 10:32:41.333000000","-3","""648","47","2","3","95","","","628","2007-05-0110:26:47.323000000","2007-05-01 10:32:41.333000000","-0.35","""649","47","2","3","38","","","628","2007-05-0110:27:01.450000000","2007-05-01 10:32:41.333000000","-0.15","""650","47","2","4","33","","","628","2007-05-0110:27:15.533000000","2007-05-01 10:32:41.333000000","-0.35","""651","47","2","4","34","","","628","2007-05-0110:27:33.767000000","2007-05-01 10:32:41.333000000","-0.15","""652","47","2","3","96","","","628","2007-05-0110:27:46.850000000","2007-05-01 10:32:41.350000000","-0.35","""653","47","2","3","97","","","628","2007-05-0110:28:00.917000000","2007-05-01 10:32:41.350000000","0.05","""654","47","2","4","36","","","628","2007-05-0110:28:10.813000000","2007-05-01 10:32:41.350000000","-15","""655","47","2","4","37","","","628","2007-05-0110:28:25.347000000","2007-05-01 10:32:41.350000000","0.35","""656","47","2","3","98","","","628","2007-05-0110:28:36.917000000","2007-05-01 10:32:41.350000000","-0.35","""694","47","2","10","26","","","628","2007-05-0110:32:17.170000000","2007-05-01 10:32:41.350000000","","""695","47","2","10","35","","","628","2007-05-0110:32:27.883000000","2007-05-01 10:32:41.350000000","45","""696","47","3","","86","","","634","2007-05-0110:32:41.320000000","","","""697","47","3","","85","","","640","2007-05-0110:32:41.333000000","","","""698","47","4","","88","","","641","2007-05-0110:32:41.333000000","","","""699","47","4","","9","","","642","2007-05-0110:32:41.333000000","","","""700","47","4","","100","","","643","2007-05-0110:32:41.333000000","","","""701","47","4","","90","","","644","2007-05-0110:32:41.333000000","","","""702","47","4","","12","","","645","2007-05-0110:32:41.333000000","","","""703","47","4","","26","","","646","2007-05-0110:32:41.333000000","","","""704","47","3","","94","","","647","2007-05-0110:32:41.333000000","","","""705","47","3","","95","","","648","2007-05-0110:32:41.333000000","","","""706","47","3","","38","","","649","2007-05-0110:32:41.333000000","","","""707","47","4","","33","","","650","2007-05-0110:32:41.333000000","","","""708","47","4","","34","","","651","2007-05-0110:32:41.333000000","","","""709","47","3","","96","","","652","2007-05-0110:32:41.350000000","","","""710","47","3","","97","","","653","2007-05-0110:32:41.350000000","","","""711","47","4","","36","","","654","2007-05-0110:32:41.350000000","","","""712","47","4","","37","","","655","2007-05-0110:32:41.350000000","","","""713","47","3","","98","","","656","2007-05-0110:32:41.350000000","","","""714","47","10","","26","","","694","2007-05-0110:32:41.350000000","","","""715","47","10","","35","","","695","2007-05-0110:32:41.350000000","","",""If you follow transaction id 714 up through the parent transaction idsit doesn't not have a settlement cost yet lot 47 shows up as settled.Thanks for you help.

View 6 Replies View Related

Transact SQL :: Types Don't Match Between Anchor And Recursive Part In Column ParentID Of Recursive Query

Aug 25, 2015

Msg 240, Level 16, State 1, Line 14

Types don't match between the anchor and the recursive part in column "ParentId" of recursive query "tmp". Below is query,

DECLARE @TBL TABLE (RowNum INT, DataId int, DataName NVARCHAR(50), RowOrder DECIMAL(18,2) NULL, ParentId INT NULL)
INSERT INTO @TBL VALUES
(1, 105508, 'A', 1.00, NULL),
(2, 105717, 'A1', NULL, NULL),
(3, 105718, 'A1', NULL, NULL),
(4, 105509, 'B', 2.00, NULL),
(5, 105510, 'C', 3.00, NULL),
(6, 105514, 'C1', NULL, NULL),

[code]....

View 2 Replies View Related

SQL 2012 :: Write Query Which Runs In Background On Cyclic Basis

Jul 9, 2014

I want to write sql query which runs in a background on cyclic basis. Basically i want to count the row entries of 1 table and store the data and the count in two distinct columns.

View 3 Replies View Related

Query Regarding Cumulative Count And Graph

Mar 29, 2007

Can we calculate Cumulative Count using Runnning value function like it is in 2005 reporting services. If any other alternative please let me know.



Also I have few queries regarding graph.

Can we breakup graph if the scale is more than the certain range?

Can we adjust the scale/Range of the graph depending on the certain parameters from Dataset?



Thank you,



Regards,

Palak Shah

View 3 Replies View Related

Cyclic Redundancy Check?

Feb 25, 2000

I was trying to modify a table and I got a "data error: cyclic redundancy check"

So I ran a DBCC CHECKDB and got this:

Server: Msg 823, Level 24, State 1, Line 3
I/O error 23(Data error (cyclic redundancy check)) detected during read of BUF pointer = 0x11c902c0, page ptr = 0x14d66000, pageid = (0x1:0x3d), dbid = 26, status = 0x801, file = d:MSSQL7datacontent_Data.MDF.

Connection Broken

This is scary stuff! What does it mean and how do I fix it?

View 2 Replies View Related

How To Convert Recursive Function Into Recursive Stored Procedure

Jul 23, 2005

I am having problem to apply updates into this function below. I triedusing cursor for updates, etc. but no success. Sql server keeps tellingme that I cannot execute insert or update from inside a function and itgives me an option that I could write an extended stored procedure, butI don't have a clue of how to do it. To quickly fix the problem theonly solution left in my case is to convert this recursive functioninto one recursive stored procedure. However, I am facing one problem.How to convert the select command in this piece of code below into an"execute" by passing parameters and calling the sp recursively again.### piece of code ############SELECT @subtotal = dbo.Mkt_GetChildren(uid, @subtotal,@DateStart, @DateEnd)FROM categories WHERE ParentID = @uid######### my function ###########CREATE FUNCTION Mkt_GetChildren(@uid int, @subtotal decimal ,@DateStart datetime, @DateEnd datetime)RETURNS decimalASBEGINIF EXISTS (SELECTuidFROMcategories WHEREParentID = @uid)BEGINDECLARE my_cursor CURSOR FORSELECT uid, classid5 FROM categories WHERE parentid = @uiddeclare @getclassid5 varchar(50), @getuid bigint, @calculate decimalOPEN my_cursorFETCH NEXT FROM my_cursor INTO @getuid, @getclassid5WHILE @@FETCH_STATUS = 0BEGINFETCH NEXT FROM my_cursor INTO @getuid, @getclassid5select @calculate = dbo.Mkt_CalculateTotal(@getclassid5, @DateStart,@DateEnd)SET @subtotal = CONVERT (decimal (19,4),(@subtotal + @calculate))ENDCLOSE my_cursorDEALLOCATE my_cursorSELECT @subtotal = dbo.Mkt_GetChildren(uid, @subtotal,@DateStart, @DateEnd)FROM categories WHERE ParentID = @uidENDRETURN @subtotalENDGORod

View 4 Replies View Related

How To Query The Using Recursive?

Jun 10, 2007

 
Hello,
I have the following tables:

Article(articleID,CategoryID,ArticleTitle)
Categories(categoryID,ParentID,CategoryTitle)
I am trying to retrieve the main category ID for a specific article ID.
For example lets say I have this data:
Article: 

1, 10 , "some title"
2,10,"some title"
3,11,"some title"
Categories:
1, NULL , "some title"
2, 1, "some title"
10, 2, "some title"
11, 10 , "some title"
 
In this example I want to know who is the main category of article 3.
The query should return the answer: 1
Thats because:

The article ID 3 is inside category 11.
Parent for category 11 is 10.
Parent for category 10 is 2.  
Parent for category 2 is 1
and Parent for category 1 is NULL, which means category 1 has no parents and it is the main category.
Query will return article id, category id, main_category_id, ArticleTitle, CategoryTitle (some union between 2 tables)
Do you have any suggestions for such query?
Thanks all.
 

View 1 Replies View Related

Recursive Query ..

Jan 18, 2008

Recursive quey to show products with "custom defines fields" related by Classifications, instead of per product Hello, I’m working on a project ..  .



I’m desperating due to the
complex (for me and also I think for some others) sql query that I need to
write, to show the products with his “custom defined fields� that are inside a ProductsFieldsByClassification
table that holds this mentioned “custom defined fieds� according to the Classifications
table, on where the Products can be found trought the productsClassifications
table.


CustomFields can be defined
and set for the products, trought his Classifications (instead of define a
custom field for each product (that consume a lot of data), I decide to use it as
I explain)

 

I will to know the properly
SQL QUERY to show a list of products with the ProductsFieldsByClassifications and ProductsFieldsValuesByClassifications:

 


As example on
a Requested ID_Classification = 16 (Torents/Games/Dreamcast/PAL), the products must be show with the
ProductsFields and Values that has the DBA for the:

·        
requested
ID_Classification

o       
PAL (ID_Classification: 16)

·        
AND all
the Classifications that belongs above (trought ID_ParentClassification) that are :

o       
Torrents (ID_Classification:
1) that will show the products values for the “Size�

o       
Games (ID_Class..:4) ß this classification has no CustomFields so none from this one.

o       
Dreamcast (ID_Class..:14 )
that will show his ID_Classification(14) product field “Levels� value (but not “AllowSave� as not have value for any product)

 




Hmnn i show a graphic that i design for (feel to click over to see at correct resolution) 

 
 
 

I also write asp.net tutorials. For those interested see my blog at http://abmartin.wordpress.com 
 

 

View 2 Replies View Related

Recursive SQL Query

Sep 21, 2004

I have a tough issue with a query.

I have the following structure


Table: Users

UserId ParentUserId
1 1
2 1
3 2
4 1
5 4
6 5


I need to write a stored procedure that takes in UserId as parameter and returns everyone under him/her.

So if Param=1 it would return result set of 2,3,4,5,6

Anyone done this before or have any ideas?

Thanks,
ScAndal

View 1 Replies View Related

Recursive Query Help

Jul 20, 2005

Hi,

Does anyone know how to do an sql recursion queries?

I believe it involves a view with a union.

I have a User Table and in that table i have a employee_id and a
boss_id. What i'd like to do is to find all employees under a certain
boss.
For example,

Employee_ID Boss_ID
1
2                     1
3                    
4                     3
5                     2

So if i'd like to know who are under the employee_id = 1 it will return
employee_id 2 and 5 since employee 2 also is the boss of employee_id =
5.

To do that i'd have to have recursion query.

Thanks,

View 2 Replies View Related

Recursive Sql Query

Sep 29, 2004

Hi,

i have the following table structure:

id | parentID
1 | NULL
2 | 1
3 | 2
4 | 3

im having trouble in creating a recursive query to return all the parents of a particular id. Have anyone ever done this?

thanks in advance,

View 7 Replies View Related

Can A Recursive Query Do This?

Dec 23, 2004

I am wondering if there is some type of recursive query to return the values I want from the following database.

Here is the setup:

The client builds reptile cages.

Each cage consists of aluminum framing, connectors to connect the aluminum frame, and panels to enclose the cages. In the example below, we are not leaving panels out to simplify things. We are also not concerned with the dimensions of the cage.

The PRODUCT table contains all parts in inventory. A finished cage is also considered a PRODUCT. The PRODUCT table is recursively joined to itself through the ASSEMBLY table.

PRODUCTS that consist of a number of PRODUCTS are called an ASSEMBLY. The ASSEMBLY table tracks what PRODUCTS are required for the ASSEMBLY.

Sample database can be downloaded from http://www.handlerassociates.com/cage_configurator.mdb

Here is a quick schema:

Table: PRODUCT
--------------------------
PRODUCTIDPK
PRODUCTNAMEnVarChar(30)


Table: ASSEMBLY
--------------------------
PRODUCTIDPK(FK to PRODUCT.PRODUCTID)
COMPONENTIDPK(FK to PRODUCT.PRODUCTID)
QTYINT


I can write a query that takes the PRODUCTID, and returns all



PRODUCT
=======
PRODUCTIDPRODUCTNAME
--------------------
1Cage Assembly - Solid Sides
2Cage Assembly - Split Back
3Cage Assembly - Split Sides
4Cage Assembly - Split Top/Bottom
5Cage Assembly - Split Back and Sides
6Cage Assembly - Split Back and Top/Bottom
7Cage Assembly - Split Back and Sides and Top/Bottom
833S - Aluminum Divider
933C - Aluminum Frame
10T3C - Door Frame
11Connector Kit
12Connector Socket
13Connector Screws



ASSEMBLY
=========
PRODUCTIDCOMPONENTQTY
---------------------
198
1104
1111
211
281
311
381
411
481
511
582
611
682
711
783
11128
11138



I need a query that will give me all parts for each PRODUCT.

Example: I want all parts for the PRODUCT "Cage Assembly - Split Back"

The results would be:


PRODUCTIDPRODUCTNAME
--------------------
2Cage Assembly - Split Back
1Cage Assemble - Solid Back
933C - Aluminum Frame
10T3C - Door Frame
11Connector Kit
833S - Aluminum Divider
12Connector Socket
13Connector Screws

Is it possible to write such a query or stored procedure?

View 4 Replies View Related

Recursive Query

Dec 6, 2007

Can you please help me to write a recursive query in sql server 2000?

I have got a table WORKORDER. wonum and parent are the two columns in the table. A wonum can have children.Those children can have children, so on. if i am giving a wonum,it should display all the children ,their children and so on.

Sample data in the table is as follows

wonum parent
7792 NULL
7793 7792
165305 7793
7794 7792
7795 7792

eg:
7792 is a workorder,which has got children and grand children

7793 is a child of 7792
165305 is a child of 7793
7794 is a child of 7792 and
7795 is a child of 7792

When I give the 7792 in the query,it should fetch all the children and grand children,etc.
output should be :
7793
165305
7794
7795

How can we do that?

View 16 Replies View Related

Recursive Query ??

Jul 23, 2005

Went looking for an answer but not really sure what phrases to lookfor. Just decided to post my question.I have a collection of groups which contain items. I also have acollection of users which can be assigned permissions to both groupsand individual items. If a user has permission to a group then the userhas that permission to each of the items in the group. I need a querywhich will return all the items and permission for a particular user.Here is the code for creating the tables and populating them.CREATE TABLE [Account] ([Name] VARCHAR(10))INSERT INTO [Account] VALUES ('210')INSERT INTO [Account] VALUES ('928')INSERT INTO [Account] VALUES ('ABC')CREATE TABLE [AccountGroup] ([Name] VARCHAR(10))INSERT INTO [AccountGroup] VALUES ('Group1')INSERT INTO [AccountGroup] VALUES ('Group2')CREATE TABLE [AccountGroupMembership] ([GroupName] VARCHAR(10), [AccountName] VARCHAR(10))INSERT INTO [AccountGroupMembership] VALUES ('Group1', '210')INSERT INTO [AccountGroupMembership] VALUES ('Group1', 'ABC')INSERT INTO [AccountGroupMembership] VALUES ('Group2', '928')INSERT INTO [AccountGroupMembership] VALUES ('Group2', 'ABC')CREATE TABLE [Permission] ([User] VARCHAR(10), [Item] VARCHAR(10), [ItemType] VARCHAR(1)-- 'A' for account, 'G' for account group, [ReadPerm] INT, [WritePerm] INT)INSERT INTO [Permission] VALUES ('john', '210', 'A', 1, 0)-- readaccess to 210 accountINSERT INTO [Permission] VALUES ('john', 'Group1', 'G', 1, 1)--read/write access to Group1 groupINSERT INTO [Permission] VALUES ('mary', '928', 'A', 0, 1)-- writeaccess to 928 accountThe simple querySELECT * FROM [Permission] WHERE [User] = 'john'returnsUser Item ItemType ReadPerm WritePerm---------- ---------- -------- ----------- -----------john 210 A 1 0john Group1 G 1 1but what I really want is (notice that Group1 has been replaced withthe two members of Group1)User Item ReadPerm WritePerm---------- ---------- ----------- -----------john 210 1 0john 210 1 1john ABC 1 1(Forget for the moment that 210 is listed twice with differentpermissions. I could take the result and do some sort of union to least(or most) restrictive permissions.)

View 4 Replies View Related

Recursive Query

Jul 20, 2005

Hi there,Need a little help with a certain query that's causing a lot of acidin my stomach...Have a table that stores sales measures for a given client. The salesmeasures are stored per year and there could be multiple salesmeasures every year per client. There is another field called lastupdate date. If there are multiple sales measures then need to selectthe one that's been entered last based on this field. Also, if thereis no sales measure data for current year then I need to return thelast year's data for which sales measure has been entered. Forexample: if client #1 has sales measure value of $200 for 1999 andnothing since, then I need to return $200 for any year following 1999.So the query would look something like this:SELECT client_name, sm_dollars FROM <tables>Based on the DDL at the bottom I would expect to get back: c1, 100;c2, 200The way I am doing it now is with correlated subqueries (3 to beexact) that each do an aggregate and join back to the original table.It works, but it is notoriously slow. SQL Server is scanning theindex and does a merge join which in a large query takes %95 of thetime. Here is the part of the query plan for it:| | | | | | |--MergeJoin(Inner Join, MANY-TO-MANYMERGE:([sales_measure].[client_id])=([sales_measure].[client_id]),RESIDUAL:(([sales_measure].[client_id]=[sales_measure].[client_id]AND [sales_measure].[tax_year]=[sales_measure].[tax_year]) AND[Expr1013]=[sales_measure].[last_update_date]))| | | | | | |--StreamAggregate(GROUP BY:([sales_measure].[client_id],[sales_measure].[tax_year])DEFINE:([Expr1013]=MAX([sales_measure].[last_update_date])))| | | | | | | |--MergeJoin(Inner Join, MERGE:([sales_measure].[client_id],[Expr1010])=([sales_measure].[client_id], [sales_measure].[tax_year]),RESIDUAL:([sales_measure].[client_id]=[sales_measure].[client_id] AND[sales_measure].[tax_year]=[Expr1010]))| | | | | | ||--Stream Aggregate(GROUP BY:([sales_measure].[client_id])DEFINE:([Expr1010]=MAX([sales_measure].[tax_year])))| | | | | | | ||--Index Scan(OBJECT:([stars_perftest].[dbo].[sales_measure].[sales_measure_idx1]),ORDERED FORWARD)| | | | | | ||--Index Scan(OBJECT:([stars_perftest].[dbo].[sales_measure].[sales_measure_idx1]),ORDERED FORWARD)| | | | | | |--IndexScan(OBJECT:([stars_perftest].[dbo].[sales_measure].[sales_measure_idx1]),ORDERED FORWARD)There are two indexes on sales measure table:sales_measure_pk - sales_measure_id (primary key) clusteredsales_measure_idx1 - client_id, tax_year, last_update_date, sm_dollarssales_measure table has 800,000 rows in it.Here is the rest of the DDL:IF OBJECT_ID('dbo.client') IS NOT NULLDROP TABLE dbo.clientGOcreate table dbo.client (client_idintidentityprimary key,client_namevarchar(100)NOT NULL)GOIF OBJECT_ID('dbo.sales_measure') IS NOT NULLDROP TABLE dbo.sales_measureGOcreate table dbo.sales_measure(sales_measure_idintidentityprimary key,client_idintNOT NULL,tax_yearsmallintNOT NULL,sm_dollarsmoneyNOT NULL,last_update_datedatetimeNOT NULL)GOCREATE INDEX sales_measure_idx1 ON sales_measure (client_id, tax_year,last_update_date, sm_dollars)GOINSERT dbo.client(client_name)SELECT'c1' UNION SELECT 'c2' UNION SELECT 'c3'GOINSERTdbo.sales_measure(client_id, tax_year, sm_dollars,last_update_date)SELECT1, 2004, 100, '1/4/2004'UNIONSELECT2, 2003, 100, '1/3/2004'UNIONSELECT 2, 2004, 150, '1/4/2004'UNIONSELECT2, 2004, 200, '1/5/2004'The view that I use to calculate sales measures:CREATE VIEW sales_measure_vw ASSELECTsm.*FROM sales_measure smINNER JOIN (SELECT sm2.client_id, sm2.tax_year,MAX(sm2.last_update_date) as last_update_dateFROM sales_measure sm2INNER JOIN (SELECT sm4.client_id, MAX(sm4.tax_year)as tax_yearFROM sales_measure sm4 GROUP BYsm4.client_id) sm3on sm3.client_id = sm2.client_idand sm3.tax_year = sm2.tax_yearGROUP BY sm2.client_id, sm2.tax_year ) sm1ON sm.client_id = sm1.client_id ANDsm.tax_year = sm1.tax_year ANDsm.last_update_date = sm1.last_update_dateAny advice on how to tame this would be appreciated. Also, any adviceon the indexes would help as well.ThanksBob

View 14 Replies View Related

Recursive Query

Dec 11, 2007

I'm trying to get from the first table bellow to the second one using recursive queries. Could you help me on this issue? I want to be able to group by project and employee id and then if the dates overlap then to get the min and max dates in one row

ProjectID EmpId StartDate EndDate
P01 E01 2007-10-01 2007-10-19
P01 E01 2007-11-01 2007-11-20
P01 E01 2007-11-15 2007-11-25
P01 E02 2007-11-30 2007-12-31


ProjectID EmpId StartDate EndDate
P01 E01 2007-10-01 2007-10-19
P01 E01 2007-11-01 2007-11-25
P01 E02 2007-11-30 2007-12-31

Thank you in advance

View 1 Replies View Related

Help With Recursive Query

Nov 7, 2007

I've been struggling with this for while. It doesn't seem that hard, but I can't seem get the results right. I've tried several SELECT queries and also played with CTE but I'm quite a novice in that dept. I have searched this forum and read many similar posts but I can't seem to get it quite right.

Suppose I have a table (Categories) with parent categories and sub categories with the following example data:

Id ParentId Category
1 null Items
2 null Autos
3 1 Books
4 2 Honda
5 1 DVDs
6 1 Furniture
7 2 BMW

Can someone suggest the most efficient way to get an appropriate result set that I could use to display each Parent Category followed by each appropriate Sub Category on a web page?

For example:

Autos
Honda
BMW

Items
Books
DVDs
Furniture

I'd appreciate any advice and thanks in advance.

View 5 Replies View Related

Recursive Query?

Jul 23, 2006

I have a set of data and I need to actually add a column to the result set based on information contained within the query. For example,

SalesmanID  SalesBudget   SalesRegion      Product      Amount
1                      1000                 USA                   Soap          100.50
1                      1000                 USA                   Milk               50.50
5                       2000                OZ                      Bread             2.50
1                       1000                USA                   Bread             2.50
3                        350                 OZ                      Nappies         4.50

Notice that Salesbudget is related to the salesmanid and doesn't change. I need to be able to add a column to this query that sum the total budget for the saleregion so output looks like this

SalesmanID  SalesBudget   SalesRegion      Product      Amount   RegionBudget
1                      1000                 USA                   Soap          100.50    3500
1                      1000                 USA                   Milk               50.50    3500
5                       2000                OZ                      Bread             2.50    2350
2                       1500                USA                   Bread             2.50    3500
3                        350                 OZ                      Nappies         4.50    2350

So I need to do a sum distinct on salesbudget by region and append to my query as a column, is this possible? If so how?

It is important that I do it this way as I will have parameters in my query that might restrict which lines are returned. For instance show all bread sales and that way I only what to sum region budgets for these.

I could do it with 2 queries but needs to be 1 as I am using a matrix report that does'nt contain a sum distinct function and is contrained by scope.

Thanks in advance

Damien

View 9 Replies View Related

Help With A Recursive Query!!!

Dec 20, 2007

i have two tables, one called P_TAXONOMY with these columns:

IDObject TaxID
DB1 259

and one hierarchical table called (TAXONOMY) with this columns:

TaxID TaxIDParent tax_name taxlevel
259 256 P.O 3

256 4 A 2

4 1 B 1

1 0 C 0


i get the TaxID from P_TAXONOMY and i have to look for recursively its father (level 0) in the TAXONOMY table; I'm pretty sure the solution to this involves some type of recursive query but if anyone here can help me out I'd really appreciate it.

i have the next query but only for 3 levels, i need it for n levels (from any leaf)

select stf.tax_name
from TAXONOMY stf,
(select st0.TaxIDParent
from TAXONOMY st0, (select st.TaxIDParent
from P_TAXONOMY spt, TAXONOMY st
where spt.TaxID = st.TaxID ) as u
where st0.TaxID = u.TaxIDParent ) as cons
where stf.TaxID = cons.TaxIDParent
group by tax_name


Thanx
Diego Bayona.


pd:
for example:
the root of TaxID = 259 (P_TAXONOMY) is 1 (TAXONOMY)

View 1 Replies View Related

Recursive Query --- Very Urgent

May 15, 2007

Hello. I have a question. I have a table that keeps track of
claims being made by clients (like insurance claims). There is a table which
has 2 fields. Field1 and Field2. Field1 has the original claim number. If an
adjustment is made to the claim, a new claim number will be generated. For example
if a person pays $100 and files a claim, he is issued a claim number which goes
into Field1. If that person spends some more money towards the same issue and
then files another claim then he is given a new claim number which is stored in
Field2.

Field1--------------Field2
--------------------------------
100--------------------150
150--------------------200
200--------------------250
250--------------------Null (No more adjustments made)
and so on.

So in the query I will supply a claim number (say 100). I
need to get the history of all the claims attached to it. In this example 100,
150, 200, 250.

Also if the claim number provided is 200 I need to get the
original claim number (which is 100) meaning I need to back track and forward
track too. I need this in SQL Server 2000.

I hope I am clear enough. Thanks.

View 3 Replies View Related

Recursive Query Problem

Jul 18, 2006

I have a simple 1:M table called UserFriends

UserID, FriendID
1 2
3 9
4 8
2 4
2 6
2 3
5 7
2 1

I would like to write a query that returns a user's friends and all their friends. For example, getUserFriends(1) would return 2, 4, 6, 3, 8, 9

I wrote a recursive function but I'm having a little trouble with it. Basically, the problem is that once a user has been processed that user should be excluded.

Here is my function:


SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO

ALTER FUNCTION dbo.GetUserConnections (@UserID INT)
RETURNS @Connections TABLE (FriendID INT, UserID INT, ProcessedFriend INT) AS
BEGIN
DECLARE oCursor CURSOR LOCAL FOR

SELECT FriendID, UserID FROM UserFriends WHERE
UserID=@UserID AND FriendID NOT IN (
SELECT ProcessedFriend FROM @Connections WHERE UserID=@UserID
) AND (
NOT EXISTS(
SELECT UserID FROM @Connections WHERE UserID=@UserID)
)
OPEN oCursor

DECLARE @LocalUserID int, @LocalFriendID INT

FETCH NEXT FROM oCursor INTO @LocalFriendID,@LocalUserID

WHILE (@@FETCH_STATUS = 0)
BEGIN
IF NOT Exists (SELECT FriendID FROM @Connections WHERE FriendID=@LocalUserID)
BEGIN
INSERT @Connections (FriendID, UserID, ProcessedFriend) SELECT @LocalFriendID, @UserID,@LocalFriendID
INSERT @Connections (FriendID, UserID, ProcessedFriend)
SELECT FriendID, @UserID, @LocalFriendID FROM dbo.GetUserConnections(@LocalFriendID)
WHERE (FriendID NOT IN (SELECT FriendID FROM @Connections))
END
FETCH NEXT FROM oCursor INTO @LocalFriendID,@LocalUserID
END

CLOSE oCursor
DEALLOCATE oCursor
RETURN
END






GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

View 1 Replies View Related

How To Write A Recursive Query?

Dec 23, 2004

I am wondering if there is some type of recursive query to return the values I want from the following database.

Here is the setup:

The client builds reptile cages.

Each cage consists of aluminum framing, connectors to connect the aluminum frame, and panels to enclose the cages. In the example below, we are not leaving panels out to simplify things. We are also not concerned with the dimensions of the cage.

The PRODUCT table contains all parts in inventory. A finished cage is also considered a PRODUCT. The PRODUCT table is recursively joined to itself through the ASSEMBLY table.

PRODUCTS that consist of a number of PRODUCTS are called an ASSEMBLY. The ASSEMBLY table tracks what PRODUCTS are required for the ASSEMBLY.

Sample database can be downloaded from http://www.handlerassociates.com/cage_configurator.mdb

Here is a quick schema:

Table: PRODUCT
--------------------------
PRODUCTIDPK
PRODUCTNAMEnVarChar(30)


Table: ASSEMBLY
--------------------------
PRODUCTIDPK(FK to PRODUCT.PRODUCTID)
COMPONENTIDPK(FK to PRODUCT.PRODUCTID)
QTYINT


I can write a query that takes the PRODUCTID, and returns all



PRODUCT
=======
PRODUCTIDPRODUCTNAME
--------------------
1Cage Assembly - Solid Sides
2Cage Assembly - Split Back
3Cage Assembly - Split Sides
4Cage Assembly - Split Top/Bottom
5Cage Assembly - Split Back and Sides
6Cage Assembly - Split Back and Top/Bottom
7Cage Assembly - Split Back and Sides and Top/Bottom
833S - Aluminum Divider
933C - Aluminum Frame
10T3C - Door Frame
11Connector Kit
12Connector Socket
13Connector Screws



ASSEMBLY
=========
PRODUCTIDCOMPONENTQTY
---------------------
198
1104
1111
211
281
311
381
411
481
511
582
611
682
711
783
11128
11138



I need a query that will give me all parts for each PRODUCT.

Example: I want all parts for the PRODUCT "Cage Assembly - Split Back"

The results would be:


PRODUCTIDPRODUCTNAME
--------------------
2Cage Assembly - Split Back
1Cage Assemble - Solid Back
933C - Aluminum Frame
10T3C - Door Frame
11Connector Kit
833S - Aluminum Divider
12Connector Socket
13Connector Screws

Is it possible to write such a query or stored procedure?

View 1 Replies View Related

Complex Recursive Query

Jan 17, 2005

I have a complex query that I am strugling with in MS SQL Server 2000. I am trying to get all of the websites a user has control of. My schema is as follows:

A user can control many companies, and a company can be controlled by many users. A company can also control other companies (thus a recursive parent relationship). A company can have many websites, but a website can only belong to one company. Thus the design:


USER TABLE
User_ID
User_Name

COMPANY TABLE
Company_ID
Company_Name
Company_ID_Parent (recursive)

USER_COMPANY TABLE
User_ID
Company_ID

WEBSITE TABLE
Website_ID
Company_ID (Foreign Key)


That said, how do I get a list of websites that a user is associated with... meaning, all of the websites that belong to a company that either the user controls directly, or a child-company of a company that either the user controls directly (at any depth).

Getting the websites is actually easy. I need the recursive part figured out.

Thx in Advance.

View 13 Replies View Related

Recursive Relationship Query

May 21, 2006

Hi all,

Im really confused and need some help please from some of you clever people.

I know the basics of SQL but Ive no idea how to write a query to do this.

Basically, we have two tables, the first containing a list of people and the second containing two relationships to the person table. The first is the parent relationship and the second the child relationship. Each person may be related to one or more other people (e.g. father, son, brother, sister etc.). If you can imagine we have a few hundred people in the person going back a couple of hundred years.

Now Ive set the scene Im really trying to create a query that can navigate all the relationships from a set point (Person).

Ultimately I would like to (given a PersonID, navigate the full PERSON_ASSOCIATION table to find:

a. All people below the PersonID (if there are any)
b. All people above the PersonID (if there are any)

For example, in the data below there is somebody called John Smith.

Going down the PERSON_ASSOCIATION table I would like to show:

John Smith has a brother called Andrew Jones who has a brother-in-law called Stephen Barnes

John Smith has a wife called Jane Wallace

John Smith has a daughter called Mary Joseph

What I am going round in circles on is the multiple relatationships, e.g. A is related to B who in turn is related to D who in turn is related to E therefore A is related to E.




PERSON
ID NAME
1 John Smith
2 Andrew Jones
3 Jane Wallace
4 Steven Barnes
5 Mary Joseph
98 Me
99 Joanne




PERSON_ASSOCIATION
ID PARENT_PERSON_ID CHILD_PERSON_ID RELATIONSHIP
1 1 2 Brother
2 1 3 Wife
3 1 5 Daughter
4 2 4 Brother-In-Law
5 98 1 Father
6 98 99 Husband


Can somebody please point me in the right direction by explaining how I can write some SQL that will navigate (and iterate through) all the PERSON and PERSON_ASSOCIATION tables.

Im sure there must be a straight forward way of doing this.

One final thing, if it helps, Im hoping to eventually end up with a stored procedure which I can basically pass in a PERSON_ID and it returns a list of all the relationships from that person.

MANY BIG thanks in advance

Im really sorry but it is driving me crazy

Mike

View 1 Replies View Related

Recursive Query Problem

Aug 30, 2007

So I have tblJobItem with fields

JobItemName, JobItemSublevel, JobItemParent, JobItemChild1, JobItemChild2

JobItemName is the name of item name
sublevel goes from 0 - 3

if sublevel is 0 then parent, child1, child2 are null
if sublevel is 1 then child1, child2 are null and parent is value of sublevel 0 jobitemname

if sublevel is 2 then child2 is null and parent is value of sublevel 0 jobitemname and child1 is name of sublevel 1 jobitemname

all that said Im trying to write a recursive query to get he heirachy structure -- the following gives me an error that there is no anchor query for tbljobitem

WITH tblJobItem (JobItemName, JobItemSubLevel, JobItemParentName, JobItemChildName) AS
(
SELECT a.JobItemName, a.JobItemSubLevel, a.JobItemParentName, a.JobItemChildName FROM tblJobItem AS a
UNION ALL

SELECT a.JobItemName, b.JobItemSubLevel, a.JobItemParentName, a.JobItemChildName
FROM tblJobItem AS a

INNER JOIN tblJobItem AS b ON a.jobitemsublevel = b.JobItemSubLevel
)

SELECT *
FROM tbljobitem
ORDER BY JobItemIDID

how do i make this work with the table structure provided.

View 15 Replies View Related

Help Sorting A Recursive Query

Jul 27, 2007

Guys, I need help sorting a recursive query. This is my table

CTLG Table
txtID(PK)
txtParentID(FK)
numSortID
txtKeywords
txtTitle
memContent

I'm using txtParentID as the FK, which matches with txtID, to create the recursion.


This is my current Query

This is my current Query:




Code Snippet
WITH tree (data, id, level, pathstr, numSortID, memContent)
AS (SELECT txtTitle, txtid, 0,
CAST('' AS NVARCHAR(MAX)), numSortID, memContent
FROM CTLG
WHERE txtParentID IS NULL
UNION ALL
SELECT txtTitle, V.txtid, t.level + 1, t.pathstr + '>' + V.txtTitle, V.numSortID, v.memContent
FROM CTLG V
INNER JOIN tree t
ON t.id = V.txtParentID)
SELECT SPACE(level) + data as data, id, level, pathstr, numSortID, memContent
FROM tree



The output is this:








Data
ID
Level
pathstr
NumSortID

Undergraduate Catalog
1
0

1

History
12
1
>History
7

Academic Calendar
14
1
>Academic Calendar
8

Preface
2
1
>Preface
2

NonDiscrimination Statement
3
1
>NonDiscrimination Statement
3

Accreditation
4
1
>Acreditation
4

Memberships
5
1
>Memberships
5

Mission Statement
8
1
>Mission Statement
6

Fall Calendar
20
2
>Academic Calendar>Fall Calendar
1

Winter Calendar
21
2
>Academic Calendar>Winter Calendar
2

Summer Calendar
22
2
>Academic Calendar>Summer Calendar


3



I need my out put to look like the following:

Undergraduate Catalog Level (0) NumSortID (1)
Preface (1) (2)
NonDiscrimination Statement (1) (3)
Accreditation (1) (4)
memberships (1) (5)
Mission Statement (1) (6)
History (1) (7)
Academic Calendar (1) (8)
Fall Calendar (2) (1)
Summer Calendar(2) (2)
Winter Calendar (2) (3)

The Order that I would like to have is based on NumSortID and by Levels. Like the above example.

View 7 Replies View Related

Recursive Query With Different Tables

Feb 29, 2008



Want to populate a navigation tree and looking for advise on how to implement the queries with (if possible) only one trip to the database.

To simplify I will give an example using made-up tables to populate MY-ARMY treeview:
Assume Table People:

PeopleID
ParentPeopleID
Name
Rank

Table General

PeopleID
<General's attributes>

Table Commander

PeopleID
<Commander's attributes>

Table Soldier

PeopleID
<Soldier's attributes>



If I build a recursive query to see MY-ARMY, is there a way to get each unique table's attribute?
I understand that the result is not uniform, therefore needs to be broken in different JOIN SELECTs, but then... how to avoid calling the recursive query multiple times?

Thx,
Uri

View 4 Replies View Related

Is Is Possible To Have More Than 1 Graph Type In One Graph?

Jan 7, 2008

I'm hoping to create a graph with durations as bar graphs and % met as a line graph. Is this possible in BIDS?

View 1 Replies View Related

Need To Store Data From Recursive Query Using CTE

Apr 18, 2008

I have a recursive query, using common table expressions, like this:
 WITH TaskHierarchy (GUID, ParentGUID, Title, Complete, HierarchyLevel)
AS
(
SELECT GUID, ParentGUID, Title, Complete, 1 HierarchyLevel
FROM Task
WHERE ParentGUID = @GUID

UNION ALL

SELECT t.GUID, t.ParentGUID, t.Title, t.Complete, th.HierarchyLevel + 1 HierarchyLevel
FROM Task t
INNER JOIN TaskHierarchy th
ON t.ParentGUID = th.GUID
)
SELECT (COUNT(*) - SUM(CAST(Complete AS INT))) Outstanding FROM TaskHierarchy
  The result is a number.  I need access to this number.  Ideally, I would like to store it in a variable, but anything would work as long as I can access it after the query.Anyone know of a way?

View 1 Replies View Related







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