How to get the data type of a return value in SQL Server

sql server data type of return value featured image
Reading Time: 3 minutes

Sometimes when writing T-SQL code (or code in any other language), it can be useful to know the data type of a value returned from an object. I was working on a tutorial recently where I wanted to show you the data type that was returned by an operation, but I didn’t know how to do it.



I got on the ol’ Google machine and did a bit of digging. Eventually, I found the answer:

Use the SQL_VARIANT_PROPERTY system function

As an example, maybe we want to know the data type of the value returned by the GETDATE() system function.

We can use the SQL_VARIANT_PROPERTY function to get it. It takes two parameters:

  1. The expression for which you want the data type of the resulting value.
  2. The Property Name, which in this case will simply be the word ‘BaseType’.

I suppose this system function is a Scalar function, which means we can simply call it in a SELECT list:

sql server data type of return value sql_variant_property

That was easy!

What about the data type of a value returned by one of our own user defined functions?

Take a look at these two tables, Products and Orders:

sql server data type of return value products and orders table

I have a handy function called getProdSum that returns how much fresh cash we have made from a specific product whose ID we pass to the function. For example, here is how much money we have made from our Coffee Table product (which is Product # 24):

sql server data type of return value calling function

If we want to know the data type of this value, we can basically plug in that same call to our SQL_VARIANT_PROPERTY function:

sql server data type of return value decimal

Very cool stuff.

These are very simple examples, but I hope they help you in your quest to understand the T-SQL language!



Next Steps:

Leave a comment if you found this tutorial helpful! If there is a different/better way to derive the data type of a return value, I’d love to hear it. Leave a comment.

Need to know the most common data types in SQL Server? I got you:

FREE EBook on SQL Server Data Types!

Do you know the answer to these other SQL questions?



Thank you very much for reading!

Make sure you subscribe to my newsletter to receive special offers and notifications anytime a new tutorial is released!

I hope you found this tutorial helpful. If you have any questions, leave a comment. Or better yet, send me an email!

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *