Search code examples
phpsql-serversql-server-2000sqlsrv

Using SQLSRV_FIELD_METADATA is there a way to return full name data types, like VARCHAR or INT?


Dear intelligent people of the internets,

Using SQLSRV on SQL Server 2000 I'm trying to echo out the column data types and lengths using the SQLSRV_FIELD_METADATA function but only a number is passed which represents the data type.

Here is the code:

  echo '<pre>';
  echo '<ul>';
    foreach( sqlsrv_field_metadata( $stmt ) as $fieldMetadata ) {
        foreach( $fieldMetadata as $name => $value) {
           echo "<li>$name: $value</li>";
        }
        echo "<br/>";
    }
  echo '</ul>';
  echo '</pre>';

Here is a snippet of the output:

Name: UNITID
Type: 4
Size: 
Precision: 10
Scale: 
Nullable: 0

Name: STOCKNUMBER
Type: 12
Size: 30
Precision: 
Scale: 
Nullable: 1

Is there a way to convert Type: 4 and Type: 12 into the actual name of the column? So instead it would return Type: INT, and Type: VARCHAR.

Thank you for your help.


Solution

  • @Esorteric, thanks for the tip. I've implemented a function that acts as a type map as suggested:

      function returnType($value) {
        switch ($value) {
            case 4:
                return "(4) SQLDMO_DTypeInt4 :: Signed integer data. The width of the integer is four bytes.";
                break;
            case 12:
                return "(12) SQLDMO_DTypeVarchar :: Variable-length character data.";
                break;
            case 93:
                return "(93) SQLDMO_DTypeDateTime4 :: ODBC SQL_TIMESTAMP_STRUCT.";
                break;
            case 5:
                return "(5) SQLDMO_DTypeInt2 :: Signed integer data. The width of the integer is two bytes.";
                break;
            case -6:
                return "(-6) SQLDMO_DTypeInt1 :: Unsigned integer data. The width of the integer is one byte.";
                break;  
            case -1:
                return "(-1) SQLDMO_DTypeText :: Long, variable-length character data.";
                break;                      
        }     
    
      }