Lets say I have this:
Declare @passRefID as int
Declare @passTextA as varchar
Deckare @oassTextB as varchar
Declare @passPropertyA as int
Declare @passPropertyB as int
Set @oassTextA = 'Joe'
Set @passTextB = 'Smith'
Set @passPropertyA = 21
Set @passPropertyB = 23
TSQL A:
Set @passRefID = Select Ref_ID from TableA where ID = 10
The Ref_ID
returns a value of 50
Now I want to use that value in another select statement which returns any amount of rows. It looks like this
TSQL B:
Select UserID from TableB where FK_RefID = @passRefID
So lets say it returns:
UserID
34
56
87
Now I want to create an update for TableC
based on the UserID
that return previously.
My TableC layout of records look like this:
ID, UserID, PropertyDefinitionID, PropertyValue
265, 34, 21, Bob
266, 34, 23, Barker
271, 34, 55, bb@abc.com
628, 56, 21, Jane
629, 56, 23, Adams
635, 56, 55, ja@abc.com
901, 83, 21, Tom
905, 83, 23, Thumb
910, 83, 55, tt@abc.com
I know I can use:
Update TableC Set PropertyValue = @oassTextA Where UserID = 34 and PropertyDefinitionID = @passPropertyA
Update TableC Set PropertyValue = @oassTextB Where UserID = 34 and PropertyDefinitionID = @passPropertyB
Update TableC Set PropertyValue = @oassTextA Where UserID = 56 and PropertyDefinitionID = @passPropertyA
Update TableC Set PropertyValue = @oassTextB Where UserID = 56 and PropertyDefinitionID = @passPropertyB
Update TableC Set PropertyValue = @oassTextA Where UserID = 83 and PropertyDefinitionID = @passPropertyA
Update TableC Set PropertyValue = @oassTextB Where UserID = 83 and PropertyDefinitionID = @passPropertyB
But my problem is that in TSQL B, those rows returned could differ. There could be 1 row or 100 rows returned and the TableC is constructed a bit different from the norm.
How can I create a dynamic UPDATE
statement based on the amount of rows return using the unique USERIDs and the way the TableC uses the PropertyDefinitionID?
Thanks for your assistance.
UPDATE TableC
SET PropertyValue = CASE WHEN PropertyDefinitionID = @passPropertyA
THEN @oassTextA
ELSE @oassTextB
END
WHERE PropertyDefinitionID IN ( @passPropertyA, @passPropertyB )
AND UserID IN (
SELECT B.UserID
FROM TableB AS B
INNER JOIN TableA AS A ON A.Ref_ID = B.FK_RefID
WHERE A.Id = 10 )