4

I like to find a way to handle multiple updates to a sql db (with one singe db roundtrip). I read about table-valued parameters in SQL Server 2008 http://www.codeproject.com/KB/database/TableValueParameters.aspx which seems really useful. But it seems I need to create both a stored procedure and a table type to use it. Is that true? Perhaps due to security? I would like to run a text query simply like this:

var sql = "INSERT INTO Note (UserId, note) SELECT * FROM @myDataTable";
var myDataTable = ... some System.Data.DataTable ...
var cmd = new System.Data.SqlClient.SqlCommand(sql, conn);
var param = cmd.Parameters.Add("@myDataTable", System.Data.SqlDbType.Structured);
param.Value=myDataTable;
cmd.ExecuteNonQuery();

So

A) do I have to create both a stored procedure and a table type to use TVP's? and
B) what alternative method is recommended to send multiple updates (and inserts) to SQL Server?

3
  • A) Yes. B) Alternatives: XML, [n]varchar(size) strings + parsing. My option is TVP. Commented Sep 25, 2011 at 14:13
  • At what point is this not worth the effort to avoid a couple of trips to the db? Commented Sep 25, 2011 at 20:20
  • Jeff - I'd like to find out how much it costs (another Q?). For now it's a hunch + more importantly a practice that seems to be commonly agreed upon, from MS P&P "Round trips significantly affect performance. They are subject to network latency and to downstream server latency. Many data-driven Web sites heavily access the database for every user request. While connection pooling helps, the increased network traffic and processing load on the database server can adversely affect performance. Keep round trips to an absolute minimum." msdn.microsoft.com/en-us/library/ff647768.aspx Commented Sep 26, 2011 at 1:37

1 Answer 1

3

Yes, you need to create the types.

Alternatives are sending a big string sql batch or passing XML to sprocs.

The downside to big sql string batches is it can blow the sql proc cache and might cause sql to recompile - especially if the batch is unique because of input data being part of that large string. By definition each batch would be unique.

XML was the main alternative before TVPs. The one downside to XML, for at least awhile, sql azure didn't support it (that might change?) so it limits your options.

TVPs seem to be the way to do this. Our project just converted to using TVPs.

Hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.