此查询在 Sql Server Management Studio 中运行良好,但是当我尝试在数据集中运行并从日期时间选择器传递 Date(@Param2 & @Pram3) 时,它抛出异常转换失败。我不知道这有什么问题,我的其他查询工作正常。这是因为 UNION ALL 而发生的吗?
.NET 代码
startDatePicker.Format = DateTimePickerFormat.Short;
endDatePicker.Format = DateTimePickerFormat.Short;
DataTable ntwTable = ntw.GetData(owner,start,end);
start = startDatePicker.Value.ToShortDateString();
end = endDatePicker.Value.ToShortDateString();
SQL
SELECT o.Name, SUM(sq.SQuantity * sq.SRate) AS TotalSale, SUM(sq.PrQuantity * sq.PrRate) AS TotalPurchase, (SUM(sq.PQuantity) - SUM(sq.SQuantity))
* (SUM(sq.PQuantity * sq.PRate) / SUM(sq.PQuantity)) AS Inventory
FROM (SELECT OwnerId, CompanyId, Quantity AS PQuantity, RatePerShare AS PRate, 0 AS SQuantity, 0 AS SRate, 0 AS PrQuantity, 0 AS PrRate, Date
FROM Purchase
UNION ALL
SELECT OwnerId, CompanyId, 0 AS PQuantity, 0 AS PRate, 0 AS SQuantity, 0 AS SRate, Quantity AS PrQuantity, RatePerShare AS PrRate, Date
FROM Purchase AS pr
UNION ALL
SELECT OwnerId, CompanyId, Quantity AS PQuantity, 0 AS PRate, 0 AS SQuantity, 0 AS SRate, 0 AS PrQuantity, 0 AS PrRate, Date
FROM Bonus
UNION ALL
SELECT OwnerId, CompanyId, Quantity AS PQuantity, CostOfShare AS PRate, 0 AS SQuantity, 0 AS SRate, 0 AS PrQuantity, 0 AS PrRate, Date
FROM RightShare
UNION ALL
SELECT OwnerId, CompanyId, 0 AS PQuantity, 0 AS PRate, Quantity AS SQuantity, RatePerShare AS SRate, 0 AS PrQuantity, 0 AS PrRate, Date
FROM Sales) AS sq INNER JOIN
Owner AS o ON o.OwnerId = sq.OwnerId
WHERE (o.OwnerId = @Param1) AND (sq.Date BETWEEN @Param2 AND @Param3)
GROUP BY sq.CompanyId, o.Name