-1

我想创建一个动态更新查询,我需要在列中设置某个值。但是需要从另一个表中选择列名。我已经有以下查询:

UPDATE core.TableRes
SET (
    SELECT Code FROM core.TableFields 
    INNER JOIN core.TableXTableFields ON TableXTableFields.FieldID = TableFields.FieldID 
    INNER JOIN core.TableResRefLinks ON TableResRefLinks.ExtraFieldID = TableXTableFields.ExtraFieldID 
    WHERE TableResRefLinks.TableResRefLinksID = RefLinks.TableResRefLinksID)
= (
    SELECT Value FROM core.TableResRefLinks WHERE TableResRefLinksID = RefLinks.TableResRefLinksID)
FROM core.TableRes
    INNER JOIN core.TableResRefLinks RefLinks ON RefLinks.ResourceID = TableRes.ResourceID
    INNER JOIN core.TableXTableFields ON TableXTableFields.ExtraFieldID = RefLinks.ExtraFieldID
    INNER JOIN core.TableFields ON TableFields.FieldID = TableXTableFields.FieldID
    WHERE (EndDate IS NULL OR EndDate > GETDATE()) AND
    (
        SELECT Code FROM core.TableFields 
        INNER JOIN core.TableXTableFields ON TableXTableFields.FieldID = TableFields.FieldID 
        INNER JOIN core.TableResRefLinks ON TableResRefLinks.ExtraFieldID = TableXTableFields.ExtraFieldID 
        WHERE TableResRefLinks.TableResRefLinksID = RefLinks.TableResRefLinksID) 
    <>
    (
        SELECT Value FROM core.TableResRefLinks 
        WHERE TableResRefLinksID = RefLinks.TableResRefLinksID)

它给了我以下错误:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '('.
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '='.
Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'FROM'.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near '<'.

有没有办法解决这个问题?如果我更改完整的 UPDATE 和 SET 语句并用 SELECT * 替换它们,我会得到结果。

编辑
这里是数据类型TableFields.Code
=> nvarchar(100)
TableResRefLinks.Value => sql_variant
并且列名 TableFields.Code 的列的数据类型设置为 sql_variant

4

1 回答 1

2

您无法使用纯 SQL 解决此问题。您需要某种脚本来构建您的语句。例如,postgresql 有一种称为“pgpsql”的脚本语言,它允许构建动态 SQL 语句。但这显然取决于底层的 RDBMS。

顺便说一句:这适用于 SELECT,因为您正在执行简单的子选择。

于 2012-05-24T14:33:20.440 回答