SQL Server CREATE VIEW必须是批处理中的唯一语句

s6fujrry  于 2022-12-17  发布在  其他
关注(0)|答案(4)|浏览(239)

我试着提出一个观点。到目前为止,我写了这个:

with ExpAndCheapMedicine(MostMoney, MinMoney) as
(
    select max(unitprice), min(unitprice)
    from Medicine
)
,
findmostexpensive(nameOfExpensive) as
(
    select tradename
    from Medicine, ExpAndCheapMedicine
    where UnitPrice = MostMoney
)
,
findCheapest(nameOfCheapest) as
(
    select tradename
    from Medicine, ExpAndCheapMedicine
    where UnitPrice = MinMoney
)

CREATE VIEW showing
as
select tradename, unitprice, GenericFlag
from Medicine;

不幸的是,我在包含CREATE VIEW showing的行上得到一个错误
“CREATE VIEW必须是批处理中的唯一语句”
我该怎么补救?!

uyhoqukh

uyhoqukh1#

正如错误所述,CREATE VIEW语句需要是查询批处理中的唯一语句。
在此方案中,您有两个选项,具体取决于您要实现的功能:
1.将CREATE VIEW查询放在开头

CREATE VIEW showing
as
select tradename, unitprice, GenericFlag
from Medicine;

with ExpAndCheapMedicine(MostMoney, MinMoney) as
(
    select max(unitprice), min(unitprice)
    from Medicine
)
,
findmostexpensive(nameOfExpensive) as
(
    select tradename
    from Medicine, ExpAndCheapMedicine
    where UnitPrice = MostMoney
)
,
findCheapest(nameOfCheapest) as
(
    select tradename
    from Medicine, ExpAndCheapMedicine
        where UnitPrice = MinMoney
    )

1.在CTE之后和CREATE VIEW查询之前使用GO
--选项2

with ExpAndCheapMedicine(MostMoney, MinMoney) as
(
    select max(unitprice), min(unitprice)
    from Medicine
)
,
findmostexpensive(nameOfExpensive) as
(
    select tradename
    from Medicine, ExpAndCheapMedicine
    where UnitPrice = MostMoney
)
,
findCheapest(nameOfCheapest) as
(
    select tradename
    from Medicine, ExpAndCheapMedicine
    where UnitPrice = MinMoney
)

GO    

CREATE VIEW showing
as
select tradename, unitprice, GenericFlag
from Medicine;
9njqaruj

9njqaruj2#

当我试图在同一条语句中创建几个视图时,我遇到了这个问题,对我来说,使用动态SQL效果很好。

EXEC('CREATE VIEW V1 as SELECT * FROM [T1];');
    EXEC('CREATE VIEW V2 as SELECT * FROM [T2];');
owfi6suc

owfi6suc3#

您还可以用途:

CREATE VIEW vw_test1 AS SELECT [Name] FROM dbo.test1;
GO
CREATE VIEW vw_test2 AS SELECT [Name] FROM dbo.test2;
GO

--If you need to grant some rights, just use :
GRANT SELECT ON vw_test....

很容易理解和避免动态SQL(即使动态SQL也能工作)

blpfk2vs

blpfk2vs4#

只需在创建视图之前和之后使用GO即可解决问题

GO
Create view Vaccinated as
select 
      location,
      population,
      vaccination
from Covid
GO

相关问题