Get value from STUFF function in T-SQL

时间:2017-10-12 09:48:54

标签: sql sql-server tsql

I have this query:

SELECT STUFF(
(
    SELECT ' '+CONVERT(VARCHAR(MAX), R.ID)+' '+O.DisplayName+' : '+CONVERT(NVARCHAR(MAX), R.Value)
    FROM AA_V_PHR_CCD_ResultsXResults R 
        INNER JOIN AA_V_PHR_CCD_ResultsObservationXLANGUAGES O
        ON R.IDResultObservation = O.ID 
    WHERE IDResults = @ID_ESAME   AND O.IDLanguage = 2
    FOR XML PATH('')

), 1, 1, '') [data];

Now I should to execute this query from my Store Procedure. This query result this Message:

data
1604 HBsAg : 0.140 1605 HBsAb : 0.000 1606 HCV : 0.020

Now I want to put this result in my variables to execute other operation, so I have do this:

BEGIN
DECLARE @TEXT AS NVARCHAR(4000)
SELECT TEXT = STUFF(
(
    SELECT ' '+CONVERT(VARCHAR(MAX), R.ID)+' '+O.DisplayName+' : '+CONVERT(NVARCHAR(MAX), R.Value)
    FROM AA_V_PHR_CCD_ResultsXResults R 
        INNER JOIN AA_V_PHR_CCD_ResultsObservationXLANGUAGES O
        ON R.IDResultObservation = O.ID 
    WHERE IDResults = @ID_ESAME   AND O.IDLanguage = 2
    FOR XML PATH('')

), 1, 1, '') [data];

END

But if I try to execute this code I have an error message:

Incorrect syntax near to 'data'.

1 个答案:

答案 0 :(得分:1)

删除别名:

BEGIN
DECLARE @TEXT AS NVARCHAR(4000)
SELECT TEXT = STUFF(
(
    SELECT ' '+CONVERT(VARCHAR(MAX), R.ID)+' '+O.DisplayName+' : '+CONVERT(NVARCHAR(MAX), R.Value)
    FROM AA_V_PHR_CCD_ResultsXResults R 
        INNER JOIN AA_V_PHR_CCD_ResultsObservationXLANGUAGES O
        ON R.IDResultObservation = O.ID 
    WHERE IDResults = @ID_ESAME   AND O.IDLanguage = 2
    FOR XML PATH('')

), 1, 1, '') [data];

END