2014-02-12 75 views
0

我一直在尋找甲骨文的東西,它像SQL Server中的表變量一樣。我發現有人在這裏提出類似這樣的問題,而人們總是說「是的,Oracle有這樣的」,但是這些例子表明這些實體根本不像SQL Server。有人能告訴我如何在Oracle中執行以下簡單的TSQL解決方案嗎?Oracle中的表變量樣式實體

declare @users table (
    ID int, 
    Name varchar(50), 
    Age int, 
    Gender char(1) 
) 

;with users as (
    select 1001 as ID, 'Bob' as Name, 25 as Age, 'M' as Gender 
    union 
    select 1021 as ID, 'Sam' as Name, 29 as Age, 'F' 
) 
insert into @users (ID, Name, Age, Gender) 
select * from users 

declare @grades table (
    UserID int, 
    ClassID int, 
    Grade int 
) 

;with grades as (
    select 1001 as UserID , 120 as ClassID, 4 as Grade 
    Union 
    select 1001 as UserID , 220 as ClassID, 2 as Grade 
    Union 
    select 1021 as UserID , 130 as ClassID, 4 as Grade 
    Union 
    select 1021 as UserID , 230 as ClassID, 4 as Grade 
    Union 
    select 1021 as UserID , 340 as ClassID, 2 as Grade 
) 
insert into @grades 
select * from grades 

select u.ID, u.Name, GPA = AVG(cast(g.grade as decimal)) 
from @users u 
    inner join @grades g on u.ID=g.UserID 
group by u.ID, u.Name 

回答

2

有些答案可能會告訴你Oracle有表變量,並且它在一定程度上確實存在。但是,大多數答案都會告訴你,你根本不應該在Oracle中這樣做;根本沒有必要。

在你的情況我會簡單地用一個CTE:

with users as (
    select 1001 as ID, 'Bob' as Name, 25 as Age, 'M' as Gender from dual 
    union 
    select 1021 as ID, 'Sam' as Name, 29 as Age, 'F' from dual 
     ) 
, grades as (
    select 1001 as UserID , 120 as ClassID, 4 as Grade from dual 
    Union 
    select 1001 as UserID , 220 as ClassID, 2 as Grade from dual 
    Union 
    select 1021 as UserID , 130 as ClassID, 4 as Grade from dual 
    Union 
    select 1021 as UserID , 230 as ClassID, 4 as Grade from dual 
    Union 
    select 1021 as UserID , 340 as ClassID, 2 as Grade from dual 
      ) 
select u.ID, u.Name, AVG(g.grade) as gpa 
    from users u 
    join grades g on u.ID = g.UserID 
group by u.ID, u.Name 

更新:我一直試圖讓很長一段時間是在Ben的評論答案下面,我包括在這裏: 「有沒有變量,你可以隨時創建並加入標準SQL @ wcm中的其他表格,是的。有許多不同類型的對象可以創建,可以讓你做到這一點,但不完全如你所願在T-SQL中「。

+0

我明白這一點,我已多次被告知。 – wcm

+0

所以你說,即使有各種類型的數組和集合,我們沒有表變量,它們可以像表一樣使用標準SQL連接到其他表中。 – wcm

+1

沒有變量,您可以隨時創建並在標準SQL @ wcm中加入其他表,是的。有許多不同類型的對象可以創建,這些對象將允許您執行此操作,但不完全像在T-SQL中那樣。 – Ben

2

如果我理解正確,那麼如果我需要臨時存儲限於在會話中可見的數據,那麼我將使用全局臨時表。可能比在內存中存儲更多的開銷,但也有很多優勢 - 收集統計數據,對它們進行索引,以及存儲數據而不考慮內存消耗的能力。

+0

我所見過的全球臨時表的使用方式一直是長期的解決方案,而不是我尋找的臨時使用類型。另外,爲了創建這些對象,您不需要在數據庫中提升權限嗎? – wcm