简体   繁体   English

如果表存在于SQL Server 2008中,则为all all

[英]Union all if the table exists in SQL server 2008

In the below code, I need to check if the table exists in each line. 在下面的代码中,我需要检查每行中是否存在表。 Please tell me how to do it. 请告诉我怎么做。

Select * from Table 1 union all
select * from Table 2 union all
Select * from Table 3

I tried this but didn't work 我尝试了这个,但没有奏效

if objectid ('Table1') is not null
Select * from Table 1 union all
if objectid ('Table2') is not null
select * from Table 2 union all
if objectid ('Table3') is not null
Select * from Table 3

A possible solution would be this: 一个可能的解决方案是:

USE MyDB;

DECLARE @recordsExistingTables TABLE(Column1 nvarchar(50), Column2 nvarchar(50));

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'Table1'))
BEGIN
   INSERT INTO @recordsExistingTables 
   SELECT *
   FROM Table1; 
END 

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'Table2')) 
BEGIN
   INSERT INTO @recordsExistingTables 
   SELECT *
   FROM Table2; 
END 

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'Table3')) 
BEGIN
   INSERT INTO @recordsExistingTables 
   SELECT *
   FROM Table3; 
END 


SELECT * FROM @recordsExistingTables;

Using a table variable, you insert only the rows of the tables that exist in your database. 使用表变量,只插入数据库中存在的表的行。 At the end of the checks, selecting the records of the table variable, you have the rows of each existing table. 在检查结束时,选择表变量的记录,您将拥有每个现有表的行。

Tried to create a sort of generic solution. 试图创建一种通用的解决方案。 Created a procedure, where you have to pass all table names in comma separated values and it will return the complete data list of all tables. 创建了一个过程,您必须以逗号分隔值传递所有表名,它将返回所有表的完整数据列表。

Create Procedure spGetTableData
@tableNames varchar(4000) --expecting all table names in csv format here
As
Begin
declare @sql nvarchar(max);
declare @tablelist table(tablename varchar(50));

--getting all existint table names in one table
set @sql = 'select name from sys.objects where name in (''' + REPLACE(@tableNames, ',',''',''') + ''')';

insert into @tablelist
exec (@sql);

--creating query with union all
set @sql = '';
select @sql = @sql + 'Select * from ' + tablename + ' Union All ' From @tablelist;

set @sql = left(@sql, len(@sql) - 9);

exec sp_executesql @sql;

End

You can execute this as : 您可以执行以下操作:

Exec spGetTableData 'existing1,nonexisting1,existing2,existing3'

Hope it helps. 希望能帮助到你。

The tables do not exist so you will need to build the select statement dynamically. 这些表不存在,因此您需要动态构建select语句。 Here is an example of what you would need to do. 以下是您需要做的一个示例。 I am not going to reproduce all the if statements as there would be 9 different combinations but you should get the general idea. 我不会重现所有if语句,因为会有9种不同的组合,但你应该得到一般的想法。

    if objectid ('Table2') is not null AND objectid ('Table1') IS not null and objectid('Table3') is not null 
    @SelectStatement = 'Select * from Table1 UNION ALL SELECT * FROM TABLE2 UNION ALL SELECT * FROM TABLE3' 

    if objectid ('Table2') is not null AND objectid ('Table1') IS not null and objectid ('Table3') is null 
    @SelectStatement = 'Select * from Table1 UNION ALL SELECT * FROM TABLE2 ' 

    if objectid ('Table2') is not null AND objectid ('Table1') IS null and objectid ('Table3') is not null 
    @SelectStatement = 'Select * from Table2 UNION ALL SELECT * FROM TABLE3 ' 

    if objectid ('Table2') is null AND objectid ('Table1') IS NOT null and objectid ('Table3') is not null 
    @SelectStatement = 'Select * from Table1 UNION ALL SELECT * FROM TABLE3 ' 

    if objectid ('Table2') is null AND objectid ('Table1') IS null and objectid ('Table3') is not null 
    @SelectStatement = 'SELECT * FROM TABLE3 ' 

    if objectid ('Table2') is null AND objectid ('Table1') IS null and objectid ('Table3') is not null 
    @SelectStatement = 'SELECT * FROM TABLE3 ' 

//..... for 3 tables there will be 9 conbinations of TABLE1, TABLE2 and TABLE3 is null checks to perform and possible combinations

EXECUTE sp_executesql @FullStatement

It is worth noting that a union requires all columns to match in type, as well as having the same number of columns. 值得注意的是,union需要所有列在类型上匹配,并且具有相同数量的列。

Assuming that they do match (if they exist), and that you have a fixed number of tables, the following query works: 假设它们匹配(如果它们存在),并且您具有固定数量的表,则以下查询有效:

declare @sql varchar(max)

if object_id('Table1') is not null
Begin
  set @sql = 'select * from Table1'
end 


if object_id('Table2') is not null
Begin
   if len(@sql) > 0 
   begin
      set @sql = @sql + char(10) + 'union all '
   end
  set @sql = @sql + 'select * from Table2'
end 


if object_id('Table3') is not null
Begin
   if len(@sql) > 0 
   begin
      set @sql = @sql + char(10) + 'union all '
   end
  set @sql = @sql + 'select * from Table3'
end 


execute(@sql)

This works by first creating a dynamic SQL statement, and storing it in the @SQL variable. 这首先创建一个动态SQL语句,并将其存储在@SQL变量中。 when done evaluating/creating the statement, it is executed using the execute(@sql) statement 在完成评估/创建语句时,它使用execute(@sql)语句执行

Just as an alternative, and in no way am I suggesting this is the best way to do it, but for my own curiosity I wondered if a CASE could do this. 作为替代方案,我绝不建议这是最好的方法,但出于我自己的好奇心,我想知道CASE是否可以做到这一点。 Turns out it can. 事实证明它可以。 Probably no more or less clunky than any other solution. 可能没有比任何其他解决方案更笨重的笨重。

SET CONCAT_NULL_YIELDS_NULL OFF
DECLARE @sql NVARCHAR(4000)
SELECT @sql = CASE WHEN name = 'table1' THEN 'select * from table1 ' END FROM sys.tables WHERE name = 'table1'

SELECT @sql += CASE WHEN @sql IS NOT NULL AND name = 'table2' THEN ' union all select * from table2' WHEN @sql IS NULL AND name = 'table2' THEN 'select * from table2' END FROM sys.tables WHERE name = 'table2'

SELECT @sql += CASE WHEN @sql IS NOT NULL AND name = 'table3' THEN ' union all select * from table3' WHEN @sql IS NULL AND name = 'table3' THEN 'select * from table3' END FROM sys.tables WHERE name = 'table3'

PRINT @sql

EXEC sp_executesql @sql

You can see it working on this Fiddle (except the sp_executesql bit - SQLFiddle won't return results from that). 你可以看到它在这个小提琴上工作(除了sp_executesql位 - SQLFiddle不会返回结果)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM