• Assuming I understood your original question, here is a simplified example, per your request. I used information schema to get the answer. Try to rewrite it using sys.tables & sys.columns like your original homework hinted at, and add in the missing clauses to always pull the first table name. The trick with dynamic sql is writing the select statement correctly in the first place because all the extra single quotes will screw you up...constantly.

    DECLARE

    @SQL VARCHAR(MAX),

    @TableName VARCHAR(100)

    --Get your table name and store it as a variable

    SELECT TOP 1 @TableName = Table_Name FROM INFORMATION_SCHEMA.columns

    --Create the dynamic statement to count the columns

    SET @SQL = '

    SELECT

    [CountOf'+@TableName+'] = COUNT(*)

    FROM information_schema.columns

    WHERE table_name = '''+@TableName+'''

    GROUP BY table_name'

    --Print & Execute the statement

    PRINT @SQL

    EXEC(@SQL)