0

I'm trying to print the list of fields in each schema and table dynamically. since I need a print for further references not a table, I used a cursor to print them out, as follows:

DECLARE AutoFields CURSOR
FOR
    SELECT TABLE_SCHEMA,TABLE_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
OPEN AutoFields
DECLARE @TableSchema NVARCHAR(100)
DECLARE @TableName NVARCHAR(100)

FETCH NEXT
FROM AutoFields
INTO @TableSchema,@TableName

WHILE @@FETCH_STATUS = 0
BEGIN
    EXECUTE('
            SELECT COLUMN_NAME
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_SCHEMA=@TableSchema
            AND TABLE_NAME=@TableName
           ')
     FETCH NEXT
     FROM AutoFields
     INTO @TableSchema,@TableName
END 

CLOSE AutoFields
DEALLOCATE AutoFields

But i get this error over and over again:

Must declare the scalar variable "@TableSchema".

What am I missing here?

2 Answers 2

1

Why can't you just write

SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS

Also i think you need this in CURSOR

DECLARE AutoFields CURSOR
FOR
    SELECT TABLE_SCHEMA,TABLE_NAME
    FROM INFORMATION_SCHEMA.tables --Not Columns
Sign up to request clarification or add additional context in comments.

2 Comments

because as i explained, i want the print of them for further usage, not a table with rows.
@Miss.Alpha - your execute('..') doing same thing as what my first query is doing. Not sure where you are printing it
1

You need to use the variables to concatenate your dynamic string, not be a part of it. Like this:

EXECUTE('
        SELECT COLUMN_NAME
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA= ''' + @TableSchema + '''
        AND TABLE_NAME= ''' + @TableName + '''
       ')

2 Comments

There's still a problem: Invalid column name 'x'. 'x' is the name of all the table names!
I'm not following you. What part of the code is this error occurring on? I don't see anywhere in the code you posted that it could happen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.