Sqlsrv_field_metadata с именем и типом

Работаю над преобразованием моего php-кода mysql в sqlsrv, но не могу понять, как получить тип и имя с помощью sqlsrv_field_metadata.

Это код: РЕДАКТИРОВАТЬ (я вставил весь код здесь)

 $sql = "
    SELECT tasks.title as Oppgaver, routines.value as Verdi, DATE_FORMAT(routines.date, '%d/%m/%Y') as Dato, routines.time as Tid, emps.user_name as Ansatt
    FROM routines, task_routine, tasks, emps
    WHERE routines.id = task_routine.routine_id
    AND task_routine.task_id = tasks.id
    AND (tasks.title  Like 'C_%') AND routines.emp_id=emps.id 
    ORDER BY routines.date, routines.time";
  }



 $result=sqlsrv_query($conn,$sql) or die("Couldn't execute query:<br>" . sqlsrv_error(). "<br>" . sqlsrv_errno()); 


$file_ending = "xls";
$reals=array();
//header info for browser
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename.xls");  
header("Pragma: no-cache"); 
header("Expires: 0");
/*******Start of Formatting for Excel*******/   
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character

//start of printing column names as names of MySQL fields

/*for ($i = 0; $i < sqlsrv_num_fields($result); $i++) {
    $type = sqlsrv_field_metadata($result,$i);
    echo sqlsrv_field_metadata($result,$i) . "\t";
    if ($type == "real")
    {
        $reals[] = $i;
    }
}*/

$metaData = sqlsrv_field_metadata($result);

for ($i = 0; $i < $metaData; $i++) {
   $type = $metaData[$i]["Type"];
   echo $metaData[$i]["Name"] . "\t";
   if ($type === SQL_REAL) {
      $reals[] = $i;
   }
}


print("\n");    
//end of printing column names  
//start while loop to get data
while($row = sqlsrv_num_rows($result))
{
    $schema_insert = "";
    for($j=0; $j<sqlsrv_num_fields($result);$j++)
    {
        if(!isset($row[$j]))
            $schema_insert .= "NULL".$sep;
        elseif ($row[$j] != ""){
            if (in_array($j, $reals)){
                $schema_insert .= str_replace(".",",","$row[$j]").$sep;
            } else {
                $schema_insert .= "$row[$j]".$sep;
            }
        }
        else
            $schema_insert .= "".$sep;
    }
    $schema_insert = str_replace($sep."$", "", $schema_insert);
    $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
    $schema_insert .= "\t";
    print(trim($schema_insert));
    print "\n";

} 

MYSQL (что работает)

$sql = "
SELECT measurements.title as Maling, routines.value as Verdi, DATE_FORMAT(routines.date, '%d/%m/%Y') as Dato, routines.time as Tid, pools.name as Basseng, emps.user_name as Ansatt
FROM routines, measure_routine, measurements, pools, emps
WHERE routines.id = measure_routine.routine_id
AND measure_routine.measure_id = measurements.id
AND (measurements.title  Like 'T_%') AND measure_routine.pool_id=pools.id AND routines.emp_id=emps.id 
ORDER BY routines.date, routines.time;

";
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database   
$Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());   
//execute query 
$result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());    
$file_ending = "xls";
$reals=array();
//header info for browser
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename.xls");  
header("Pragma: no-cache"); 
header("Expires: 0");
/*******Start of Formatting for Excel*******/   
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
    $type = mysql_field_type($result,$i);
    echo mysql_field_name($result,$i) . "\t";
    if ($type == "real")
    {
        $reals[] = $i;
    }
}



print("\n");    
//end of printing column names  
//start while loop to get data
while($row = mysql_fetch_row($result))
{
    $schema_insert = "";
    for($j=0; $j<mysql_num_fields($result);$j++)
    {
        if(!isset($row[$j]))
            $schema_insert .= "NULL".$sep;
        elseif ($row[$j] != ""){
            if (in_array($j, $reals)){
                $schema_insert .= str_replace(".",",","$row[$j]").$sep;
            } else {
                $schema_insert .= "$row[$j]".$sep;
            }
        }
        else
            $schema_insert .= "".$sep;
    }
    $schema_insert = str_replace($sep."$", "", $schema_insert);
    $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
    $schema_insert .= "\t";
    print(trim($schema_insert));
    print "\n";
}

Я искал документацию, но не узнал, как: http://msdn.microsoft.com/en-us/library/cc296197.aspx

1 ответ

Если вы эхо sqlsrv_field_metadata($stmt) как объект JSON, вы можете увидеть, как использовать эту функцию.

Взято из msdn sqlsrv_field_metadata:

$tsql = "SELECT ReviewerName, Comments FROM Production.ProductReview";
$stmt = sqlsrv_prepare( $conn, $tsql);

echo json_encode(sqlsrv_field_metadata($stmt));

приведет к строке JSON что-то вроде:

// Just example, related with nothing
[{
  "Name":"Id",
  "Type":-5,
  "Size":null,
  "Precision":19,
  "Scale":null,
  "Nullable":0
},
{
  "Name":"Username",
  "Type":-9,"Size":50,
  "Precision":null,
  "Scale":null,
  "Nullable":0
}]

С MSDN снова:

  • Name: Имя столбца, которому соответствует поле.
  • Type: Числовое значение, соответствующее типу SQL.
  • Size: Количество символов для полей символьного типа (char(n), varchar(n), nchar(n), nvarchar(n), XML). Количество байтов для полей двоичного типа (двоичный (n), varbinary (n), UDT). NULL для других типов данных SQL Server.
  • Precision: Точность для типов переменной точности (вещественная, числовая, десятичная, datetime2, datetimeoffset и время). NULL для других типов данных SQL Server.
  • Scale: Масштаб для типов переменной шкалы (числовой, десятичный, datetime2, datetimeoffset и время). NULL для других типов данных SQL Server.
  • Nullable: Перечисляемое значение, указывающее, является ли столбец обнуляемым (SQLSRV_NULLABLE_YES), столбец не обнуляемый (SQLSRV_NULLABLE_NO), или неизвестно, является ли столбец обнуляемым (SQLSRV_NULLABLE_UNKNOWN).

Снова ищем результат:

  • Первая строка - это столбец с именем Id ("Name": "Id") с типом bigint (SQL_BIGINT (-5)) и не может быть NULL (Nullable: 0)
  • Второй ряд - это столбец с именем Username с типом nvarchar(50) ("Type": -9 а также "Size": 50) и не может быть NULL

Итак, как получить имя и типы?

Определите массив и присвойте ему значение sqlsrv_field_metadata($stmt):

$metaData = sqlsrv_field_metadata($stmt); // $result instead of $stmt in your case

Теперь вы можете выполнить цикл с этим массивом:

for ($i = 0; $i < $metaData; $i++) {
   $type = $metaData[$i]["Type"];
   echo $metaData[$i]["Name"] . "\t";
   if ($type === SQL_REAL) {
      $reals[] = $i;
   }
}
Другие вопросы по тегам