0

我需要将表的名称作为列中的值提取。困难在于查询设置为循环 - 查询从多个表中检索数据,但没有表名/ID,我无法判断从哪个表中检索数据。这是一个相当大的查询,所以我不包括整个事情,而是我认为代表我的问题的信息。循环遍历大约 100 个表,但结果不反映数据来自的表。结果示例如下所示。

DECLARE @zone integer
DECLARE ZoneCursor CURSOR FOR

SELECT ZoneID 
FROM Zone 
ORDER BY  ZoneID

      OPEN ZoneCursor

      FETCH NEXT FROM ZoneCursor into @zone

      WHILE @@FETCH_STATUS = 0

      BEGIN

EXEC('

declare @aStart1date as varchar(20)
declare @aStart2date as varchar(20)
-- ENTER THE START AND STOP DATES
set @aStart1date = ''07/24/2013''
set @aStart2date = ''07/24/2013''


SELECT 
    e.NetworkID
    ,network.name as Network
    ,Convert(varchar(16),DateAdd(day,e.BreakDate,''08-12-1960''),101) as Break_Date
    ,Convert(Varchar(32),DateAdd(Second,e.BreakTime,''00:00:00''),108) as Break_Time
    ,b.Length
    ,(CASE
            WHEN b.availtypeid = -1 THEN ''Split Break'' 
            WHEN b.availtypeid = 0 THEN ''None''

    END)  as AvailType

FROM  
    event' + @zone + ' e (nolock), break' + @zone + ' b (nolock), network, availtype

WHERE 
        (e.breakdate >= datediff(day,''8/12/1960'', @aStart1date)
        and e.breakdate<=  datediff(day,''8/12/1960'', @aStart2date))
        and e.networkid = b.networkid 
        and e.breakdate = b.breakdate
        and e.breaktime = b.breaktime
        and b.networkid = network.networkid
        and e.networkid = network.networkid

GROUP by e.networkid, network.name, e.breakdate, e.breaktime,b.length, e.status, b.availtypeid
ORDER by e.networkid, e.breaktime ')

            FETCH NEXT FROM ZoneCursor into @zone
       END

      CLOSE ZoneCursor

DEALLOCATE ZONECURSOR

结果:

NetworkID   Network Break_Date  Break_Time  Length  AvailType
1   CNN 07/24/2013    00:15:00      60  Interconnect
1   CNN 07/24/2013    00:31:00            60    Interconnect
4

1 回答 1

3
SELECT ''' + @zone +''' as zone
,e.NetworkID
,network.name as Network
...
于 2013-09-18T13:46:07.223 回答