1

Is there any way to add variable number of columns to a table.

I am trying below but no success.

DECLARE @VAR INT = 1
WHILE @VAR <=20
BEGIN
    DECLARE @COLUMN VARCHAR(MAX) = 'COLUMN_'+CAST(@VAR AS VARCHAR)
    IF NOT EXISTS(SELECT 1 FROM SYS.columns WHERE OBJECT_ID = OBJECT_ID('MY_TBL') AND name=@COLUMN )
        begin
        ALTER TABLE MY_TBL ADD @COLUMN NVARCHAR(3) NULL;
        end
    SET @VAR += 1
END
4
  • 4
    That's a really bad table design. Why are you embedding data in the metadata (column names). It will also lead to convoluted and confusing queries. The standard way of representing repeating groups of the same "type" of data is as multiple rows of data. Commented Apr 6, 2017 at 6:17
  • 1
    This is bad design. If you have lots of columns with the same type data, make multiple rows instead. Thats what they're for. Commented Apr 6, 2017 at 6:18
  • 1
    Summing up with previous guys here. This is a terrible design. Commented Apr 6, 2017 at 6:20
  • Which DBMS are you using? And yes this is a horrible idea Commented Apr 6, 2017 at 6:27

2 Answers 2

2

You need to use dynamic SQL. Try the following code.

DECLARE @VAR INT = 1
WHILE @VAR <=20
BEGIN
    DECLARE @COLUMN VARCHAR(MAX) = 'COLUMN_'+CAST(@VAR AS VARCHAR)
    IF NOT EXISTS(SELECT 1 FROM SYS.columns WHERE OBJECT_ID = OBJECT_ID('MY_TBL') AND name=@COLUMN )
        begin
        declare @sql varchar(100)= ' ALTER TABLE MY_TBL ADD '+@COLUMN+' NVARCHAR(3) NULL;' 
        exec(@sql);
        end
    SET @VAR += 1
END
Sign up to request clarification or add additional context in comments.

Comments

-1

For SQL-Server:

Format:

SELECT COUNT(*) 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'table' 

Example:

SELECT COUNT(*) 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_CATALOG = 'imDB' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'MovieName'

You can store it in a variable and use it accordingly.

I hope you understood :)

2 Comments

How does this answer the question?
I don't know what was in his mind when he wrote this answer 6 year ago.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.