ALTER TABLE my_table ADD @column INT(ALTER TABLE my_table ADD @column INT)
问题描述
如果我想使用一个变量作为新列的名称,这在 MS SQL 中可行吗?
If i want to use a variable as name of the new column, is this posible in MS SQL?
不起作用的例子:
ALTER TABLE my_table ADD @column INT
这对我很有用:
EXEC ('ALTER TABLE my_table ADD ' + @column + ' INT')
推荐答案
这可以使用动态 sql 构建您的 DDL 并使用 EXEC
命令执行字符串.
This is possible using dynamic sql to build your DDL and using the EXEC
command to execute the string.
Declare @SQL VarChar(1000)
SELECT @SQL = 'ALTER TABLE my_table ADD ' + @column + ' INT'
Exec (@SQL)
请参阅这篇文章.
我还要补充一点,当您冒险进入动态 sql 领域时,您需要注意不要将自己暴露在 SQL 注入攻击.总是清理传入的参数.
I will also add that the moment you venture to the land of dynamic sql, you need to take care to not expose yourself to SQL Injection attacks. Always clean up the parameters coming in.
正如 Philip 所提到的 - 在执行此操作之前要深思熟虑.可能的事实并不使它成为一件好事...
As Philip mentions - think long and hard before doing this. The fact that it is possible does not make it a good thing...
Erland Sommarskog 写了一篇关于使用动态 SQL 的详尽文章 - 动态 SQL 的诅咒与祝福我建议阅读全文.
Erland Sommarskog wrote an extensive article about using dynamic sql - The curse and blessings of dynamic SQL which I recommend reading fully.
这篇关于ALTER TABLE my_table ADD @column INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ALTER TABLE my_table ADD @column INT


- SQL 临时表问题 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01