During my presentation on Sql Saturday #40 event I mentioned that one of the biggest improvements in SQL Server 2008 from development standpoint is table-valued parameters support (TVP). It’s not only simplifying development – think about passing temporary table variable as parameter from within t-sql code as well as from the client applications. It also gives great performance improvement especially if you need to save large data packet. Think about data processing tasks where client application loads large record set, processes it and saves it back in one transaction.
Let’s do some tests. Let’s create the table:
First, let’s use classical approach – use SqlCommand and insert records in the loop
Now let’s use TVP. First of all we need to create a type:
Next step is creating stored procedure which we will use to insert new records
Next, let’s modify the code to use TVP and stored procedure
It worth to mention that client code needs to create and populate DataTable object to assign it to the parameter. Obviously it requires some time, on other hand, this is client code – transaction has not been started yet.
Finally, let’s run a few tests:
For the package of 5000 records, avg execution time of the classical method on my laptop is in around 2,600-2,700 milliseconds. TVP approach takes only about 180 milliseconds where 60 milliseconds is DataTable creation. So actual transaction time takes in around 130 milliseconds only – in about 20 times faster than classical method.
For the package of 50,000 records, avg execution times respectively are 20,500 ms and 1,300 ms with 300 ms as DataTable creation.
As you can see, it’s not only the speed, the transaction duration is about 20 times shorter. Huge difference.
Obviously, if you’re on SQL Server 2005, TVP is not an option. Although there are a couple methods which could help you to improve the classical method. I will show it to you in a few days.