Question

I'm trying to create a script that when run against a DB takes a column and sets it to NOT NULL.

The column is supposed to be a VARCHAR(50), and if I knew it hadn't been changed this would be a piece of cake, However, I can't be certain that no one has altered the length, so I need to make sure I don't reduce the size of the column if for example it's been increased to 100 by someone else.

I was hoping I could do something like this, but it doesn't seem to work (assume I've already made sure there are no NULL values):

DECLARE @myColumnLength INT

SET @myColumnLength = (
    SELECT character_maximum_length
    FROM information_schema.columns
    WHERE table_name = 'mytable'
    AND column_name = 'mycolumn'
)

ALTER TABLE mytable
    ALTER COLUMN mycolumn VARCHAR(@myColumnLength) NOT NULL 

Any ideas? Am I attacking the problem in a wrong way? It would seem logical there'd be a way to set a column to NOT NULL without altering the column size, but my Google-fu is failing me today.

Was it helpful?

Solution

You can create a dynamic statement and execute it with EXEC:

DECLARE @myColumnLength INT

SET @myColumnLength = (
    SELECT character_maximum_length
    FROM information_schema.columns
    WHERE table_name = 'mytable'
    AND column_name = 'mycolumn'
)

DECLARE @cmd VARCHAR(1000)
SET @cmd = 'ALTER TABLE mytable ALTER COLUMN mycolumn VARCHAR(' + @myColumnLength + ') NOT NULL'

EXEC (@cmd)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top