使用先前查询的结果查询数据库并将它们组合

时间:2017-02-19 22:25:05

标签: sql sql-server

我正在使用动态sql来查询数据库:

    DECLARE @VALUE VARCHAR(5000);
    SET @VALUE = '123'
    DECLARE @SQL5 NVARCHAR(MAX) = 'Select distinct item_id, attr_val from [dbo].[CONTRACT_ATTR] WHERE [ATTR_VAL]  LIKE ''%@VALUE%'' AND [FIELD_ID] = 413 ORDER BY [attr_val]';
    SET @SQL5 = replace(@SQL5, '@VALUE', @VALUE);
    EXEC SP_executesql @SQL5;

结果如下:

enter image description here

我正在尝试获取结果(item_id)并运行另一个选择查询。像这样:

UNION
Select Column3 From @SQL5 where other_column = 1234

对于返回的每一行,结果将是3列,在第二次选择中找到2个原始列和新列。

我做错了什么以及如何解决?

2 个答案:

答案 0 :(得分:1)

以下是没有动态SQL的答案:

DECLARE @VALUE VARCHAR(100)

SET @VALUE = '123'

SELECT myuser.item_id,
       myuser.attr_val,
       parent.attr_val
FROM [dbo].[CONTRACT_ATTR] AS myuser
JOIN [dbo].[CONTRACT_ATTR] AS parent 
  ON parent.item_id = myuser.item_id 
  AND myuser.item_id = parent.item_id 
WHERE myuser.field_id = 239 
and parent.[ATTR_VAL]  LIKE '%' + @VALUE + '%'

我还将连接条件完全移入on子句。

答案 1 :(得分:0)

我明白了:

SELECT myuser.item_id,
       myuser.attr_val,
       parent.attr_val
FROM [dbo].[CONTRACT_ATTR] AS myuser
JOIN [dbo].[CONTRACT_ATTR] AS parent 
  ON parent.item_id = myuser.item_id 
WHERE myuser.item_id = parent.item_id and myuser.field_id = 239 and parent.[ATTR_VAL]  LIKE '%123%'

集成动态sql:

    DECLARE @SQL5 NVARCHAR(MAX) = 'SELECT myuser.item_id, myuser.attr_val, parent.attr_val FROM [dbo].[CONTRACT_ATTR] AS myuser JOIN [dbo].[CONTRACT_ATTR] AS parent ON parent.item_id = myuser.item_id WHERE myuser.item_id = parent.item_id and myuser.field_id = 239 and parent.[ATTR_VAL]  LIKE ''%@VALUE%''';
    SET @SQL5 = replace(@SQL5, '@VALUE', @VALUE);
    EXEC SP_executesql @SQL5;