将视图中的数据聚合为 UDF 以在 select 语句中使用 [英] Aggregate data from view as UDF to use in select statement
本文介绍了将视图中的数据聚合为 UDF 以在 select 语句中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个现有视图,它以以下格式返回数据.
I have an existing view that returns data in the following format.
option_name product_id
XSMALL (2-6) 17854
SMALL (6-10) 17854
MEDIUM (10-14) 17854
LARGE 18232
如何根据向函数发送 product_id 以逗号分隔的格式返回此数据?
How do I return this data in a comma separated field formatted like this, based on sending a product_id to the function?
超小 (2-6)、小 (6-10)、中 (10-14)
XSMALL (2-6), SMALL (6-10), MEDIUM (10-14)
我使用的是 MS SQL 2k5.
I am using MS SQL 2k5.
推荐答案
您可以在 SQL Server 2005 及更高版本中使用 FOR XML PATH
:
You can use FOR XML PATH
in SQL Server 2005 and up:
CREATE FUNCTION dbo.GetProductNames(@ProductID int)
RETURNS TABLE
AS
SELECT
Options = SUBSTRING((
SELECT ', ' + o2.option_name
FROM options AS o2
WHERE o2.product_id = o1.product_id
FOR XML PATH('')), 3, 1000)
FROM options AS o1
WHERE o1.product_id = @ProductID
这篇关于将视图中的数据聚合为 UDF 以在 select 语句中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文