0

我有一张Product记录和Model记录的表格。产品和型号记录都有一个QTYSize列。对于给定的product_id,我想从记录中获取所有qtys和,并将它们放入**父记录的单个*字段中,由管道“”分隔。这是我到目前为止的sql。它成功地从给定 product_id 的模型记录中获取大小和数量值,但我无法让它更新父产品记录字段,并递归执行。有人可以帮帮我吗?谢谢sizesModelqty and size Product|

此示例使用 product_id'26206'

--declare local variables
DECLARE
      @size_DelimitedString VARCHAR(MAX),
      @qty_DelimitedString VARCHAR(MAX)

 --pivot rows into delimited string
SELECT
      @size_DelimitedString = COALESCE(@size_DelimitedString, '') + CONVERT(VARCHAR(10), [BD New Product Data].model_size) + '|'
FROM
      [BD New Product Data]
      where record_type = 'model' and product_id = '26206'

 SELECT
      @qty_DelimitedString = COALESCE(@qty_DelimitedString, '') + CONVERT(VARCHAR(10), [BD New Product Data].model_quantity) + '|'
FROM
      [BD New Product Data]
      where record_type = 'model' and product_id = '26206'

--trim off last pipe
SET @size_DelimitedString = (SELECT SUBSTRING(@size_DelimitedString, 1, LEN(@size_DelimitedString)-1))
SET @qty_DelimitedString = (SELECT SUBSTRING(@qty_DelimitedString, 1, LEN(@qty_DelimitedString)-1)) 

--show results  
SELECT @size_DelimitedString 
SELECT @qty_DelimitedString 
4

2 回答 2

0
SELECT 
   product_id
 , STUFF((
    SELECT '|' + CONVERT(VARCHAR(10), A.model_size)
    FROM [BD New Product Data] A 
    WHERE A.record_type = 'model' AND A.product_id = T.product_id
    FOR XML PATH(''), TYPE
   ).value('.', 'VARCHAR(MAX)'), 1, 1, '') AS product_sizes
 , STUFF((
    SELECT '|' + CONVERT(VARCHAR(10), A.model_quantity)
    FROM [BD New Product Data] A 
    WHERE A.record_type = 'model' AND A.product_id = T.product_id
    FOR XML PATH(''), TYPE
    ).value('.', 'VARCHAR(MAX)'), 1, 1, '') AS product_quantities
FROM [BD New Product Data] T 
WHERE T.record_type = 'product' 
 --AND T.product_id = '26206'
于 2013-04-11T02:53:50.630 回答
0
USE Prod
Update dbo.[BD Active Test]
 Set dbo.[BD Active Test].size = STUFF((
    SELECT '|' + CONVERT(VARCHAR(10), [dbo].[BD New Product Data Test].model_size)
    FROM [dbo].[BD New Product Data Test] 
    WHERE [dbo].[BD New Product Data Test].record_type = 'model' AND [dbo].[BD New Product Data Test].product_id = dbo.[BD Active Test].sku
    FOR XML PATH(''), TYPE
   ).value('.', 'VARCHAR(MAX)'), 1, 1, '')
 , dbo.[BD Active Test].qty = STUFF((
    SELECT '|' + CONVERT(VARCHAR(10), [dbo].[BD New Product Data Test].model_quantity)
    FROM [dbo].[BD New Product Data Test] 
    WHERE [dbo].[BD New Product Data Test].record_type = 'model' AND [dbo].[BD New Product Data Test].product_id = dbo.[BD Active Test].sku
    FOR XML PATH(''), TYPE
    ).value('.', 'VARCHAR(MAX)'), 1, 1, '')
from dbo.[BD Active Test]
INNER JOIN dbo.[BD New Product Data Test] ON dbo.[BD Active Test].sku = dbo.[BD New Product Data Test].product_id 
where dbo.[BD New Product Data Test].record_type = 'PRODUCT' 
于 2013-04-12T03:55:42.267 回答