Home > Back-end >  Get contents of the whole column
Get contents of the whole column

Time:09-23

I am trying to retrieve the contents of an entire column. Select in brackets gets me the correct column names. The result returns instead of data the column name as many times as there are rows with data in the table (instead of data).

WHILE @cnt < @column_count
BEGIN
    SELECT (
        SELECT *
        FROM #TEMP_COLUMN_NAME
        ORDER BY (SELECT null)
        OFFSET @CNT ROWS FETCH NEXT 1 ROWS ONLY
    ) FROM DDServices_History;

    SET @CNT = @CNT   1;
END;

I receive something like this:

enter image description here

And I would like to get the data from these tables and not the column names.

CodePudding user response:

You need to use dynamic SQL. Something like this:

DECLARE  @SqlStatment AS NVARCHAR(1000);

Then within your loop:

SET @SqlStatment = 'SELECT '   (
        SELECT *
        FROM #TEMP_COLUMN_NAME
        ORDER BY 1
        OFFSET @CNT ROWS FETCH NEXT 1 ROWS ONLY
    )   ' FROM DDServices_History';
    
EXECUTE sp_executesql @SqlStatment;
  • Related