I am new to using cursors for looping through a set of rows. But so far I had prior knowledge of which columns I am about to read.
E.g.
DECLARE db_cursor FOR
SELECT Column1, Column2
FROM MyTable
DECLARE @ColumnOne VARCHAR(50), @ColumnTwo VARCHAR(50)
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @ColumnOne, @ColumnTwo
...
But the tables I am about to read into my key/value table have no specific structure and I should be able to process them one row at a time. How, using a nested cursor, can I loop through all the columns of the fetched row and process them according to their type and name?
SQL is not very good in dealing with sets generically. In most cases you must know column names, data types and much more in advance. But there is XQuery. You can transform any
SELECT
into XML rather easily and use the mighty abilities to deal with generic structures there. I would not recommend this, but it might be worth a try:The idea in short
sys.objects
) we can write the SELECT and force it that way.SELECT
will read each row and return a classical EAV-list.TSQL cursors are not really designed to read data from tables of unknown structure. The two possibilities I can think of to achieve something in that direction are:
SELECT * FROM TABLE_NAME FOR XML AUTO
and further process the retrieved data for your purposes (see FOR XML (SQL Server)).