This question asked by interviewer. Why must Table-Valued Parameters be READONLY. Let’s see why it is read only. Table-Valued Parameters are mandatory READONLY because SQL Server passes them as immutable, streaming row sets optimized for concurrency, plan stability, and minimal logging. Allowing writes would break pipelining, require locking and logging, and invalidate execution plan assumptions. If modification is required, the TVP must be copied into a temp table.
When you pass a TVP as below
DECLARE @MyTVP MyTableType;
Then SQL Server Materializes it
in memory (or tempdb if large) and treats it like a structured input stream and
shares it safely across execution contexts. It is NOT a normal table variable.
TVPs are passed as a serialized
row set stream. SQL Server can pipeline rows into execution plan
to avoid locking and avoid logging. If writes were allowed then it breaks streaming
and would require full materialization locking.
Concurrency safety: Multiple
threads may read TVP simultaneously. If we allowing writes than it would cause
the Race conditions and Latches/locks.
Let’s see the demo
Creating table type
|
CREATE TYPE dbo.OrderType AS TABLE ( OrderID INT, Amount DECIMAL(10,2) ); |
Now creating SP to consume this
TT.
|
CREATE PROCEDURE dbo.usp_TestTVP @Orders dbo.OrderType
READONLY AS BEGIN SELECT * FROM @Orders; END; |
SP created successfully.
Let’s try to remove READONLY and then creating the SP.
|
CREATE PROCEDURE dbo.usp_TestTVP_RemRO @Orders dbo.OrderType AS BEGIN SELECT * FROM @Orders; END; |
Getting an error.
SQL Server enforces it.
Let’s try to insert/update the TT
inside the SP.
|
CREATE PROCEDURE dbo.usp_TestTVP_insert @Orders dbo.OrderType
READONLY AS BEGIN INSERT INTO @Orders VALUES (3, 100); SELECT * FROM @Orders; END; |
Getting an error.
When we need to update the data
of Table type first, we need to create temp table or variable table and store
TT data into it and the update temp table or variable table.
No comments:
Post a Comment
If you have any doubt, please let me know.