문제

I am in need to pulling a table's name as a value in a column. What makes it difficult is that the query is setup as a loop - the query retrieves data from multiple tables, but without the table name/ID, I cannot tell from which table the data was retrieved. It is a rather large query, so I am not including the entire thing, rather the info which I believe represents my issue. The loop goes through approximately 100 tables, but the results don't reflect the table from which the data came. Example of the results is also shown below.

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

Results:

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
도움이 되었습니까?

해결책

SELECT ''' + @zone +''' as zone
,e.NetworkID
,network.name as Network
...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top