如何遍历 table 的列名并将值传递给 MSSQL while 循环中的 UDF
How to iterate through column name of a table and pass value to UDF in MSSQL while loop
表名:股票
我正在尝试获取股票公司的利润或亏损 table。(参考下面屏幕截图中的输出 table)
我创建了用户定义函数,传递参数为股票公司和 return 显示损益的整数值。
CREATE FUNCTION FetchStockProfitLoss(
@stockCompany nvarchar(50)
)
RETURNS INT
AS
BEGIN
declare @buyStock as INT;
declare @sellStock as INT;
declare @profitLoss as INT;
Set @buyStock = (SELECT SUM(stockvalue) from stocks where stockcompany=@stockCompanyand transactiontype='buy');
Set @sellStock = (SELECT SUM(stockvalue) from stocks where stockcompany=@stockCompanyand transactiontype='sell');
set @profitLoss = (@buyStock) -(@sellStock);
RETURN @profitLoss
END;
通过传递单个 StockCompany 调用 UDF。
SELECT distinct stock_symbol,dbo.FetchIndStock('Google') as ProfitLoss from stocks where stock_symbol='Google'
如何在存储过程中使用循环为所有股票公司实现相同的结果(如输出)?
示例数据:
TransactionID 是主列。
输出:
这里似乎不需要 UDF
一个简单的条件聚合应该可以解决问题
Select StockCompany
,ProfitLoss = sum( StockValue * case when TransactionType = 'Buy' then -1 else 1 end)
From YourTable
Group By StockCompany
表名:股票
我正在尝试获取股票公司的利润或亏损 table。(参考下面屏幕截图中的输出 table)
我创建了用户定义函数,传递参数为股票公司和 return 显示损益的整数值。
CREATE FUNCTION FetchStockProfitLoss(
@stockCompany nvarchar(50)
)
RETURNS INT
AS
BEGIN
declare @buyStock as INT;
declare @sellStock as INT;
declare @profitLoss as INT;
Set @buyStock = (SELECT SUM(stockvalue) from stocks where stockcompany=@stockCompanyand transactiontype='buy');
Set @sellStock = (SELECT SUM(stockvalue) from stocks where stockcompany=@stockCompanyand transactiontype='sell');
set @profitLoss = (@buyStock) -(@sellStock);
RETURN @profitLoss
END;
通过传递单个 StockCompany 调用 UDF。
SELECT distinct stock_symbol,dbo.FetchIndStock('Google') as ProfitLoss from stocks where stock_symbol='Google'
如何在存储过程中使用循环为所有股票公司实现相同的结果(如输出)?
示例数据:
TransactionID 是主列。
输出:
这里似乎不需要 UDF
一个简单的条件聚合应该可以解决问题
Select StockCompany
,ProfitLoss = sum( StockValue * case when TransactionType = 'Buy' then -1 else 1 end)
From YourTable
Group By StockCompany