In a SQL Server stored procedure, can I use two separate columns from a table-valued parameter (TVP) in both the CASE
and WHERE
clauses?
In my TVP, I have two columns like so:
CREATE TYPE tt_Index AS TABLE
(
referenceType varchar(20),
referenceID varchar(20)
)
In the stored procedure, how can I iterate over the table parameter and use referenceType
within a CASE
, and referenceID
within a WHERE
clause?
Something like this:
CREATE PROCEDURE usp.Test
@parIndexTable tt_Index READONLY
AS
SELECT
CASE (@parIndexTable.referenceType)
WHEN 'ref1' THEN (SELECT * FROM NamesCurrent nc
WHERE @parIndexTable.referenceID = nc.referenceID)
WHEN 'ref2' THEN (UPDATE NamesCurrent nc
SET nc.Name = 'Craig'
WHERE @parIndexTable.referenceID = nc.referenceID)
END
From what I've understood, I need to iterate over the TVP as a table but just unsure of the syntax for that and how it fits in with the case statement so I can use both parameters.
1条答案
按热度按时间oug3syen1#
I must admit, the logic you have seems odd here, as you have a
SELECT
and anUPDATE
and you want toSELECT
from thatUPDATE
(?). As you want both aSELECT
and anUPDATE
on different thing, you need to statements here; one for theSELECT
which doesn'tUPDATE
anything and another for theUPDATE
, which assume also needs anOUTPUT
clause.To use the TVP, you just need to use a
JOIN
and you can filter the rows in theSELECT
/UPDATE
in theWHERE
.This results in the following statements: