Search code examples
sql-server-2005t-sqlsql-variant

SQL 2005 - Variant Parameter Question


I am working on a function that will be used by no less than 10 SProc's, and will probably grow once it is ironed out.

Problem i am running into is that i do not want to develop a function for each Data Type, which is why the SQL_VARIANT data type is looking pretty convenient for the action. I know is can do the ISNULL check on the data type but i also want to check to see if the Value being passed is a valid Number but the ISNUMERIC function does not work with SQL_VARIANT and I'm not too sure about the SQL_VARIANT_PROPERTY function.

Code so far:

CREATE FUNCTION dbo.mpt_Format_Number
(
    @value SQL_VARIANT
    , @money BIT
)
RETURNS VARCHAR
AS
BEGIN
    --Check for NULL value
    IF ISNULL(@value) BEGIN
        -- Value IS NULL, return NULL
        RETURN NULL
    END ELSE BEGIN
        -- Value is NOT NULL
        DECLARE @TMP VARCHAR
    END 
END

Solution

  • CREATE FUNCTION dbo.mpt_Format_Number 
    ( 
        @value SQL_VARIANT 
        , @money BIT 
    ) 
    RETURNS VARCHAR 
    AS 
    BEGIN 
    --Check for NULL value 
    IF @value is null  
              -- Value IS NULL, return NULL 
        RETURN NULL 
    ELSE 
    BEGIN 
        -- Value is NOT NULL 
        if isnumeric(convert(varchar(max), @value)) = 1 RETURN 'Y' -- is valid number
        --DECLARE @TMP VARCHAR 
    
    END  
    return 'N' --is not valid number 
    END 
    

    You can always test the property type with this syntax. Should be easy to incooperate in your function.

    declare @t SQL_VARIANT
    set @t = '3'
    select SQL_VARIANT_PROPERTY(@t, 'basetype') 
    

    Result:

    varchar