如何修复此查询以避免SQL Server 2008

时间:2017-10-01 13:25:38

标签: sql-server sql-server-2008

我想修复此查询,因为SQL Server会引发语法错误。

查询的目的是将列Articulo.ReferenciaFichas连接成一个字符串,以包含在select语句中。

表格

Articulos:

        Codigo    Nombre           
        ---------------
        Z540021   Motul oil 1050w2
        Z540022   Motul oil 1030w

ReferenciaFichas:

       Codigo      Articulo
       --------------------           
       MF99.00102   Z540021
       MP08-0186    Z540021
       OUT1006      Z540021
       MTUL14       Z540022

为了连接该列,我编写了这个独立的查询

DECLARE @provrefs VARCHAR(200)

SELECT 
    @provrefs = COALESCE(@provrefs + ',', '') + [provlist].[Codigo]
FROM
    (SELECT
         [Codigo]
     FROM 
         [GES16100].[dbo].[ReferenciasFichas]
     WHERE 
         Articulo = 'Z540021') provlist

SELECT @provrefs

结果是:

MF99.00102,MP08-0186,OUT1006

但是当我将此查询移动到select时,查询无效,因为语法错误。 我试过在文件顶部移动declare语句,然后添加 额外的括号。但我找不到任何解决方案。

我如何解决这个问题?

此查询无效:

SELECT
    [arts].[Codigo] AS [Referencia],
    ((DECLARE @provrefs VARCHAR(200)            
      SELECT @provrefs = COALESCE(@provrefs + ',', '') + [provlist].[Codigo]
      FROM
          (SELECT [reff].[Codigo]
           FROM [GES16100].[dbo].[ReferenciasFichas] reff
           WHERE [reff].[Articulo] = [arts].[Codigo]) provlist)
SELECT @provrefs) AS [Proveedores]
FROM [GES16100].[dbo].[Articulos] AS arts

预期结果

Referencia    Proveedores
--------------------------
Z540021       MF99.00102,MP08-0186,OUT1006
Z540022       MTUL14       

1 个答案:

答案 0 :(得分:1)

使用stuff() with select ... for xml path ('') method of string concatenation

select 
    Referencia = arts.Codigo
  , Proveedores = stuff(
      (
      select ','+reff.Codigo
      from GES16100.dbo.ReferenciasFichas as reff
      where reff.Articulo = arts.Codigo
      for xml path (''), type).value('(./text())[1]','nvarchar(max)')
    ,1,1,'')
from GES16100.dbo.Articulos as arts

rextester演示:http://rextester.com/MVSW22706

返回:

+------------+------------------------------+
| Referencia |         Proveedores          |
+------------+------------------------------+
| Z540021    | MF99.00102,MP08-0186,OUT1006 |
| Z540022    | MTUL14                       |
+------------+------------------------------+