I have a scenario where I combine two tables into one (using UNION) and also JOIN data from some other tables.
I can do this either with a VIEW or a UDF/User Defined Function.
Considering that I have no view so far at all in my database, but quite a few UDF's for fulltext search and the like, I'm tempted to use a UDF for this scenario as well to keep it "clean".
However, this is ent开发者_如何学Cirely subjective and I wondered if there is a better objective reason to go for either a VIEW or a UDF in this scenario.
I did compare query plans for both and they are the exact same so I don't believe there is a performance penalty or advantage for using either one.
Is there other reason to choose one over the other or does it not matter?
I would always use features in order of sophistication. A view is relatively straightforward in terms of performance profile and security management. I would probably use it first.
I'm assuming you are talking about an inline table-valued UDF, which will pretty much have identical performance characteristics. Security on a UDF is a little different and you cannot have instead of triggers to be able to do "inserts" on the view. A benefit of the UDF would be that you can force parameters to be supplied, thereby ensuring usage patterns are as expected, whereas a view can be queried without any criteria (perhaps accidentally).
If you did end up wanting to have a UDF for parameterization, you could layer it on top of the view (so no code duplication) and you should find that the performance is not affected significantly, because the optimizer can combine views and inline TVF fairly successfully.
One advantage i see by using this scenario as view is to index them and use them as "indexed views" where unlike a traditional view there is physical file that is created and therefore querying is faster where there are considerable amount of rows in it. The very effect of using this is to bypass the joins and unions for all the rows instead only build them for new rows.
As our friend Cade suggested, you cud use a view inside a UDF to keep it clean and it isn't a lot different.
Hope this helps !
精彩评论