如何通过视图将多个select语句转换为SQL VIEW和MODIFY DATA?

时间:2018-02-24 18:42:49

标签: sql-server ssms ssms-2017

我有这些多个选择语句,我想做一个

CREATE VIEW dbo.vw_customers_addresses_services_servicetanks

这是我的SELECT语句:

SELECT * FROM Customers
     WHERE EXISTS
      (SELECT * FROM Addresses
       WHERE Addresses.OwnerId = Customers.Id
       AND Addresses.OwnerId = 97587
       AND Addresses.TenantId = 1013);


(SELECT * FROM Addresses
     WHERE Addresses.OwnerId = 97587
     AND Addresses.TenantId = 1013
     AND Addresses.Type = 'Delivery');


SELECT * FROM dbo.Services
     WHERE EXISTS
      (SELECT * FROM Addresses
       WHERE Addresses.Id = Services.AddressId
       AND Addresses.OwnerId = 97587
       AND Addresses.TenantId = 1013);

(SELECT ServiceTanks.*
     FROM ServiceTanks, Addresses, Services
      WHERE Services.Id = ServiceTanks.ServiceId
      AND Addresses.Id = Services.AddressId
      AND Addresses.OwnerId = 97587
      AND Addresses.Tenantid = 1013)

现在作为多选语句工作。 但是我的目标是通过SQL VIEW修改数据,我可以使用SSMS和EDIT TOP X ROWS的魔力从第三个选择语句快速更新AddressID RESULT。

当我将我的CREATE VIEW置于第一个选择语句之上时,它会给出一个大红色的波浪形,其中包含"不正确的语法:'创建视图'必须是批次中唯一的陈述。"

我是在做梦还是按照我的描述做到这一点?

1 个答案:

答案 0 :(得分:0)

文档...... https://docs.microsoft.com/en-us/sql/relational-databases/views/modify-data-through-a-view

有关如何通过具有许多基础选择语句(表)的视图修改数据的代码示例。

--tables
if exists (select * from sys.tables where name = 'table1')
    drop table table1
go

if exists (select * from sys.tables where name = 'table2')
    drop table table2
go

create table table1 (tkey1 int identity(1,1), fk int, name varchar(32));
create table table2 (tkey2 int identity(1,1), name varchar(32));
--data
insert into table2 (name) values ('MS')
insert into table2 (name) values ('OSS')
insert into table2 (name) values ('Oracle')
insert into table1 (fk, name) values (3, 'SQL')
insert into table1 (fk, name) values (1, 'postgreSQL')
insert into table1 (fk, name) values (2, 'mySQL')
go

if exists (select * from sys.views where name ='vw')
    drop view vw
go
create view vw
as
select t1.tkey1, t1.fk, t1.name as t1_name, t2.tkey2, t2.name as t2_name from table1 t1 inner join table2 t2 on t1.fk = t2.tkey2
go

select * from vw
go

begin tran
update vw set fk = 2 where fk = 1
update vw set fk = 1 where fk = 3
update vw set fk = 3 where fk = 2
select * from vw
rollback tran

begin tran
update vw set t2_name = 'OSS' where fk = 1
update vw set t2_name = 'MS' where fk = 3
update vw set t2_name = 'Oracle' where fk = 2
select * from vw
commit tran