简体   繁体   English

可以通过使用 order by 子句使用视图插入数据吗?

[英]It is possible to insert data using views by using order by clause?

During my interview for the position of SQL Developer the interviewer asked me one question在我采访 SQL Developer 的 position 时,面试官问了我一个问题

It is possible to insert data using views including order by clause?是否可以使用包含 order by 子句的视图插入数据?

I answered to the interviewer "No it is not possible".我对面试官的回答是“不,不可能”。 But she told that it is possible.但她说这是可能的。 I searched through internet but I couldn't get the solution.我通过互联网搜索,但我无法得到解决方案。

So, kindly give me the solution.所以,请给我解决方案。

You can not create the view with order by (unless some limit clause is used) but you can use the order by when selecting from view and insert into table using the insert into.. select.. order by..您不能使用order by创建视图(除非使用了一些限制子句),但您可以在从视图中选择时使用order by并使用insert into.. select.. order by..

insert into test(t_col)
select vw_col from vw order by vw_col

Db<>fiddle example Db<>小提琴示例

If you are phrasing the question correctly, I would say you are correct for the following reasons:如果您正确地表达了这个问题,我会说您是正确的,原因如下:

  1. Views do only allow order by clauses except with very limited exceptions.视图只允许order by子句,除了非常有限的例外。
  2. Views can be arbitrary queries, and hence most views are not "insertable" (the real term is updatable ).视图可以是任意查询,因此大多数视图不是“可插入的”(真正的术语是可更新的)。

There are specific exceptions to each of these.这些都有特定的例外。 For instance, you can use select top 100 percent in a view that has a query with an order by .例如,您可以在具有order by查询的视图中使用select top 100 percent However, that doesn't mean that the view is "ordered".但是,这并不意味着视图是“有序的”。 Simply that the top 100% of rows based on the order by are returned.只需返回基于order by的前 100% 行。

Similarly, there are some views that are insertable.同样,有些视图是可插入的。 In general, though, you would need to write an insert trigger on a view to insert into it.不过,一般来说,您需要在视图上编写一个insert触发器才能插入其中。

Hmmm.嗯。 . . . . I guess the answer might be "yes", but only under very limited and specific circumstances.我想答案可能是“是”,但仅限于非常有限和特定的情况下。 Here is an example where it actually works. 是一个实际工作的例子。 But to be honest, I think "no" illustrates better knowledge of SQL Server unless you are answering an essay question.但老实说,我认为“否”说明了对 SQL 服务器的更好了解,除非您回答的是论文问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM