简体   繁体   English

更改表列语法错误

[英]Alter Table Column Syntax Error

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'. '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 编辑:可以接收@nome的值的示例

  • Very Bad 很坏
  • Bad
  • Good
  • Very Good 很好

You've indicated that @nome may contain, for instance, Very Bad. 您已经指出@nome可能包含例如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: 如果是这样,则它包含一个空格-您需要分隔名称,以便SQL Server知道该空格是名称的一部分:

SELECT @sql = 'ALTER TABLE #temp3 ADD [' + @nome + '] INT'
EXEC (@sql);

or more properly, use QUOTENAME 或更正确地使用QUOTENAME

SELECT @sql = 'ALTER TABLE #temp3 ADD ' + QUOTENAME(@nome) + ' INT'
EXEC (@sql);

Otherwise, SQL Server is trying to add a column called Very with a datatype of Bad , and it doesn't even know how to interpret int after that. 否则,SQL Server尝试添加一个名为Very的列,其数据类型为Bad ,并且在此之后它甚至不知道如何解释int

thanks to @Damien that encourage me to investigate: 感谢@Damien鼓励我进行调查:

if object_id(N'#tempg') is not null
    drop table #tempg

select 1 as i into #tempg

select * from #tempg

alter table #tempg add j int

exec sp_executesql N'alter table #tempg add k int'

select * from #tempg

note that 注意

exec 'alter table #tempg add l int'

fails with 失败于

Msg 102, Niveau 15, État 1, Ligne 1
Syntaxe incorrecte vers 'alter table #tempg add l int'.

============================================= Edition ==========================================版本

exec ('alter table #tempg add l int')

runs 运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM