![]() |
Database »
Database »
SQL Server
Intermediate
License: The Code Project Open License (CPOL)
Table Value Parameter in SQL Server 2008By Robin_RoyMS SQL Server 2008 new feature, Table Value Parameter. |
SQL, SQL Server (SQL 2008), DBA, Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
One of the fantastic new features of SQL Server 2008 is the Table value parameter. In previous versions of SQL Server, there wasn’t a native way to pass a table to a Stored Procedure or functions. The usual workaround was to pass a large varchar or the XML type and parse through it. Now, in SQL Server 2008, Table parameters are available.
Many a times, we need to utilize a single Stored Procedure to update multiple database tables with one-to-many relationships. In such occasions, we end up concatenating large strings, and inside the procedure, end up parsing the string to get records. With SQL Server 2008, it is very simple, and we no more need to write tons of lines of code to implement such requirements.
Here are a few facts that you must know before starting to use the Table Value Parameter:
CREATE TYPE dbo.OrderIDs AS TABLE
(
pos INT NOT NULL PRIMARY KEY,
orderid INT NOT NULL UNIQUE
)
DECLARE @T AS dbo.OrderIDs;
INSERT INTO @T(pos, orderid) VALUES(1, 10248)
INSERT INTO @T(pos, orderid) VALUES(2, 10250)
INSERT INTO @T(pos, orderid) VALUES(3, 10249);
SELECT * FROM @T;
In the above code snippet, we create a Table User Defined Type. In SQL Server 2008, we can define Table UDTs (this is a new feature in SQL Server 2008). Then, create a variable using the newly created UDT and insert a few records into the variable and query the same.
CREATE PROC dbo.sp_GetOrders
(@T AS dbo.tbl_Order READONLY)
AS
SELECT O.OrderID, O.OrderDate, O.CustomerID
FROM dbo.tbl_Order AS O JOIN @T AS T ON
O.OrderID = T. OrderID
ORDER BY T. RecordID;
GO
DECLARE @MyOrderIDs AS dbo.tbl_Order;
INSERT INTO @MyOrderIDs(pos, orderid) VALUES(1, 10248)
INSERT INTO @MyOrderIDs(pos, orderid) VALUES(2, 10250)
INSERT INTO @MyOrderIDs(pos, orderid) VALUES(3, 10249);
EXEC dbo.sp_GetOrders @T = @MyOrderIDs;
The above code snippet shows how to use the Table UDT as a parameter in SQL Stored Procedure.
So now, with the Table UDT and the ability to pass the table value parameter to Stored Procedures and functions, we need lesser code and also get performance benefits.
Hope you enjoyed this article. Happy programming!!!
| You must Sign In to use this message board. | |||||||||||||||
|
|||||||||||||||
|
|||||||||||||||
|
|||||||||||||||
|
|||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 10 Jun 2009 Editor: Smitha Vijayan |
Copyright 2009 by Robin_Roy Everything else Copyright © CodeProject, 1999-2009 Web22 | Advertise on the Code Project |