子查询使用XML强制转换返回了多个值

时间:2018-06-08 14:20:10

标签: sql xml select declare

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

CREATE PROCEDURE list_select (@id INT)

AS

IF (@id IS NOT NULL)
BEGIN
    DECLARE @xml XML = CAST((SELECT data FROM messages WHERE id = @id) AS XML)
    DECLARE @reference VARCHAR(MAX) =  @xml.value('(/*:xml/*:reference/text())[1]', 'varchar(50)')
    DECLARE @name VARCHAR(MAX) = @xml.value('(/*:xml/*:name/text())[1]', 'varchar(50)')

END

SELECT
    @reference as reference,
    @name as name
GO

如何才能使用多个值?

1 个答案:

答案 0 :(得分:0)

认为 for xml path做你想做的事:

DECLARE @xml XML = (SELECT data FROM messages WHERE id = @id FOR XML PATH (''))