我在SQL Server 2008 R2中创建了一个返回varchar(4000)的标量函数。 此varchar(4000)是连接表的多个行和多个列的结果。 我将在报告的选择源中使用此功能。 详细信息是具有特定销售数量和价格的产品。
使用select功能时会出现问题。 结果被截断。 他要返回13行,只返回5。 如果我在sql management studio函数内使用print命令返回 13行。
如何使函数返回正确的数字行?
print dbo.fnReturnProducts ('{25899A98-5E68-E641-8C9D-7F341F17F2EF}') -- returns 13 lines
select dbo.fnReturnProducts ('{25899A98-5E68-E641-8C9D-7F341F17F2EF}') -- returns 5 lines
alter function [dbo].[fnReturnProducts](@OrderId uniqueidentifier) returns varchar(4000)
begin
declare @Products as varchar(4000)
declare @ProductName as varchar(43)
declare @ProductOrder as varchar(3)
declare @Quantity varchar(30)
declare @UnitPrice varchar(30)
declare @TotalPrice varchar(30)
select @Products = ''
DECLARE aux_cursor CURSOR FOR
select
ProductName as ProductName,
dbo.FormatNumber (ProductOrder, 0, '(', 0) as ProductOrder,
dbo.FormatNumber (Quantity, 2, '', 0) as Quantity,
dbo.FormatNumber (UnitPrice , 2, '$', 0) as UnitPrice,
dbo.FormatNumber (Quantity * UnitPrice, 2, '$', 0) as TotalPrice
from vwOrderDetails
Where OrderId = @OrderId
order BY vwOrderDetails.ProductOrder
OPEN aux_cursor
FETCH NEXT FROM aux_cursor
INTO
@ProductName,
@ProductOrder,
@Quantity,
@UnitPrice,
@TotalPrice
WHILE @@FETCH_STATUS = 0
BEGIN
if len(@Products) > 0
begin
select @Products = @Products + char(10)
end
select @Products = @Products + '(' + @ProductOrder + ') ' + @Quantity + ' - ' + @ProductName + ' a ' + @UnitPrice + ' = ' + @TotalPrice
FETCH NEXT FROM aux_cursor
INTO
@ProductName,
@ProductOrder,
@Quantity,
@UnitPrice,
@TotalPrice
END
CLOSE aux_cursor
DEALLOCATE aux_cursor
RETURN @Products
end
go
答案 0 :(得分:0)
试试这个:
select dbo.fnReturnProducts ('{25899A98-5E68-E641-8C9D-7F341F17F2EF}') into #tablename
select * from #tablename
答案 1 :(得分:0)
这不是答案,而是来自SSMS(和应用程序)的结果。 查看区别:仅打印和选择命令。 在应用程序内部我使用select(我的问题)。
print dbo.fnReturnProducts ('{25899A98-5E68-E641-8C9D-7F341F17F2EF}') -- returns 13 lines
(1) 1.00 - MAC INST PARATI GAL/CAIPIRA 85GR a $.75 = $.75
(2) 1.00 - MAC INST PARATI CAR/LEG.85GR a $.75 = $.75
(3) 1.00 - MAC INST PARATI GAL/CAIPIRA 85GR a $.75 = $.75
(4) 1.00 - TRINK TANGERINA 35GR a $.69 = $.69
(5) 1.00 - TRINK TANGERINA 35GR a $.69 = $.69
(6) 1.00 - MAC ORSI BAM.OVOS PARAFUSO 500GR a $1.56 = $1.56
(7) 1.00 - MAC INST PARATI CAR/LEG.85GR a $.75 = $.75
(8) 1.00 - ORSI ACHOC PO 400GR a $2.16 = $2.16
(9) 1.00 - ORSI ACHOC PO 400GR a $2.16 = $2.16
(10) 1.00 - BISC.PANCO ROSQ NATA 500G a $3.53 = $3.53
(11) 1.00 - ST PROTEX ERVA DOCE 90GR a $1.76 = $1.76
(12) 1.00 - OLEO SOJA CORCOVADO 900ML UN a $3.59 = $3.59
(13) 1.00 - OLEO SOJA CORCOVADO 900ML UN a $3.59 = $3.59
select dbo.fnReturnProducts ('{25899A98-5E68-E641-8C9D-7F341F17F2EF}') -- returns 5 lines
(1) 1.00 - MAC INST PARATI GAL/CAIPIRA 85GR a $.75 = $.75
(2) 1.00 - MAC INST PARATI CAR/LEG.85GR a $.75 = $.75
(3) 1.00 - MAC INST PARATI GAL/CAIPIRA 85GR a $.75 = $.75
(4) 1.00 - TRINK TANGERINA 35GR