带有表名和列名变量的 DDL 语句
在我的存储过程中,我创建了一个 temp_tbl
并希望在游标或 while 循环中添加几列。光标一切正常(创建 temp_bl
但当列字符串位于 varchar 变量中时,我无法添加该列。
WHILE @@FETCH_STATUS = 0
BEGIN
SET @webadressenrow = 'Webadresse_'+CAST(@counter as nchar(10))
ALTER TABLE IVS.tmpBus
ADD @webadressenrow varchar(500) Null
fetch next from cur_web into @webadressen
SET @counter = @counter + 1
END
上面的代码会导致语法错误,而以下代码可以工作:
WHILE @@FETCH_STATUS = 0
BEGIN
SET @webadressenrow = 'Webadresse_'+CAST(@counter as nchar(10))
ALTER TABLE IVS.tmpBus
ADD SOMECOLUMNAME varchar(500) Null
fetch next from cur_web into @webadressen
SET @counter = @counter + 1
END
有人能给我这个小问题的语法提示吗?
In my stored procedure, I make a temp_tbl
and want to add several columns in a cursor or while loop. All works fine the cursor (the creation of a temp_bl
but I can´t add the column when the column string is in a varchar variable.
WHILE @@FETCH_STATUS = 0
BEGIN
SET @webadressenrow = 'Webadresse_'+CAST(@counter as nchar(10))
ALTER TABLE IVS.tmpBus
ADD @webadressenrow varchar(500) Null
fetch next from cur_web into @webadressen
SET @counter = @counter + 1
END
The code above results in a syntax error, while this code works:
WHILE @@FETCH_STATUS = 0
BEGIN
SET @webadressenrow = 'Webadresse_'+CAST(@counter as nchar(10))
ALTER TABLE IVS.tmpBus
ADD SOMECOLUMNAME varchar(500) Null
fetch next from cur_web into @webadressen
SET @counter = @counter + 1
END
Can anybody give me a syntax hint to this small problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将无法参数化 ALTER TABLE 语句,但您可以构建 SQL 并执行它,如下所示:
不过要小心安全/SQL 注入攻击。
You won't be able to parameterise the
ALTER TABLE
statement but you could build up the SQL and execute it something like this:Be careful about security/SQL-Injection attacks though.
一般来说 DDL 语句,即定义表和列的语句不接受表或列名称的变量。
有时您可以通过准备语句来解决这个问题,但并非所有数据库引擎都提供对准备好的 DDL 的支持。
以下示例适用于 SQL Server 2005,但我建议动态添加列可能不是最佳解决方案
产生以下结果
Generally speaking DDL statements i.e. those that define tables and columns do not accept variables for table or column names.
You can sometimes get around that by preparing the statements but support for prepared DDL is not provided by all database engines.
The following example works in SQL Server 2005, although I would suggest that adding columns dynamically may not be the optimal solution
Produced the following results
我已经用非最佳方式解决了问题。
该代码非常适合我。我希望另一个沮丧的程序员可以使用这个。
i have Solved The Problem with the Non optimal Way.
The Code Works prefectly for me. i Hope another frustrated programmer can Use this.