use*_*391 4 sql sql-server sql-server-2000
使用Microsoft SQL 2000,我想将多个表(A,B,C和D)连接在一起.我知道桌子A总是存在的.但是,我只知道至少有一种表格形式(B,C,D)存在.
我有什么方法可以做这样的事情来完成我想做的事情?
Select * form table a
If table b exists left Join table b on a.id = b.id
If table c exists left Join table c on a.id = c.id
If table d exists left Join table d on a.id = d.id
Run Code Online (Sandbox Code Playgroud)
您必须检查数据字典视图并使用动态SQL
declare @myquery varchar(1000)
set @myquery = 'Select * from a '
if exists (select * from sysobjects where xtype='U' and name = 'b')
begin
set @myquery = @myquery + 'inner join b on b.id = a.id '
end
if exists (select * from sysobjects where xtype='U' and name = 'c')
begin
set @myquery = @myquery + 'inner join c on c.id = a.id '
end
if exists (select * from sysobjects where xtype='U' and name = 'd')
begin
set @myquery = @myquery + 'inner join d on d.id = a.id '
end
exec( @myquery)
Run Code Online (Sandbox Code Playgroud)
我使用过sysobjects,然而您被鼓励使用信息架构视图,而不是
并且,动态SQL上的一个大型解析器
好处
缺点