是否可以为计算列规范或公式添加SELECT查询?我想使用这个查询:
SELECT IIF( [Name] = 'Tuition'
, CONVERT([DECIMAL](15,2),Cost * t1.SubjectUnit)
, CONVERT([DECIMAL](15,2),Cost)
) as FinalCost
FROM [HCCDB].[dbo].[SubjectOfferedFee] AS t0
INNER JOIN HCCDB.dbo.SubjectsOffered AS t1
ON t1.SubjectsOfferedID = t0.SubjectsOfferedID
在ALTER表语句中:
ALTER TABLE HCCDB.dbo.SubjectOfferedFee
ADD FinalCost AS [THE QUERY SELECT QUERY ABOVE]
我在另一列上尝试过此操作,方法是通过创建新列并添加公式来连接列。
CONVERT([varchar](50),[FirstName])
+ ' ' + CONVERT([varchar](50),[MiddleName])
+ ' ' + CONVERT([varchar](4),[LastName])
它有效,但如何添加SELECT查询?
答案 0 :(得分:0)
只需在当前上下文中创建用户定义函数。
CREATE FUNCTION dbo.fnGetSubjectCost(@id INT)
RETURNS DECIMAL
AS
-- Returns cost if the subject that if particular name is equal to Tuition then cost x unit.
BEGIN
DECLARE @ret DECIMAL;
SELECT @ret = IIF([Name] = 'Tuition', CONVERT([DECIMAL](15,2),Cost * t1.SubjectUnit), CONVERT([DECIMAL](15,2),Cost))
FROM [HCCDB].[dbo].[SubjectOfferedFee] AS t0
INNER JOIN HCCDB.dbo.SubjectsOffered AS t1
ON t1.SubjectsOfferedID = t0.SubjectsOfferedID
WHERE t0.SubjectOfferedFeeID = @id
IF (@ret IS NULL)
SET @ret = 0;
RETURN @ret;
END;
GO
然后您可以使用此函数计算列规范或
ALTER TABLE HCCDB.dbo.SubjectOfferedFee
ADD FinalCost AS CONVERT(DECIMAL(15,2), dbo.fnGetSubjectCost(CONVERT(INT, [SubjectOfferedFeeID])))
然后解决了。