使用局部变量在sql中设置表字段

gfttwv5a  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(267)

我试图用源表中的值更新目标表中的不同字段。更新可能针对不同的表列,我希望动态设置。
似乎我不能使用“dest.[@fieldname]”来动态设置值。我有办法做到这一点吗?

DECLARE @FieldName VARCHAR(50) = ''

SET @FieldName = 
   CASE
       WHEN @FieldCode = 0 THEN 'type'
       WHEN @FieldCode = 1 THEN 'name'
       WHEN @FieldCode = 2 THEN 'age'
   END

MERGE INTO DestTable dest
USING #tempTable src 
    ON dest.record_id = src.record_id
        WHEN MATCHED
            THEN UPDATE SET
              ***dest.[@FieldName]***= src.value END;
dwbf0jvd

dwbf0jvd1#

您始终可以使用动态查询。在这种情况下,还可以按条件更新所有字段:

MERGE INTO DestTable dest
USING #tempTable src 
ON dest.record_id = src.record_id
    WHEN MATCHED
        THEN UPDATE SET type = IIF(@FieldCode = 0, src.value, type),
                        name = IIF(@FieldCode = 1, src.value, name),
                        age = IIF(@FieldCode = 2, src.value, age)

您还可以使用动态查询:

DECLARE @Statement NVARCHAR(MAX) = N'MERGE INTO DestTable dest
USING #tempTable src 
ON dest.record_id = src.record_id
    WHEN MATCHED
        THEN UPDATE SET ' + IIF(@FieldCode = 0, 'type', IIF(@FieldCode = 1, 'name', 'age')) + ' = src.value'
EXEC(@Statement)
iih3973s

iih3973s2#

您可以通过if-else逻辑进行静态查询。

IF @FieldCode = 0
BEGIN
UPDATE dest 
SET
type = src.value
FROM DestTable dest
INNER JOIN #tempTable src 
    ON dest.record_id = src.record_id
END 
ELSE IF @FieldCode = 1
BEGIN
UPDATE dest 
SET
name = src.value
FROM DestTable dest
INNER JOIN #tempTable src 
    ON dest.record_id = src.record_id
END
ELSE IF @FieldCode = 2
BEGIN
UPDATE dest 
SET
age = src.value
FROM DestTable dest
INNER JOIN #tempTable src 
    ON dest.record_id = src.record_id

end

或者可以有一个update语句。基于 @fieldcode ,您正在更新src.value,如果不同的字段代码,那么您将使用相同的值进行更新。

UPDATE dest 
SET
type = CASE WHEN @FieldCode = 0 THEN src.value ELSE dest.type END,
name = CASE WHEN @FieldCode = 1 THEN src.value ELSE dest.name END,
age = CASE WHEN @FieldCode = 2 THEN src.value ELSE dest.age END
FROM DestTable dest
INNER JOIN  #tempTable src 
    ON dest.record_id = src.record_id

相关问题