What is the purpose of creating a temporary table in MSSQL using PHP?

Creating a temporary table in MSSQL using PHP can be useful when you need to store temporary data that is specific to a particular session or query. Temporary tables can help improve performance by reducing the need for complex joins or subqueries. They can also be used to break down a complex query into smaller, more manageable parts.

<?php
// Establish a connection to the MSSQL database
$serverName = "your_server_name";
$connectionOptions = array(
    "Database" => "your_database_name",
    "Uid" => "your_username",
    "PWD" => "your_password"
);
$conn = sqlsrv_connect($serverName, $connectionOptions);

// Create a temporary table
$sql = "
CREATE TABLE #tempTable (
    ID INT PRIMARY KEY,
    Name VARCHAR(50)
)";
$stmt = sqlsrv_query($conn, $sql);

// Insert data into the temporary table
$sql = "
INSERT INTO #tempTable (ID, Name)
VALUES (1, 'John'),
       (2, 'Jane'),
       (3, 'Doe')
";
$stmt = sqlsrv_query($conn, $sql);

// Retrieve data from the temporary table
$sql = "SELECT * FROM #tempTable";
$stmt = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    echo "ID: " . $row['ID'] . ", Name: " . $row['Name'] . "<br>";
}

// Drop the temporary table
$sql = "DROP TABLE #tempTable";
$stmt = sqlsrv_query($conn, $sql);

// Close the connection
sqlsrv_close($conn);
?>