I needed to create a table with dynamic columns, so I created a cursor that loops through the records of a table and will create the necessary columns, however, is giving me this error:
Incorrect syntax near ‘INT’.
Example code:
SELECT @sql = 'ALTER TABLE #temp3 ADD ' + @nome + ' INT'
EXEC (@sql);
I have also tried this:
EXEC ('ALTER TABLE #temp3 ADD ' + @nome + ' INT')
But still the same error
Any suggestions?
Edit:
Examples of values that can receive @nome
- Very Bad
- Bad
- Good
- Very Good
You’ve indicated that
@nomemay contain, for instance, Very Bad. If that is so, it contains a space – you need to delimit the name so that SQL Server knows that the space is part of the name:or more properly, use
QUOTENAMEOtherwise, SQL Server is trying to add a column called
Verywith a datatype ofBad, and it doesn’t even know how to interpretintafter that.