How to create 500 columns programatically in SQL Server? [duplicate]

That table is really a very bad design. Anyway, here you have the code. It uses dynamic sql:

DECLARE @sql nvarchar(max)

SET @sql = N'CREATE TABLE TheMostStupidTableIHaveEverSeen(ID int, Name varchar(100)'
DECLARE @i int = 1
WHILE @i <= 598
BEGIN
    SET @sql = @sql + N', A' + CAST(@i AS nvarchar(4)) + N' int'
    SET @i = @i + 1
END
SET @sql = @sql + N')'
EXEC (@sql)

Leave a Comment