在SQL查询中使用第二个select语句

时间:2019-03-22 17:27:54

标签: sql-server stored-procedures

我正在尝试在SQL查询中使用第二条Select语句,但是我的应用程序中的表未显示第二条选择语句中的值TAGS_DELIMITED。我收到“在所选数据源上找不到名称为'TAGS_DELIMITED'的字段或属性”。当单独执行第二个选择语句时,第二个选择语句可以很好地工作,而第一个选择语句也可以,但是当它们像下面这样一起工作时,则不起作用。

数据如下:

ORDERS:
ORDER_ID    FIRST_NAME  Active
300         Barney      Y

TAGS:
TAG_ID  TAGS
1       ORANGES
2       APPLES

TaggedOrders
ORDER_ID    TAG_ID
300         1
300         2

The final results of the table should display:
Order ID    First Name  Tags
1           Barney      ORANGES,APPLES

搜索词“巴尼”

和SQL存储过程:

        @Keyword varchar (200)
        ,@IsActive varchar(10)
AS
BEGIN
SELECT DISTINCT ORDERS.ORDER_ID AS [ORDER_ID], First_Name AS [First_Name]           

        FROM ORDERS     

    LEFT JOIN TaggedOrders
    ON ORDERS.ORDER_ID = TaggedOrders.ORDER_ID
    LEFT JOIN Tags
    ON TAGS.TAG_ID = TaggedOrders.TAG_ID
    WHERE ORDERS.First_Name LIKE '%'+@Keyword+'%' and Orders.Active = @IsActive

SELECT STUFF((
       SELECT ','+Tags.TAGS
       FROM Tags
       left join TaggedOrders
       on TaggedOrders.TAG_ID = tags.TAG_ID
       left join ORDERS
       ON TaggedOrders.ORDER_ID = ORDERS.ORDER_ID
       where Orders.First_Name = @Keyword
       FOR XML PATH('')
),1,1, '') AS [TAGS_DELIMITED]  

END

1 个答案:

答案 0 :(得分:1)

谢谢@Thermos的建议。这有效:

        @Keyword varchar (200)
        ,@IsActive varchar(10)
AS
BEGIN
SELECT DISTINCT ORDERS.ORDER_ID AS [ORDER_ID], First_Name AS [First_Name],
STUFF((
       SELECT ','+Tags.TAGS
       FROM Tags
       left join TaggedOrders
       on TaggedOrders.TAG_ID = tags.TAG_ID
       left join ORDERS
       ON TaggedOrders.ORDER_ID = ORDERS.ORDER_ID
       where Orders.First_Name = @Keyword
       FOR XML PATH('')
),1,1, '') AS [TAGS_DELIMITED]           

        FROM ORDERS     

    LEFT JOIN TaggedOrders
    ON ORDERS.ORDER_ID = TaggedOrders.ORDER_ID
    LEFT JOIN Tags
    ON TAGS.TAG_ID = TaggedOrders.TAG_ID
    WHERE ORDERS.First_Name LIKE '%'+@Keyword+'%' and Orders.Active = @IsActive  

END