检查联合查询中是否存在SQL表

时间:2014-05-28 12:36:38

标签: sql-server sql-server-2008 if-statement

我该怎么做?我试图在我的表上运行如下的查询。但首先我要检查数据库是否存在。我试图运行以下语法,但它给我一个编译错误: '关键字'IF'附近的语法不正确。'

if object_id('table1') Is not null
Select empName, empStoreNum, empSales, 'East' As SalesDistrict
FROM store1
UNION ALL
if object_id('table2') is not null
Select empName, empStoreNum, empSales, 'East' As SalesDistrict
FROM store2
UNION ALL
if object_id('table3') is not null
Select empName, empStoreNum, empSales, 'East' As SalesDistrict
FROM store3

3 个答案:

答案 0 :(得分:4)

DECLARE @temp TABLE(empName varchar(100),empStoreNum varchar(100),empSales int,location varchar(20))
if object_id('table1') Is not null
insert into @temp
Select empName, empStoreNum, empSales, 'East' As SalesDistrict
FROM store1

if object_id('table2') is not null
insert into @temp
Select empName, empStoreNum, empSales, 'East' As SalesDistrict
FROM store2

if object_id('table3') is not null
insert into @temp
Select empName, empStoreNum, empSales, 'East' As SalesDistrict
FROM store3


select empName, empStoreNum, empSales,location
from @temp

答案 1 :(得分:2)

你不能。查询中的表需要存在。我可以想到两种方法来解决你的问题。一个使用临时表和另一个动态SQL。第一种方法看起来像这样:

declare @t table (empName varchar(255), empStoreNum int, empSales money);
if object_id('table1') Is not null
    insert into @t(empName, empStoreNum, empSales)
        Select empName, empStoreNum, empSales, 'East' As SalesDistrict
        FROM store1;

if object_id('table2') is not null
    insert into @t(empName, empStoreNum, empSales)
        Select empName, empStoreNum, empSales, 'East' As SalesDistrict
        FROM store2;

if object_id('table3') is not null
    insert into @t(empName, empStoreNum, empSales)
        Select empName, empStoreNum, empSales, 'East' As SalesDistrict
        FROM store3;

select *
from @t;

答案 2 :(得分:1)

在我的例子中,我正在执行一个sql语句。它检查数据库'AdventureWorksDW2012' 如果数据库存在,则检查表'DimDate'。如果表存在,则执行样本选择步骤。

我正在使用此示例,因为您没有提供数据库名称。

Use master
Go

if Exists(
Select * from sys.databases where name = 'AdventureWorksDW2012')
begin
    Declare @sql  varchar(max) = 
    'use [AdventureWorksDW2012]

    if Exists(
    Select 1 from sys.tables where name = ''DimDate''
    )
    begin
        Select 1
    End
    '

    Exec (@sql)
End

结果

--When AdventureWorksDW2012 exists and it contains DimDate

enter image description here

希望这有帮助。