首页 > 解决方案 > 如何在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”语句来理解我的表名中的变量。提前致谢!

标签: sqlvariableswhile-loop

解决方案


好吧,我不知道您使用 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

推荐阅读