Assuming that you only have columns called Col1
, Col2
, ... Col56
, and that are in the "correct" order (ascending my numerical value) you could do something like:
CREATE TABLE YourTable (Col1 int,
Col3 int,
Col4 int,
Col5 int,
Col6 int,
Col7 int,
Col8 int,
Col9 int,
Col10 int);
SELECT *
FROM dbo.YourTable;
GO
DECLARE @SQL nvarchar(MAX);
DECLARE @TableName sysname = N'YourTable';
SET @SQL = N'ALTER TABLE ' + QUOTENAME(@TableName) + N' DROP COLUMN ' +
STUFF((SELECT N',' + QUOTENAME(C.COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.TABLE_NAME = @TableName
AND C.ORDINAL_POSITION > 4
--AND C.COLUMN_NAME LIKE N'Col%' --uncomment if needed
ORDER BY C.ORDINAL_POSITION
FOR XML PATH(N''),TYPE).value(N'.',N'nvarchar(MAX)'),1,1,N'') + N';';
PRINT @SQL;
EXEC sp_executesql @SQL;
GO
SELECT *
FROM dbo.YourTable;
GO
DROP TABLE YOurTable;
DB<>Fiddle
INFORMATION_SCHEMA.COLUMNS
– Andrea