0

I am creating a procedure in SQL Server and I need to extract columns of that respected table. I extracted the column_name but when I used inside the cursor the statement:

select distinct @column_name from AogerCnlyOi.dbo.CnlyOiDealAnalysis

Here I need the data containing inside the column. But I get the name of column in the output.

USE AogerCnlyOi
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


    create PROCEDURE [dbo].[QC_Actian_SSIS] AS
    
    DECLARE @column_name VarChar(MAX)
    declare @data_type VarChar(MAX)
    
    
    BEGIN
    
    Declare cur_tracking CURSOR FOR
    select column_name,data_type from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='CnlyOiDealAnalysis' order by ordinal_position
    
    OPEN cur_tracking;
    FETCH NEXT FROM cur_tracking INTO @column_name,@data_type;
    WHILE @@Fetch_status=0
    begin
    
    select distinct @column_name from AogerCnlyOi.dbo.CnlyOiDealAnalysis
    
    FETCH NEXT FROM cur_tracking INTO @column_name,@data_type;
    END;
    CLOSE cur_tracking;
    DeAllocate cur_tracking;
    
    END 
    Go

Suppose my first column name was "AuditGroup" then I need the data inside the "AuditGroup" while using:

select distinct @column_name from AogerCnlyOi.dbo.CnlyOiDealAnalysis

but I am getting output as:

enter image description here

Since AuditGroup is the column name I need the data of Auditgroup. How can I achieve this?

Dale K
  • 25,246
  • 15
  • 42
  • 71
  • you will need to use dynamic query [sp_executesql](https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-ver16) – Squirrel Jul 13 '22 at 08:07
  • 1
    This feels like an [xy problem](//xyproblem.info) if I am honset. What are you *actually* trying to achieve here? – Thom A Jul 13 '22 at 08:08
  • @Squirrel yes it worked thank you. please put separate ans so i can tick – Dikshit Karki Jul 13 '22 at 08:13

0 Answers0