动态SQL创建视图

时间:2015-07-15 12:35:57

标签: sql-server-2008 view inline-code

我有一个表格,其中包含一些低于标准的商店名称列表。每个商店名称在服务器上都有自己的数据库(我们正在合并所有数据库,但目前所有数据库都是独立的)。是否可以迭代表(称为故障存储)并创建一个视图来保存所有故障存储的数据?这是表结构:(当然是垃圾数据)

create table failingstores
(
  storename varchar(100)
  ,weeklysales int
  ,monthlysales int
  ,storemanager varchar(100)
)

Insert Into failingstores Values 
('one', 80, 800, 'managerone'), 
('two', 90, 900, 'managertwo'), 
('three', 40, 400, 'managerthree'), 
('four', 10, 100, 'managerfour')

我想要发生的动态sql是迭代storename字段中的值并创建一个视图。所以这将是我的视图语法:

Create view failingstoresfulldata As
Select * from managerone
union all
select * from managertwo
union all
select * from managerthree
union all
select * from managerfour

2 个答案:

答案 0 :(得分:0)

我最近不得不做类似的事情并使用动态SQL将数据从数据库拉到本地表中。当然,存储到本地表是可选的,但是一旦存在,您可以在顶部构建任何其他SQL对象来查询您的内容!

IF OBJECT_ID(N'tempdb..#Databases') is not null
    Drop Table #Databases

Select Name 
Into #Databases
From (Values
     ('Company1DB')
    ,('Company2DB')
    ,('Company3DB')
    ) as db(Name)

Declare @DBName varchar(50),@SQL nvarchar(max)=''

While (select count(*) From #Databases) >1 Begin
    Select Top 1 @DBName=Name From #Databases
    Select @DBName=isnull(@DBName,'')
    Set @SQL=@SQL+'Union All
    SELECT
        Column1
        ,Column2
        ,Column3
    FROM '+@DBName+'.tablename'

    Delete From #Databases where Name=@DBName
End 

Select @SQL=Stuff(@SQL,1,9,'') --- Remove leading "Union All"

Select @SQL --- Preview of Query

--- Pull the data into a single table for easy querying or further manipulation ---
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'FullData') AND type in (N'U')) Begin
    Create Table FullData (
        Column1 int
        ,Column2 int
        ,Column3 int
    )
End Else Begin
    Truncate Table FullData
End

Insert Into FullData Exec SP_ExecuteSQL @SQL,N''

--- Cleanup ---
Drop Table #Databases

答案 1 :(得分:0)

我更喜欢更简单的解决方案:

declare @sql varchar(max) = 'Create view failingstoresfulldata As
'
select @sql = @sql +
'Select * from ' + storemanager + '
union all
'
from failingstores

set @sql = left(@sql, len(@sql)-11)
print @sql
--exec (@sql)

首先使用 print 检查生成的动态 SQL,然后取消注释 exec 命令以便下次运行。