Posts

Showing posts with the label SQL HierarchyId Table-Valued Function Sort

Sorting the results of a MS SQL table-valued function

For whatever reason, MS SQL table-valued functions don't get the respect they deserve. Linq to entities pretends that they don't exist at all. I mean, seriously, how hard would it be to allow you to import them in the same way that you can import stored procedures? Anyway, as a mechanism for abstracting your database schema, I like them. They are pre-compiled, strongly typed, and results cached, so they can get very fast. One thing they don't do well is return sorted values. The following code won't work well when contained in a table-valued function: SELECT * FROM Table1 ORDER BY Column1 This requires us to resort to doing something like this: SELECT TOP 100 PERCENT * FROM Table1 ORDER BY Column1 And even that result can be ignored sometimes. Consider a table that consists of a key, HierarchyId , and a description. We want to unwind the hierarchyId so that we have key, parent key, and description. This is necessary if we are working with the hierarchy outside of...