我有一张包含Product
条记录和Model
条记录的表格。产品和模型记录都有QTY
和Size
列。对于给定的product_id
,我想从qtys
条记录中抓取所有sizes
和Model
,并将它们放入单qty and size
**父 Product
记录的字段,由管道“|
”分隔。这是我到目前为止的sql。它成功地从给定product_id的Model记录中获取大小和数量值,但我无法让它更新父Product记录字段,并以递归方式执行。有人可以帮我一把吗? THX
此示例使用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
答案 0 :(得分: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'
答案 1 :(得分: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'