返回首页

我有一个观点,即调用一个函数(输入日期)计算,一切正常,然而,现在存储在另一个表(要求输入日期值的变化和列,而在此之前它是一个表,我可以传递到它的功能)。我的挑战是,我需要获取列名的其他的表tbl_LURecordCode

vw_FolderRetentionDates是认为加入有5至10日期列包含需要返回值的表。基于在tbl_LURecordCode转让,我需要获取该值,并传递到现有的功能,不计算。


Create Function [dbo].[fn_GetRetentionDate]

(

    @recodeCode varchar(10),

    @trackingID varchar(38)

)

Returns Date

AS

BEGIN

    -- Declare the return variable here

    DECLARE @Result as Date, @ColumnName as varchar(50)

    

    -- Fetch the column assigned to the record code.

    Select @ColumnName  = RetentionDateColumnName From tbl_LURecordCode Where RecordCode = @recodeCode;

    

    -- default to EndDate if not set.

    IF @ColumnName IS NULL

        set @ColumnName = 'EndDate';

        

    -- fetch the value of the column name from the view

    Select @Result = @ColumnName FROM vw_FolderRetentionDates Where Tracking_ID = @trackingID

    

    Return @Result

END

 


这个函数总是返回NULL,并告诉我选择@结果= @ ColumnName是试图分配一个NULL @结果,这是日期类型的空。

我可以使用动态SQL创建一个存储过程,但我不能从一个视图或函数调用的SP,我需要调用计算功能从视图

有另一种方式做或没有任何方式来获得在功能工作不使用动态SQL(我不认为有,但我想我会抛出这个,看看是否有人有一个想法)

一种可能的解决方案将基于@的ColumnName创建一个CASE语句,并执行SQL:

伪代码:
{C}
唯一的缺点是,如果添加另一个日​​期列,那么我们必须去更新此功能。

谢谢,
皮特

回答

评论会员:皮特平衡计分卡 时间:2012/02/06
我结束了这样做的,它的工作原理:

ALTER Function [dbo].[fn_GetRetentionDate]

(

	@recodeCode varchar(10),

	@trackingID varchar(38),

	@endDate date

)

Returns Date

AS

BEGIN

	-- Declare the return variable here

	DECLARE @Result as Date, @ColumnName as varchar(50)

	

	-- Fetch the column assigned to the record code.

	Select @ColumnName  = RetentionDateColumnName From tbl_LURecordCode Where RecordCode = @recodeCode;

	

	-- default to EndDate if not set.

	IF @ColumnName IS NULL

		set @ColumnName = 'EndDate';

		

	-- fetch the value of the column name from the view

	Return Case @ColumnName

	 When 'SettleDate' Then (SELECT SettleDate from vw_FolderRetentionDates Where Tracking_ID = @trackingID)

	 When 'EndDate' Then @endDate --(SELECT EndDate from vw_FolderRetentionDates Where Tracking_ID = @trackingID)

	 When 'TerminationDate' Then (SELECT TerminationDate from vw_FolderRetentionDates Where Tracking_ID = @trackingID)

	 When 'TradeDate' Then (SELECT TradeDate from vw_FolderRetentionDates Where Tracking_ID = @trackingID)

	 When 'PaidDate' Then (SELECT PaidDate from vw_FolderRetentionDates Where Tracking_ID = @trackingID)

	 When 'InvoiceDate' Then (SELECT InvoiceDate from vw_FolderRetentionDates Where Tracking_ID = @trackingID)

	 When 'FundEndDate' Then (SELECT FundEndDate from vw_FolderRetentionDates Where Tracking_ID = @trackingID)		 ELSE NULL

	End	

	

END

评论会员:digimanus 时间:2012/02/06
你尝试[@的ColumnName]。在这种情况下一个变量被视为栏