2

可以说我有这个:

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

返回Ref_ID值 50

现在我想在另一个返回任意数量行的 select 语句中使用该值。看起来像这样

TSQL B:

Select UserID from TableB where FK_RefID = @passRefID

所以可以说它返回:

UserID
34
56
87

现在我想TableC根据UserID之前的返回创建一个更新。

我的TableC记录布局如下所示:

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

我知道我可以使用:

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

但我的问题是,在TSQL B中,返回的那些行可能会有所不同。可能返回 1 行或 100 行,并且TableC的构造与标准略有不同。

如何UPDATE根据使用唯一 USERID 返回的行数以及 TableC 使用 PropertyDefinitionID 的方式创建动态语句?

感谢你的协助。

4

1 回答 1

1
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 )
于 2011-08-17T22:08:55.770 回答