作者TeemingVoid (TeemingVoid)
标题Re: [SQL ] SQL Server 2005 新增所相依的物件
时间Mon Jan 20 00:24:07 2014
※ 引述《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
1F:推 terranhardy:非常谢谢你的详细说明,学到很多,也解决我的问题了。 01/20 01:40