SQL - CTE vs VIEW

不打扰是莪最后的温柔 提交于 2019-12-18 14:55:40

问题


My question here is what is the difference between CTE and View in SQL. I mean in which case I should use the CTE and which case the View. I know that both are some kind of virtual tables but I can't differentiate their use.

I found a similar question here but it's about performance.

Update 1:

For example: I have a database filled with trades(tbl_trade). I need to select from 3.5 millions records only the trades that was opened the current month until current time and then manipulate the data(with different queries on the virtual table - this looks like View). The problem here is that I want a SUM of 3-4 columns and then on I need to SUM some columns and create a virtual column with the result(looks like CTE).

Eg: tbl_trade has columns: profit,bonus and expenses. I need SUM(profit),SUM(bonus),SUM(expenses) and a new column total which will be equal to SUM(profit)+SUM(bonus)+SUM(expenses).

PS. Rerunning the queries for SUM is not an option since I already have the result.

Thanks in advance!


回答1:


Views can be indexed but CTE can't. So this is one important point.

CTE work excellent on tree hierarchyi.e. recursive

Also, consider views when dealing with complex queries. Views being a physical object on database (but does not store data physically) and can be used on multiple queries, thus provide flexibility and centralized approach. CTE, on the other hand are temporary and will be created when they are used; that's why they are called as inline view.

Update

According to your updated question, views will be the right choice. Dealing with 3.5 million rows in CTE will create extra overhead on TempDb which will eventually slow down SQL Server performance. Remember, CTE is a disposable view hence no statistics are stored and you can't create Indexes too. It is just like a sub query.




回答2:


Both will be interpreted exactly the same by the Plan Optimizer. It's just a different thing.

A view can be used on it's own. It can encapsulate complex statements to a more simple query.

Were a CTE is mostly used to write cleaner code with lesser redundancy in procedures/views for example. You can use a CTE for recursive queries too, which is a very great and powerful feature!

I hope this helps to clarify things.




回答3:


One of the reasons to choose CTE: If you are doing hierarchical querying, use CTEs. CTEs can be called recursively. Views cannot be called recursively.



来源:https://stackoverflow.com/questions/30918633/sql-cte-vs-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!