使用SQL Server Reporting Services,我想生成一个包含某些订单的行详细信息的报告,如下所示:
Order Details
2315 1x5432 Apple Tree, 9x912 Roses, 1x13 Spade
2316 3x12 Lawn grass
如果使用transact SQL或使用Reporting Services中内置的东西,我怎么能最有效地做到这一点? (我可能会以许多订单结束,因此每个订单行的调用可能很昂贵......)
答案 0 :(得分:1)
我一般用用户定义的函数解决了这类问题。
CREATE FUNCTION GetDetails (@order_id INT) RETURNS NVARCHAR(1000) AS
BEGIN
DECLARE mycursor
CURSOR READ_ONLY
FOR SELECT description
FROM OrderDetails
WHERE order_id = @order_id
DECLARE @description NVARCHAR(100)
DECLARE @return_value NVARCHAR(1000)
SET @return_value = ''
OPEN mycursor
FETCH NEXT FROM mycursor INTO @description
WHILE @@fetch_status = 0
BEGIN
SET @return_value = @return_value + @description
FETCH NEXT FROM mycursor INTO @description
IF (@@fetch_status = 0) SET @return_value = @return_value + ', '
END
CLOSE mycursor
DEALLOCATE mycursor
RETURN @return_value
END;
您的查询将是:
SELECT order_id, GetDetails(order_id) as details
FROM Order
答案 1 :(得分:1)
我使用FOR XML和STUFF
做同样的事情SELECT DISTINCT
Col1.Table_Name TableName,
STUFF
(
(
SELECT
', ' + CONVERT (VARCHAR, Col2.Column_name)
FROM Information_Schema.Columns Col2
WHERE Col1.Table_Name = Col2.Table_Name
ORDER BY Col2.Table_Name
FOR XML PATH('')
), 1, 2, ''
) AS ColumnNames
FROM Information_Schema.Columns Col1
答案 2 :(得分:0)
我使用受this thread启发的COALESCE
解决了它:
CREATE FUNCTION GetDetails(@OrderID varchar(10))
RETURNS varchar(1000) AS
BEGIN
DECLARE @result varchar(1000), @delimiter char
SET @delimiter = ','
SELECT @result = COALESCE(@result + @delimiter, '') + Details
FROM
(
SELECT ProductNumber
, Quantity + 'x' + ProductNumber + ' ' + ProductName AS Details
FROM OrderDetail where OrderID = @OrderID
) OrderDetail
ORDER BY ProductNumber
RETURN @result
END
然后,如同the answer by Jeremy Stein:
SELECT OrderId, GetDetails(OrderId) AS Details
FROM Order