在 SQL 中重命名表时使用表名中的变量 [英] use a variable in the table name when renaming a table in SQL

查看:42
本文介绍了在 SQL 中重命名表时使用表名中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码重命名 SQL Server 2008 R2 中的表;

I am trying to rename a table in SQL Server 2008 R2 using the code below;

declare @date varchar(8)
set @date = convert( varchar(8), getdate(), 112)

exec sp_rename 'LM_SM_Billing_and_Send_Data', 'LM_SM_Billing_and_Send_Data_@date'

我的目的是重命名表格并附加当前日期.

My intention is to rename the table with the current date appended.

select convert( varchar(8), getdate(), 112)

返回 20141219

returns 20141219

但是当我运行重命名时,它会为表命名;

but when I run the rename it names the table;

LM_SM_Billing_and_Send_Data_@date  

而不是插入日期

我想知道是否可以将其重命名为;

I'm wondering if it is possible to have it rename to;

LM_SM_Billing_and_Send_Data_20141219

通过使用表名中的变量.

by using the variable in the table name.

我一直在谷歌上搜索很多东西,似乎指向使用动态 SQL,但我从未使用过它,并且不确定获得我正在寻找的结果的语法是什么.

I've been googling quite a bit and things seem to point to using dynamic SQL, but I've never used it and not sure what the syntax would be to get the results I am looking for.

推荐答案

您在这里遇到的问题,正如 John Saunders 在他的评论中指出的那样,SQL 不会将您的变量的值替换为您的参数.(字符串插值)

The issue you've ran into here, as John Saunders pointed out in his comment, SQL won't substitute the value of your variable into your parameter. (String interpolation)

在尝试解决此问题时,您可能会遇到的另一个问题是在过程调用中进行连接.以下也工作.

Another issue you might run into, when trying to work around this problem, is concatenating in the procedure call. The following will also not work.

exec sp_rename 'LM_SM_Billing_and_Send_Data', 'LM_SM_Billing_and_Send_Data_' + @date

上面也会出错的原因,是因为参数可以是变量,也可以是常量,而不是如上所示的表达式.如果我们声明 @myNewName,并将所需的值设置到该变量中,我们就可以将其传递给过程.

The reason the above will also error, is because a parameter can be either a variable, or a constant, not an expression as the above shows. If we declare @myNewName, and set the desired value into that variable, we can then pass that to the procedure.

试试这个:

declare @date varchar(8)
set @date = convert( varchar(8), getdate(), 112)

declare @myNewName varchar(255) = 'LM_SM_Billing_and_Send_Data_' + @date

exec sp_rename 'LM_SM_Billing_and_Send_Data', @myNewName

这可能是一个很好的参考,因为人们继续使用 SQL 参数:http://msdn.microsoft.com/en-us/library/ms189260(v=sql.105).aspx

This may be a good reference as one continues to work with SQL parameters: http://msdn.microsoft.com/en-us/library/ms189260(v=sql.105).aspx

这篇关于在 SQL 中重命名表时使用表名中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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