【问题标题】:Dynamic Query with if and UNION ALL使用 if 和 UNION ALL 进行动态查询
【发布时间】:2017-08-23 14:08:42
【问题描述】:

我正在尝试编写一个选择语句来将数据插入到表中。 我需要从所有以“Centers”开头的数据库和这些数据库中以“AcctHist”开头的所有表中选择数据。我正在使用交叉连接来获取 Databasename.Tablename 的所有可能组合。但是,由于所有此类组合均无效,因此我正在尝试检查该表是否在选择之前存在。我将此添加为动态查询的一部分......但随后我在 if 语句之间得到了一个 UNION。 是否可以从 CTE 中仅选择有效的 DB.table 组合?在动态查询中不做?

 declare @tsql nvarchar(max)
 set @tsql = ''

 ;with cte_dbtabnames
 as
 (
     select d.name dbname,t.name tbname
      from sys.databases d
      cross join sys.tables t
      where d.name like 'Centers%'
      and t.name  like 'AcctHist%'
 )

  select @tsql = @tsql + case len(@tsql) when 0 then '' else ' UNION ALL '  end +

   'if object_id(''['+ dbname + '].dbo.['+ tbname + ']'') is not null       begin '+ ' select * from [' + dbname + '].dbo.['+ tbname + '] end' 
  from cte_dbtabnames

 select @tsql
 exec(@tsql)

【问题讨论】:

    标签: tsql


    【解决方案1】:

    您需要使用系统表根据在每个数据库中找到的表生成动态 sql。这段代码应该可以帮助您入门。

    declare @SQL nvarchar(max) = ''
    
    select @SQL = @SQL + 'select DatabaseName = ''' + name + ''', * from [' + name + '].sys.tables t where t.name like ''AcctHist%'' UNION ALL '
    from sys.databases d
    where name like 'Centers%'
    
    set @SQL = left(@SQL, len(@SQL) - 10)
    
    select @SQL
    --uncomment the exec line below when you are comfortable the dynamic sql is correct.
    --exec sp_executesql @SQL
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多