If you have to do this using Dynamic SQL, this should get you started:
DECLARE @SQL nvarchar(MAX);
SELECT @SQL = N'SELECT ' +
STUFF(CONVERT(varchar(MAX),(SELECT N',' + NCHAR(10) + QUOTENAME(c.[name])
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.[name] NOT IN (N'PathwayCode',N'Gamma')
--Note I use STRING_SPLIT ehre, which is a 2016 Function
--You'll need to find a String Splitter for prior versions
AND t.[name] = N'YourTable'
FOR XML PATH(N''), TYPE)),1,2,N'') + NCHAR(10) +
N'FROM YourTable;';
PRINT @SQL;
EXEC sp_executesql @SQL;
Honestly, though, this seems more work than it solves; especially as we're only omitting 2 columns. SSMS can easily provide a SELECT
statement with all the column in, and you can then easily remove those from the statement.
If you need a more permanent object, then use a VIEW
.
Edit:
If you want to make this "truly" dynamic, you could do it this way:
CREATE PROC Select_Exclude @Table sysname, @Columns nvarchar(4000) AS
DECLARE @SQL nvarchar(max);
SELECT @SQL = N'SELECT ' +
STUFF(CONVERT(varchar(MAX),(SELECT N',' + NCHAR(10) + QUOTENAME(c.[name])
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.[name] NOT IN (SELECT SS.[value] FROM STRING_SPLIT(@Columns,',') SS)
AND t.[name] = N'YourTable'
FOR XML PATH(N''), TYPE)),1,2,N'') + NCHAR(10) +
N'FROM ' + QUOTENAME(ot.[name]) + ';'
FROM sys.tables ot
WHERE ot.[name] = @Table;
PRINT @SQL;
EXEC sp_executesql @SQL;
GO
EXEC Select_Exclude @Table = N'YourTable', @Columns = N'PathwayCode,Gamma';
But again, why..? This is just over the top. I really did this more to prove a point.