我想创建一个动态更新查询,我需要在列中设置一个特定的值。但是列名需要从另一个表中选择。 我已经有以下查询:
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 *替换它们,我会得到结果。
EDIT
以下是数据类型
TableFields.Code =&gt;为nvarchar(100)
TableResRefLinks.Value =&gt; SQL_VARIANT
并且将列名为TableFields.Code的列的数据类型设置为sql_variant
答案 0 :(得分:2)
使用纯SQL无法解决此问题。您需要某种脚本来构建语句。例如,postgresql有一个名为“pgpsql”的脚本语言,它允许构建动态SQL语句。但这显然取决于底层的RDBMS。
顺便说一下:当你进行简单的子选择时,这适用于SELECT。