我不太确定如何问这个问题,但让我通过例子来问:
我有一个表,无法更改其结构。它记录类似 ATM 终端的现金存款,并为每种面额的纸币有一栏。现在,当我需要存款的总值(value)时,我需要这样的代码:
(rd.Count_R10 * 10) + (rd.Count_R20 * 20) + (rd.Count_R50 * 50) + (rd.Count_R100 * 100) + (rd.Count_R200 * 200)
我想编写一个 T-SQL 函数来为我提供该总值,但对于任何行,而不是整个查询,因此我的函数将类似于:
CREATE FUNCTION DepositTotal
(
@row ????
)
RETURNS money
AS
BEGIN
RETURN (row.Count_R10 * 10) + (row.Count_R20 * 20) + (row.Count_R50 * 50) + (row.Count_R100 * 100) + (row.Count_R200 * 200)
END
然后我会这样调用它:
select
DepositDate
, DepositTotal(thisRow)
, BatchId
from Deposits
最佳答案
解决方案必须是函数吗?或者是您无法更改表结构的限制因素?您可以在表格上编写一个 View ,添加一个包含您的总值(value)的列。
CREATE VIEW DepositsWithTotal
select
Deposits.* -- Expand this - I just don't know your schema
, DepositTotal = (Count_R10 * 10) + (Count_R20 * 20) + (Count_R50 * 50) + (Count_R100 * 100) + (Count_R200 * 200)
from Deposits
然后只需从 DepositsWithTotal
中选择,而不是 Deposits
关于sql-server - 将 'current' 行传递给 SQL Server 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4647042/