在SQL Server中是否可以以这种方式检查表是否存在?如果它不存在,它将运行catch
declare @SQL varchar(4444)
select @SQL = '
begin try
select * from ServerName.DBName.dbo.TableNAme
end try
begin catch
select 1
end catch'
exec (@SQL)
Run Code Online (Sandbox Code Playgroud)
我不想使用这里描述的解决方案,因为我想使用与上面完全相同的表结构.
原因:我将在循环中运行多个动态查询,并且在ServerName,DbName,TableName之上将作为参数传递.
它应该工作,如果你动态地这样做.如果不动态执行,则会在解析时捕获丢失的表,并且不会触发CATCH.
编辑:我的意思是这样的:
declare @SQL varchar(4444)
select @SQL = 'select * from ServerName.DBName.dbo.TableNAme'
begin try
exec (@SQL)
end try
begin catch
select 1
end catch
Run Code Online (Sandbox Code Playgroud)