Every version of SQL Server brings in something new that challenges our understanding of how the software product works. For me, working with SQL Server is quite refreshing and fulfilling because every single day there is something about the product that I discover and learn. There are tons of professionals who are working on this product and they push the limits of use and bring interesting use cases which I get to learn. Let us learn about Row Constructor.
This journey of SQL Server on this blog is just my way to express all these learnings and get them documented. In a recent code review for one of my consulting assignment, I saw a code and was completely taken aback at how it even ran for such a long time.
I had to go ahead and do my homework to see how this was actually written by the developer. Assume you wanted to have some code that gave you a common value with something other value as a CROSS JOIN. The final output was looking like:
As you can see the “Kilo”, “Mega” “Giga” are repeated for Byte and Meter values. This can be done in a number of ways, but the code I wrote to get this is using the row-constructor feature of SQL Server.
SELECT [MetricsPre].[Pre] + [Measuring].[Unit] AS [Measuringment], [MetricsPre].[Multiplier], UPPER([Measuring].[Unit]) FROM (VALUES ('kilo', '10^3'), ('mega', '10^6'), ('giga', '10^9'), ('tera', '10^12')) AS [MetricsPre] ( [Pre], [Multiplier] ), (VALUES ('byte'), ('meter')) AS [Measuring] ( [Unit] ) GO
I know it is pretty unconventional, but it still does the job for us.
Test your TSQL Skills:
- Is there any other way one can achieve the same result using SQL Server in a single query? Do let me know via comments below. I know CTE is one of the other ways too. So try something else now.
- Is there any other implementation of row-constructor that you have used in your environment that you want to share with the blog readers? Do let me know via comments.
I look forward for some interesting implementations for you, and it is going to be a learning that I will cherish and look forward to.
Reference: Pinal Dave (http://blog.sqlauthority.com)
First appeared on SQL SERVER – Understanding How to Play With Row Constructor