How To Convert Recursive Function Into Recursive Stored Procedure
Jul 23, 2005
I am having problem to apply updates into this function below. I tried
using cursor for updates, etc. but no success. Sql server keeps telling
me that I cannot execute insert or update from inside a function and it
gives me an option that I could write an extended stored procedure, but
I don't have a clue of how to do it. To quickly fix the problem the
only solution left in my case is to convert this recursive function
into 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 decimal
AS
BEGIN
IF EXISTS (SELECT
uid
FROM
categories WHERE
ParentID = @uid)
BEGIN
DECLARE my_cursor CURSOR FOR
SELECT uid, classid5 FROM categories WHERE parentid = @uid
declare @getclassid5 varchar(50), @getuid bigint, @calculate decimal
OPEN my_cursor
FETCH NEXT FROM my_cursor INTO @getuid, @getclassid5
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM my_cursor INTO @getuid, @getclassid5
select @calculate = dbo.Mkt_CalculateTotal(@getclassid5, @DateStart,
@DateEnd)
SET @subtotal = CONVERT (decimal (19,4),(@subtotal + @calculate))
END
CLOSE my_cursor
DEALLOCATE my_cursor
SELECT @subtotal = dbo.Mkt_GetChildren(uid, @subtotal,
@DateStart, @DateEnd)FROM categories WHERE ParentID = @uid
END
RETURN @subtotal
END
GO
Hi, I would like some help on a stored recursive procedure I have been working on for my assigment. I had the solution from my course master some time back, but accidentally deleted the file before finishing the course, and would like the solution to that problem. The questions are as follows: 1) Create a recursive stored procedure that counts from 1 to 10 2) Create a recursive stored procedure that counts from 10 to 1
I believe there's more than one approach in solving these procedures, and any feeback is welcome.
How do I call my Stored Procedure recursively:CREATE PROCEDURE dbo.GetParentIONode(@IONodeID int,@FullNodeAddress char(100) OUTPUT)ASBEGINDECLARE @ParentIONodeID intIF EXISTS (SELECT ParentIONodeID FROM IONodes WHERE IONodeID = @IONodeID)BEGINSET @FullNodeAddress = CAST((SELECT ParentIONodeID FROM IONodes WHEREIONodeID = @IONodeID) AS VARCHAR) + ' / ' + @FullNodeAddress--CALL SP Again with @ParentIONodeID and @FullNodeAddress untilParentIONodeID = NULLSELECT @FullNodeAddressENDENDGO
The MLID in the header table will be generated automatically.All the Parents will be stored in the HEADER and their childs in the DETAIL.When a child is added to a parent,the Parent's MLID will be stored in the MLID field in the DETAIL table with the newly added child.That child will come to the PARENT table when a child is added to that.The MLITEM id in the parent table can be repeated when that item undergoes a rivision.But the MLID for this will be a new one.An item in the Parent Table can have any number of childs and these childs can have any number of children(there is no limit for the level.)
Now if i select an item id '1000' (for example from the Header Table) with a concatstring (it could be without a concat string also).all its childs and their children should be printed in a report like the following
************************************************** *************************** I NEED TO CREATE THE TREE USING BOTH THE HEADER(MSTHDRML) AND THE DETAIL TABLE(MSTDTLML) ************************************************** ***************************
How can this be done.Is it necessary to use a recursive function in a stored procedure to generate this ...... i have never used Recursive function in SQL SERVER Stored Procedures.Can anyone help me on this(with Code).if not stored procedure, then what else can be done for this.
I need to develope a stored procedure (eventually called by a trigger) that creates a record in an event table for all the descendants of a drawing. There are 3 tables involved as example tables shown below:
DwgTable
DwgID (integer)--drawing record identifier
PrntDwgID (integer)--parent drawing record identifier (a previously defined DwgID from this table)
DwgEventTable
DwgEventID (integer)--record identifier
DwgID (integer)--value from DwgTable
EventID (integer)--value from EventTable
EventTable
EventID There are other fields in two of the tables and only the fields shown in the DwgEventTable, but only the fields shown are required for adding a record in the DwgEventTable for a new event in the EventTable. The problem is identifying all the DwgID's of the descendant of the DwgID where the EventID occurred. There may be 0 to N descendants in 0 to N generations. I need to add a record for the original DwgID and all the descendant DwgID's in the DwgEventTable for the event identified by EventID.
I could do this from the client side, but a better place would be from the server side. I need some clue(s) on how to start coding a recursive stored procedure in SQL Server 2005. From what I have read, you cannot create a managed code procedure that appends or updates records--if managed code can add/modify records then I can do the above with managed code procedure.
I apologize if I posted in the wrong section, but I cannot find a solution to this. I was hoping that some one can help me figure this out. I need this solution in a stored procedure VS using dataset because there are thousands of categories and it is extremely slow with a dataset. I have a category table ID intPARENTID intNAME SAMPLE DATA:
ID NAME PARENT_ID
1 ANIMALS 0
2 DOGS 1
3 CATS 1
4 Abyssinian 3
5 Persian 3
6 Rurkish Van 3
7 Dalmation 2
8 German Shepherd 2
9 Irish Setter 2
10 Bulldog 2
I need the stored proc to return results in a single record set like this: ANIMALS - DOGS - - Dalmation - - German Shepherd - - Irish Setter - - Bulldog - CATS - - Abyssinian - - Persian - - Turkish Van Seems fairly easy but I have been battling with this for days now. Thank you in advance, EL
Hello, I am hoping someone can help me in this. I am looking to write a stored procedure that will return the heirarchy of an organization. I will display how the heirarchy might look and then list the tables involved.
John Smith
- Jacob Jones - Lisa Thompson - Samuel Barber
- Paul Smith - John Jackson
Ok, so Jacob, Lisa, an Samuel report up to John Smith. Paul and John Jackson report up to Samuel Barber.
Here are the tables:
Users holds the user_id, first_name, last_name, and reports_to_user_id. User_Roles holds the user_id, role_type_id Role_Types holds the role_type_id, and the type (which could be Administrator, Standard, Guest) for example. In addition, Role_Types also has ranking which must be taken into consideration as well. 1 being the top rank and 9 being the lowest.
I have a table of product types, the table is layed like this:
TypeID TypeName ParentID
each type has a ParentID equal to one of the other types TypeID (except the very top level types) to build a hierarchy with several levels.
I need a way of giving a function a single TypeID, and have it return a table that has the the TypeID of every type underneath it in the hierarchy. it could go down several levels (like 10 or more) so it needs to recursively work...
I'm just completely lost...
I can get this to work just fine in VB... but in VB i can just use a nice little for each loop...
I am trying to write a recursive function which allows me to provide a hierarchical structure from an employee table but I am getting an error
Server: Msg 512, Level 16, State 1, Procedure GetEmployee, Line 10 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Is there a way in which I can write a recursive function to do this. Or would I need to use cursors, multiple functions??? Any help or examples would be great. Thanks for your help
CREATE FUNCTION GetEmployee(@EmpID as int) RETURNS @Employee Table ( StaffNo int, ParentStaffNo int ) AS BEGIN DECLARE @ManagerID int SET @ManagerID = (SELECT [id] FROM eii.dbo.test WHERE Parent_ID = @EmpID)
IF @ManagerID IS NOT NULL and @ManagerID > '' and @ManagerID <> @EmpID INSERT INTO @Employee SELECT [id],parent_id FROM eii.dbo.test Where [id] = @ManagerID UNION SELECT * FROM GetEmployee(@ManagerID)
I am writing a function which I hope to use as a column value in aselect query. The function recursively walks a taxonomic heirarchy,extracting the name for an organism at the taxonomic level requestedby the user. I'm having trouble figuring out the syntax to call thefunction from itself (see **1), and the value returned.When I test the funciton, it says 'commands completed successfully',but nothing is returned. This is in SQL2000, runing on Windows2000.The table the function acts on is:CREATE TABLE [dbo].[tblbenthictaxa] ([tsn] [int] IDENTITY (1, 1) NOT NULL ,[rank_id] [int] NOT NULL ,[dir_parent_tsn] [int] NULL ,[req_parent_tsn] [int] NOT NULL ,[taxa_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL) ON [PRIMARY]GOReqParentTSN is the recursive link to rows in the table;Level is the taxonomic level the user requested (an integerrepresenting Order, Family, Genus or Species).CREATE FUNCTION dbo.CBN_RecursTaxa (@ReqParentTSN int,@Level int)RETURNS varchar(100) ASBEGINDeclare @Rank int,@taxaname varchar(100)SELECT @ReqParentTSN = tblbenthictaxa.req_parent_tsn,@TaxaName = tblbenthictaxa.taxa_name,@Rank = tblbenthictaxa.rank_idFROM tblbenthictaxaWHERE tblbenthictaxa.TSN=@ReqParentTSNif @Rank > @Level**1 --exec CBN_RecursTaxa @ReqParentTSN, @LevelRETURN @TaxaNameENDThanks in advance for any help,Tim
I'm having trouble creating a recursive function in T-SQL (SQL Server 2000).
I've got a table that has an ID column and a ParentID column. Each row can have a value in the ParentID column that references the ID column of another record - I'll call such rows "child records". I'll cal the row referenced by the ParentID the "parent record". Each child record can itself have another child record.
I need a function that will take an ID column value as a parameter, and walk up the chain of parent records until I get the first record in the series and return that record's ID value. I'll call that record the "UrParent record".
I'm trygin to create a recursive function called ufunc_ST_GetUrParentCertNum. In the function, there is of course a recursive call to itself - GetUrParentCertNum. However, when I try to run the CREATE FUNCTION script, I get the error: Server: Msg 195, Level 15, State 10, Procedure ufunc_ST_GetUrParentCertNum, Line 26 'ufunc_ST_GetUrParentCertNum' is not a recognized function name.
I tried the same thing with a Stored Procedure, and that worked fine. However, I really want this to work as a function.
Does anyone have advice on how I can achieve this? Thanks in advance.
Need getting the below Cursor query convert to a Recursive CTE or with a while loop as I do not want to use a cursor.
Declare @Companyname Nvarchar (400) declare @str nvarchar(MAX) TRUNCATE TABLE STAGING.dbo.[IT_G_L Entry] DECLARE GLEntry_cursor CURSOR FOR SELECT REPLACE Name FROM Company where Name <> 'AAAAA' OPEN GlEntry_cursor
I have a stored proc I want to convert it to either a Normal Query using A while loop or a set based operation/recursive cte as I want to run it for multiple CompanyNames. I get the error message as An INSERT EXEC statement cannot be nested when I execute if for Multiple Companies using another Cursor
If I convert it to a Function I get the below error message
Invalid use of a side-effecting operator 'EXECUTE STRING' within a function
converting this query to a normal query or let me know if there is any change which need to done to work with multiple companynames.
CREATE PROC [dbo].[USPT] @CompanyName varchar(50),@tablename varchar(50) AS BEGIN -- EXEC [USPT] 'xyz corp','Sales Header' DECLARE @str1 VARCHAR (MAX) set @str1 = ' DECLARE @No VARCHAR (MAX)
I have a database which stores information about organisms collectedduring sediment toxicology research. For each sample, organisms insediment are collected and identified taxonomically (Order, Family,Genus, Species).Taxonomy lookup information in the database is stored in a recursivetable in the form:TSN (taxa serial number)Rank (Order, Family, Genus, Species)NameParent_TSN (related Taxa at higher taxonomic level)When the number of a particlar organism collected is entered into thedatabase, the count is stored along with the lowest level TSN theorganisms were identified to.Okay - now the problem. Depending on the type of analysis being done,a user may want organism counts at the lowest level, or rolled up to ahigher taxonomic level (usually Family). Can I write a recursivefunction which will cycle through the Taxonomy database, and providethe name of the organism at the appropriate taxonomic level? Is this areasonable approach with regard to speed and efficiency?Something Like:SELECT sample_id, 'Get Name Function(Rank, TSN)', Sum([count]) ASNoTaxa FROM dbo.tblbenthicResults could then be grouped and summed on the Name, to summarisedata for each sample/taxa.Is this a reasonable approach? Or is there a better one? Did I explainthe problem well enough?Thanks in advance,Tim
I have a recursive CTE on an inline table valued function. I need to set the MAXRECURSION option on the CTE, but SQL Server is complaining with "Incorrect syntax near the keyword 'OPTION'".
It works fine on non-inline function. I couldn't find any documentation indicating this wasn't possible.
I can use the MAXRECURSION option in call to the function
SELECT * FROM MyFunction () OPTION ( MAXRECURSION 0 )
but that means that the user needs to know the "MyFunction" uses recursive CTE, which defeats the purpose of the abstraction.
I've got an application where I need to traverse a "tree" of parent and child relationships. I've got code in my application that does this nicely, and I want to move it to the database in the form of stored procs for a little better performance. The initial way I created it, is that the stored proc creates a cursor for the parent nodes, then calls itself for each child node, and rips through it that way. The problem is is that I get a cursor already exists error. Am I doing something wrong, or is that a limitation of SQL server to only have one named cursor open at a time? Is there a better way to do this?
I'm trying to write a recursive stored proc for the TreeView control that will return XML for the TreeView. Does anyone have any examples of code to do this or any resources that might help me write the stored proc?
Hi allI am implementing a stored procedure which needs to recursively callitself until specific condition is reached, Could anyone give someadvice about that?Thanks a lotRobert Song
I need to help in writing stored procedure to recursively delete Categories and ads for those categories Simplified table views: Category: CategoryID, Name, ParentCategoryID Ads: AdID, Name, CategoryID Please help
Hello Everyone, I have a purchase order table that holds say 2 columns. PO and OrgPO. That is Purchase Order # and Original Purchase Order # respectively. Assume i have the following rows in the table. PO OrgPO -- ------ po1 NULL co1 po1 co2 co1 co3 co2 po2 NULL cpo1 po2 po3 NULL Now what i would like to report in the output is the PO and along with the lastly generated change order for that po. For eg, PO LastCO -- ------ po1 co3 po2 cpo1 po3 po3 Currently i 'm using function to achieve this effect and i believe this is not the efficient way. I would like to generate this in a much efficient way. Please help me to achieve this.
I have problem is getting list of all the Tree Level Employees.here is the my table structure
Manager ~ SubOrdinate 1 ~ 2 1 ~ 3 1 ~ 4 2 ~ 5 2 ~ 6 2 ~ 7 3 ~ 8 3 ~ 9 4 ~ 10 5 ~ 11 SO ON I NEED THE WAY , HOW I CAN GET THE HIRE LEVELS ( EG IF I PASS MANAGER(EMPLOYEE NO) 1 IT SHOULD DISPLAY HIS 1 LEVELS AND 2, 3 SO ON LEVELS OF LEVELS OUTPUT COULD BE ,
PASSED EMPLOYEE NO : 1 LEVEL ~ EMPLOYEE 1 ~ 2 1 ~ 3 1 ~ 4 2.1 ~ 5 2.1 ~ 6 2.1 ~ 6 3.1 ~ 7 SO ON THAT EMPLOYEE RELATED INFORMATION ( ITS LIKE MLM LEVELS) CAN ANYBODY HELP IN THE ,
is there any way to define a recursive cte within another cte. I have defined a recursive cte which works great for finding the different versions of a given item. What I would like to do is to define a set of items for which I want to find the different versions.
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:
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.
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
i have a table like this parentid | childid | description 1 2 blah 1 3 1 4 2 23 2 24 5 8 3 10 and i want to give the parentid 1 and get all the children i have a cursor now like this but i dont know how to make it recursive any help?
1 2 DECLARE @childid nvarchar(50) 3 DECLARE ItemStruc CURSOR FOR 4 5 SELECT cmponent_prt_no , parent_part_no 6 FROM oauser_prod_structure 7 WHERE parent_part_no = @parentid 8 9 OPEN ItemStruc 10 FETCH NEXT FROM ItemStruc 11 INTO @childNum , @parentid 12 13 WHILE @@FETCH_STATUS = 0 14 BEGIN 15 16 print @childNum +'is the a child to: ' +@parentid
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.
I have a list of categories that I have to find the path to each my table is set up like ID CategoryNum CategoryName ParentID 1 AA Top Level 1 02 AB Top Level 2 03 BA Second Level 1 1I need my query/stored proc to return Tope Level 1/Second Level 1 if I pass in the integer of 3I can do this in programming but cant seem to wrap my head around it in SQL ServerTIA for the help
I'm using exec sp_dboption 'ilgadmin', 'recursive triggers',true
I made
create trigger dbo.templates_ondelete on templates for delete as begin delete pages where templateid = (select [id] from deleted) end go
create trigger dbo.pages_ondelete on pages for delete as begin delete pageItems where pageid = (select [id] from deleted) end go
The second trigger must be started by the first one.
But it doens't work because if I do delete from templates where id = 2 more than one page (7 pages) are deleted and the second trigger doesn't work (it can only delete one by one in pageitems!)
Is there any option in SQL Server that I forgot or can I use an other methode
Hey there, Hopefully someone has a sec to help me out. I have a pretty tough query here for ya.
I want to turn this:
Parent | Child Fred | Mark John | Cindy Mark | John John | Suzy
into this:
Ancestor | Level | Descendant Fred | 1 | Mark Fred | 2 | John Fred | 3 | Cindy Fred | 3 | Suzy Mark | 1 | John Mark | 2 | Cindy Mark | 2 | Suzy John | 1 | Cindy John | 1 | Suzy
I want to do this in a single select statement. No loops or cursors. Please tell me you are as stumped as I am so that I don't feel so dumb.