<?xml version="1.0" encoding="utf-8" ?>
<root>
    <sqlSnippet id="1">
        <name>
            Generate select statement for temp table.
        </name>
        <params>
        	<param pid="1" usage="TableName">b227a7d1-bf9b-4011-88cc-87e58cb481df</param>
        </params>
        <code>
DECLARE @SqlStatement NVARCHAR(MAX);
DECLARE @xyzFoo TABLE (ID INT IDENTITY(1,1), SqlS NVARCHAR(MAX));
INSERT INTO @xyzFoo (SqlS)
SELECT
      'SELECT '
     UNION ALL
SELECT 
        '     ['+C1.COLUMN_NAME+']'+
        CASE 
            WHEN C1.ORDINAL_POSITION=TBL.COL_COUNT THEN CHAR(10)+'FROM '+LEFT(C1.TABLE_NAME, CHARINDEX('___',C1.TABLE_NAME,3)-1)
            ELSE ','+CHAR(10)
        END
FROM tempdb.Information_schema.COLUMNS C1
    INNER JOIN
        (SELECT T2.TABLE_NAME, C2.COL_COUNT, 
        ROW_NUMBER() OVER (PARTITION BY T2.TABLE_SCHEMA,LEFT(T2.TABLE_NAME,15) ORDER BY T2.TABLE_NAME DESC) AS RN
        FROM tempdb.INFORMATION_SCHEMA.TABLES T2
                INNER JOIN 
                (
                    SELECT C2.TABLE_SCHEMA,C2.TABLE_NAME,MAX(ORDINAL_POSITION) AS COL_COUNT
                        FROM    tempdb.INFORMATIOn_SCHEMA.COLUMNS C2
                        GROUP BY C2.TABLE_SCHEMA,C2.TABLE_NAME
                        ) C2
                    ON T2.TABLE_NAME=C2.TABLE_NAME
                    AND T2.TABLE_SCHEMA=C2.TABLE_SCHEMA
                ) TBL
                ON C1.TABLE_NAME=TBL.Table_Name
                AND TBL.RN=1
WHERE C1.TABLE_NAME LIKE 'b227a7d1-bf9b-4011-88cc-87e58cb481df%';
SELECT @SqlStatement=COALESCE(@SqlStatement,'')+xf1.SqlS
FROM @xyzFoo xf1;
EXECUTE sp_ExecuteSQL @SqlStatement;
SELECT @SqlStatement;
</code>
    </sqlSnippet>
</root>
