CREATE FUNCTION dbo.GetFieldValueByDataType (@ASysObj_Id INT, @AColName VARCHAR(128), @AValue VARCHAR(8000)) RETURNS VARCHAR(8000) AS 
BEGIN

DECLARE @SysName VARCHAR(128)

SELECT @SysName = SysTypes.Name FROM syscolumns
INNER JOIN SysObjects ON SysObjects.Id = SysColumns.Id
INNER JOIN SysTypes ON SysTypes.xtype = SysColumns.xtype
WHERE SysObjects.Id = @ASysObj_Id
AND SysColumns.Name = @AColName

RETURN
CASE @SysName 
  WHEN 'bigint'        THEN CAST(CAST(@AValue AS BIGINT) AS VARCHAR)
  WHEN 'binary'        THEN CAST(CAST(@AValue AS BINARY) AS VARCHAR)
  WHEN 'bit'           THEN CAST(CAST(@AValue AS BIT) AS VARCHAR)
  WHEN 'char'          THEN CAST(CAST(@AValue AS CHAR) AS VARCHAR)
  WHEN 'datetime'      THEN CAST(CAST(@AValue AS DATETIME) AS VARCHAR)
  WHEN 'decimal'       THEN CAST(CAST(@AValue AS DECIMAL) AS VARCHAR)
  WHEN 'float'         THEN CAST(CAST(@AValue AS FLOAT) AS VARCHAR)
  WHEN 'int'           THEN CAST(CAST(@AValue AS INT) AS VARCHAR)
  WHEN 'money'         THEN CAST(CAST(@AValue AS MONEY) AS VARCHAR)
  WHEN 'nchar'         THEN CAST(CAST(@AValue AS NCHAR) AS VARCHAR)
  WHEN 'numeric'       THEN CAST(CAST(@AValue AS NUMERIC) AS VARCHAR)
  WHEN 'real'          THEN CAST(CAST(@AValue AS REAL) AS VARCHAR)
  WHEN 'smalldatetime' THEN CAST(CAST(@AValue AS SMALLDATETIME) AS VARCHAR)
  WHEN 'smallint'      THEN CAST(CAST(@AValue AS SMALLINT) AS VARCHAR)
  WHEN 'smallmoney'    THEN CAST(CAST(@AValue AS SMALLMONEY) AS VARCHAR)
  WHEN 'timestamp'     THEN CAST(CAST(@AValue AS TIMESTAMP) AS VARCHAR)
  WHEN 'tinyint'       THEN CAST(CAST(@AValue AS TINYINT) AS VARCHAR)
  WHEN 'varbinary'     THEN CAST(CAST(@AValue AS VARBINARY) AS VARCHAR)
  WHEN 'varchar'       THEN CAST(CAST(@AValue AS VARCHAR) AS VARCHAR)
END

END