/*
SIMPLE CURSOR EXAMPLE
Generation of a table with nested entities using cursors,
Logical entities are generated in a hierarchical
EJEMPLO SIMPLE DE CURSORES Entities dictionary
Generacion de una tabla con entidades anidades usando cursores,
Se generan entidades logicas en forma jerarquica
*/
--Declare a tableDECLARE @Entionary TABLE ([ID] INT IDENTITY(1,1) ,[Type] VARCHAR(25) ,[PhisicName] VARCHAR(255) ,[LogicName] VARCHAR(255) ,[Parent] INT ,[Synonym] INT ,[Help] xml)-- Var where I take the Identity number of Patern rowDECLARE @RootID INTEGER-- Name of tableDECLARE @object_name VARCHAR(255)-- Logical name... if you like other name is free to change itDECLARE @LogicName VARCHAR(255)-- Modify Date of Table, only to show other fieldDECLARE @modify_date DATETIME--Insert the root Row where depends every table nameINSERT INTO@Entionary ([Type] ,[PhisicName] ,[LogicName] ,[Parent] ,[Synonym]) values ('Entity' ,'Generic' ,'Generic' ,NULL ,NULL)-- Take the Identity valueSET @RootID = @@IDENTITY--Well here declare a cursor, only thatDECLARE Table_cursor CURSOR FORSELECTname AS [object_name],modify_dateFROMsys.objectsWHEREtype = 'U'ORDER BYname--Open the cursorOPEN Table_cursor--Fetch the firstFETCH NEXT FROM Table_cursor--Use the field values in the declared varsINTO @object_name , @modify_date--Loop not eofWHILE @@FETCH_STATUS = 0BEGIN--Insert table entitySET @LogicName = 'Logic_' + @object_nameSET @LogicName = @LogicName + '('+convert( Varchar(10), @modify_date)+')'INSERT INTO @Entionary ([Type] ,[PhisicName] ,[LogicName] ,[Parent] ,[Synonym]) values ('SubEntity' ,@object_name ,@LogicName ,@RootID ,NULL)--For each table insert every fieldINSERT INTO @Entionary ([Type] ,[PhisicName] ,[LogicName] ,[Parent] ,[Synonym])select'Field' ,c.name ,'LogicField_' + c.name ,@@identity ,NULLFROMsys.columns AS cINNER JOINsys.objects AS oON (o.object_id = c.object_id)WHEREo.name = @object_name--Move next :PFETCH NEXT FROM Table_cursorINTO @object_name , @modify_date--End of cursorEND--Close an Deallocate cursorCLOSE Table_cursorDEALLOCATE Table_cursor--I Can't use agregate functions with update from (I Don't know why)... with declared tables, use the temp tableSELECT * INTO #temp FROM @Entionary-- other example for set a xml field, only thatUPDATE #temp SET [Help] = t.ResultFROM(SELECT ID, CONVERT(XML, '' + CHAR(13) + CHAR(9) + 'MRP '+ CHAR(13) + CHAR(9) + '23/09/2010 '+ CHAR(13) + CHAR(9) + '' + [LogicName] + ' '+ CHAR(13) + CHAR(9) + '' + [PhisicName] + ' '+ CHAR(13) + CHAR(9) + '' + CHAR(13) + ' ' ) AS ResultFROM #temp ) AS t INNER JOIN #temp ON ( #temp.id = t.id)--show the ResultSetSELECT * FROM #temp--Drop the temp tableDROP TABLE #temp
No hay comentarios:
Publicar un comentario