ALTER TABLE my_table添加@column INT [英] ALTER TABLE my_table ADD @column INT

查看:224
本文介绍了ALTER TABLE my_table添加@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添加@column INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆