SQL Server结果为带有计数器的单个字符串

时间:2014-04-10 01:40:42

标签: sql-server

我有一张这样的表:

 Product_Id      Description
 ---------------------------
  BX01              Desc 1
  BxX1              Desc 2
  Dss3              Desc 3
  HHXY              Desc 4

我希望结果完全符合:

1 - BX01, 2 - BxX1, 3 - Dss3, 4 - HHXY

我有这个问题:

DECLARE @ProID VARCHAR(8000)  
SELECT @ProID = COALESCE(@ProID + ', - ', '') + Product_Id FROM TABLE      
SELECT @ProID 

但返回值仅为:

BX01,- BxX1,- Dss3,- HHXY

缺少计数。

怎么做?

谢谢

2 个答案:

答案 0 :(得分:0)

使用row_number函数

尝试这样的事情
SELECT CAST(row_number AS VARCHAR(5)) +' - '+ Product_Id +', '
from
  (select Product_Id, ROW_NUMBER()OVER(order by Product_Id) as row_number
   FROM TABLE      ) as derived_tbl
FOR XML PATH('')

答案 1 :(得分:0)

假设数字是行号,您应该使用ROW_NUMBER()more info):

DECLARE @tmp TABLE (ID varchar(300), [Desc] varchar(300))

INSERT INTO @tmp (ID, [Desc])
SELECT 'BX01', 'Desc 1'
UNION
SELECT 'BxX1', 'Desc 2'
UNION
SELECT 'Dss3', 'Desc 3'
UNION
SELECT 'HHXY', 'Desc 4'

DECLARE @ProID VARCHAR(8000)  
SELECT @ProID = COALESCE(@ProID + ', ', '') + CAST(t.row AS varchar(20))+ ' - ' + t.ID
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY ID) AS row, ID
    FROM @tmp) AS t

SELECT @ProID