I'm making a way for our developers to easily update our database. The way we're doing this is by creating dynamic queries where they define the variables at the top and the query uses the variables for everything else. I've used many recommendations off Stackoverflow, but can't get this to work.
USE MyDatabase DECLARE @TABLE VARCHAR(200) = 'MyTable' DECLARE @COLUMN VARCHAR(200) = 'MyColumn' DECLARE @DATATYPE VARCHAR(200) = 'VARCHAR(200)' IF COL_LENGTH(@TABLE, @COLUMN) IS NULL BEGIN DECLARE @SQL as NVARCHAR(MAX) = 'ALTER TABLE ' + @TABLE + ' ADD COLUMN ' + @COLUMN +' '+ @DATATYPE EXEC SP_EXECUTESQL @SQL END I get the error:
Incorrect syntax near the keyword 'COLUMN'.
ALTER TABLEdocumentation, you can't specify theCOLUMNkeyword there. You have to specify it when dropping a column, but it is not legal syntax when adding. It's one of those SQL Server inconsistencies that nobody can really justify but is also unlikely to ever get fixed.