You can't use a SELECT
statement or an integer variable as the size of the column in an ALTER TABLE
statement. As a general rule, you can't mix DDL (data description language, e.g., CREATE
, ALTER
, DROP
) and DML (data manipulation language, e.g., SELECT
, INSERT
, UPDATE
) in the same statement.
What this means is that you'll have to use dynamic SQL just to accomplish the task. You won't be able to use dynamic SQL to build static SQL that you can save and reuse. You'll need to retrieve the maximum length of the field and save it to a variable, and then construct the ALTER
statement, and finally EXEC ()
the ALTER
statement. The easiest way to do that is probably with a cursor through INFORMATION_SCHEMA.COLUMNS
, but you can use doubly dynamic SQL, too. That is, dynamic SQL that itself generates dynamic SQL. That's much harder to debug, however.
Beyond that, I question the validity of what you're trying to do. Simply put, you should never need to use this code. The database schema should be relatively fixed because altering it has significant impacts on performance. By changing the size of a column, you're telling the database engine that it needs to change the way it stores the data on the disk physically, and that's not something you should be doing lightly or regularly. You'll be much further along just setting the value large enough to accommodate user needs. Modern RDBMSs are much better about not storing data inefficiently, but altering column sizes often is still poor practice.