sql - 如何在sql的while循环中的object_id语句中使用表名中的变量
问题描述
我需要删除不同数量的表,这取决于 while 循环。除了 object_id 语句的解释之外,循环中的所有内容都有效。我的代码如下所示:
declare @t int = 10
while @t <=11
begin
if object_id('[a\b].rot@t'. 'U') is null
drop table [a\b].rot@t
set @t = @t + 1
end
这给了我如下错误消息:“消息 102,级别 15,状态 1,第 16 行 '@t' 附近的语法不正确。”
错误消息指的是 if object_id 语句中的“@t”。
我尝试了与示例代码中类似的 if object_id 语句的不同版本,但没有任何运气。如果我对值进行硬编码,则脚本按预期工作。
短循环间隔仅用于测试,短代码是我遇到的问题的一个示例。实际上,循环间隔和代码都更长且更复杂。
由于公司规则,我无法提供源数据,但我希望有人可以帮助解决如何让我的“if object_id”语句来理解我的表名中的变量。提前致谢!
解决方案
好吧,我不知道您使用 MSSQL 或 MYSQL 或其他什么 SQL。
这种语法我不熟悉什么:'[a\b].rot@t' 所以我在下面写了一个注释,你可能不得不以不同的方式做,因为我不熟悉它是如何工作的。
但语法可能不同,但您可以执行以下操作:
DECLARE @DynamicSQL varchar(MAX) = ''
declare @t int = 10
while @t <=11
begin
if object_id('[a\b].rot@t'. 'U') is null
-- here instead of doing drop directly build out a string:
--drop table [a\b].rot@t dont do this
-- though I am not familar with this syntax of the @t in the string, so you may have to concat that with the drop table some other way
SET @DynamicSQL = 'drop table [a\b].rot@t'
-- then execute the dynamic SQL variable
EXEC @DynamicSQL
set @t = @t + 1
end
推荐阅读
- reactjs - 反应useCallback不更新功能
- javascript - 无法在我的 html 上显示第三个幻灯片
- spring-boot - 强制验证注解提供消息
- visual-studio-code - Visual Studio Code,如何将文件或文件夹从一个分支复制到另一个分支?
- apache-flink - 当输入文件很大时,AWS EMR 上的 Flink akka AskTimeoutException
- java - JDK 17:Switch 语句导致 java.lang.VerifyError:操作数堆栈上的类型错误
- javascript - 我无法将 firebase 连接到我的 html 文件
- php - 如何在 laravel 任务调度程序中运行 queue:work 命令?
- python - 根据条件删除相邻的列表元素?
- triggers - EEG BIOSEMI 引发精神病