【问题标题】:How to iterate through column name of a table and pass value to UDF in MSSQL while loop如何遍历表的列名并将值传递给 MSSQL while 循环中的 UDF
【发布时间】:2021-12-10 10:19:07
【问题描述】:

表格名称:股票

我正在尝试在股票表中获取股票公司的损益。(请参阅下面屏幕截图中的输出表)

我创建了用户定义函数,将参数作为股票公司传递并返回整数值,显示盈亏。

 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 是主列。

输出:

【问题讨论】:

    标签: sql-server stored-procedures while-loop sql-server-2012 user-defined-functions


    【解决方案1】:

    这里似乎不需要 UDF

    一个简单的条件聚合就可以解决问题

    Select StockCompany
          ,ProfitLoss = sum( StockValue * case when TransactionType = 'Buy' then -1 else 1 end)
     From  YourTable
     Group By StockCompany
    

    【讨论】:

      猜你喜欢
      • 2019-01-01
      • 2019-03-06
      • 1970-01-01
      • 2011-10-24
      • 2022-11-12
      • 2018-02-02
      • 2021-10-24
      • 2016-10-02
      • 1970-01-01
      相关资源
      最近更新 更多