【问题标题】:Update multiple rows based on multiple values根据多个值更新多行
【发布时间】:2011-08-17 21:59:54
【问题描述】:

假设我有这个:

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

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

我的 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 的构造与标准略有不同。

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

感谢您的帮助。

【问题讨论】:

    标签: tsql sql-update multiple-records


    【解决方案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 )
    

    【讨论】:

    • 好吧...我刚刚发现这行不通,因为我的 TableC 是如何实际填充和创建的。我将编辑我的初始帖子。我很感激你的回复。我希望您能再次提供帮助或谁能提供帮助。
    • 成功了!杰出的!我知道需要对其进行更多调整以添加更多变量,但希望我能弄清楚。再次感谢您帮助我。这个查询对我来说是一个不同的动物,但我很欣赏你所做的。
    猜你喜欢
    • 2013-07-13
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    相关资源
    最近更新 更多