Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
mikesmithee
Starting Member
1 Post |
Posted - 2009-10-28 : 02:50:01
|
| I am trying to create a generic table valued function which returns all children IDs for a specified parent of any self join table.The function is passed the table name, PK column name, parent column name and the ID value and returns a single column table with all the child IDs (including all descendants down to the leaf level of the self join hierarchy).The cursor works fine on its own to retrieve the child IDs, but I'm having problems including it in the function definition. See SQL below:CREATE FUNCTION getChildren (@TableName varchar(30), @PKColumnName varchar(30), @ParentColumnName varchar(30), @PKValueId decimal(9))RETURNS @resultsTable table (PKValueId numeric(9))ASBEGINdeclare @CurrentPKValueId as decimal(9),@Table as varchar(30),@PKColumn as varchar(30),@ParentColumn as varchar(20)SET @Table = @TableNameSET @PKColumn = @PKColumnNameSET @ParentColumn = @ParentColumnNameINSERT INTO @resultsTableSELECT @PKColumnFROM @TableWHERE @PKColumn = @PKValueIdDECLARE SelfJoinCursor CURSOR FOR SELECT @PKColumnFROM @TableWHERE @ParentColumn = @PKValueIdOPEN SelfJoinCursorFETCH NEXT FROM SelfJoinCursor INTO @PKValueIdWHILE (@@fetch_status <> -1)BEGININSERT INTO @resultsTableSELECT @PKColumnFROM dbo.getChildren(@PKValueId)FETCH NEXT FROM SelfJoinCursor INTO @PKValueIdENDCLOSE SelfJoinCursorDEALLOCATE SelfJoinCursorRETURN ENDThe error states I need to declare the @Table variables again in the cursor, but I'm not sure how. Any suggestions appreciated. |
|
|
|
|
|