четверг, 22 января 2015 г.

T-SQL Tricks - Part 2

Hi visitors,
Just in case: how can someone to use MS SQL Server 2000 system functions inside of UDF? The BOL says 'NO'. MS SQL 2008 restricts UDF but less.
But we will go further then plain 'no' and 'may be' and make almost ANY system function available in your UDF:

--The UDF:
CREATE FUNCTION dbo.fnSysGetAge(@dtBirthDate as datetime)
RETURNS int
AS
BEGIN
    DECLARE @intAge int, @dtGetDate datetime
    IF ISNULL(@dtBirthDate,0)<>0
    BEGIN
        SELECT  TOP 1 @dtGetDate = FunctionValue FROM vwSysFunctionValue WHERE FunctionName = 'GETDATE()'
        SET @intAge = ROUND(CONVERT(int, @dtGetDate - @dtBirthDate) / 365,0)
    END
    ELSE
        SET @intAge = 0
   
    RETURN @intAge
END
GO

--The view:
CREATE VIEW dbo.vwSysFunctionValue
AS
SELECT     CONVERT(nvarchar, GETDATE()) AS FunctionValue, 'GETDATE()' AS FunctionName
UNION
SELECT     CONVERT(nvarchar(20), RAND()) AS FunctionValue, 'RAND()' AS FunctionName
UNION
SELECT     CONVERT(nvarchar(20), dbo.fnSysGetCurrentUserOptionID()) AS FunctionValue, 'UserID()' AS FunctionName
GO
-------------
The same trick you can make with other system function - if they are available in views then they are available in your UDF!