Re: [SQL ] SQL Server 2005 新增所相依的物件

看板Database作者 (TeemingVoid)時間12年前 (2014/01/20 00:24), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串4/4 (看更多)
※ 引述《terranhardy (cO.Zy)》之銘言: : 先謝謝你的回應,學到很多,試了一下後還有些問題, : 1. 有辦法直接增加新的Table進去view就好,一定要全部Table都再加一次是嗎? 是的,要全部寫一遍。(所幸有複製貼上功能 :p) : 2. 假設view裡面資料行有十個欄位,與Table的資料行的名稱不一致, : 造成在加時會出現Invalid column name錯誤訊息,這要怎麼解決呢? 基本上,以 union 連接的 select 敘述,只要各 select 引用的欄位數量 相等而且資料型態相同即可,欄位名稱並沒有規定要一樣。至於實際傳回 用戶端的結果集的欄位名稱,以第一個 select 敘述的欄位名稱為準,如 果是檢視表,也可以在 create view 時,自訂新的欄位名稱。 (實際寫法,請參考文後附上的例子。) : 3. 我每個Table的資料行欄位數量都不一樣,但總集合起來是view裡面的十個欄位, : view的某欄若Table A沒有的則會顯示Null,不曉得要如何做到這一點。 湊數的欄位,就代 NULL 值即可,稍後的例子,我會加上這種寫法。 : 4. 若只增加每個Table有在View裡的欄位,則會顯示 : All the queries in a query expression containing a UNION operator : must have the same number of expressions in their select lists : 錯誤訊息。 : 所以看來應該要新增相同數量的欄位,但又會造成第二點的錯誤。 你說的沒錯,詳情也請參閱第二點的說明以及下列例子: -- 舉例來說,假設你有以下兩個資料表,table1 以及 table2, -- 兩個 table 的欄位名稱與數量不盡相同: use lab go create table table1 ( id int primary key, data1 int, data2 int, data3 int ) go insert into table1 values (1, 111, 121, 131) insert into table1 values (2, 112, 122, 132) insert into table1 values (3, 113, 123, 133) go create table table2 ( id int primary key, dat1 int, dat3 int ) go insert into table2 values (21, 211, 231) insert into table2 values (22, 212, 232) insert into table2 values (23, 213, 233) go -- 建立檢視表 -- 傳回 Client 端的欄位名稱以第一個 select 的欄位為準 -- table2 少一個欄位,用 NULL 代入 create view TestView as select id, data1, data2, data3 from table1 union select id, dat1, NULL, dat3 from table2 go select * from TestView go drop view TestView go -- 或者,在定義檢視表時,寫明結果集的欄位名稱 -- 例如下例的 (id, d1, d2, d3) create view TestView (id, d1, d2, d3) as select id, data1, data2, data3 from table1 union select id, dat1, null, dat3 from table2 go select * from TestView go -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.252.127.12

01/20 01:40, , 1F
非常謝謝你的詳細說明,學到很多,也解決我的問題了。
01/20 01:40, 1F
文章代碼(AID): #1Is_mg7p (Database)
討論串 (同標題文章)
文章代碼(AID): #1Is_mg7p (Database)