在PHP中运行Microsoft .SQL文件

时间:2011-03-23 10:43:42

标签: php sql-server

如何使用php运行MSSQL .sql文件?

我有一组MS SQL文件,如下所示,它们与ToadSQL一起用于检索过去的数据:

-- RUN AS SCRIPT SO THAT MONDAY IS FIRST DAY OF THE WEEK
set datefirst 1;

select top 10 artist_name, album_name, sum(units) total_units, sum(sales) total_sales from (

-- Sales by album
select c.[name] album_name, d.[name] artist_name, sum(b.price) sales, count(b.Id) units from [order] a, orderalbum b , album c, artist d
where b.albumid=c.id 
and c.ArtistId = d.Id
and a.successful=1 and a.id=b.orderid
and datepart(ww, a.OrderDate) = datepart(ww, getDate())-1
and datepart(yyyy, a.OrderDate) = datepart(yyyy, getDate())
group by c.[name], d.[name]

union

-- Sales by album variant
select d.[name] album_name, e.[name] artist_name, sum(b.price) sales, count(b.Id) units from [order] a, orderalbum b , albumvariant c, album d, artist e
where d.id=c.albumid and  b.albumvariantid=c.id   
and d.ArtistId = e.Id
and a.successful=1 and a.id=b.orderid
and datepart(ww, a.OrderDate) = datepart(ww, getDate())-1
and datepart(yyyy, a.OrderDate) = datepart(yyyy, getDate())
group by d.[Name], e.[Name]

) x
group by x.album_name, x.artist_name
having sum(x.sales) > 0
order by total_units desc; 

我现在正在构建一个应用程序以自动执行该过程,但我不想重新发送带有查询的轮子。如何使用php

运行MSSQL .sql文件

由于有些查询两个表并且使用'union'这可能会变得特别复杂吗?

希望有一些可以提供帮助的SQL主管。

2 个答案:

答案 0 :(得分:2)

在CodeIgniter中我提出了以下内容:

function runsql($file = '')
{

    $this->db_download = $this->load->database('download', TRUE);

    $sql = file_get_contents($file);

    $query = $this->db_download->query($sql);
    $result = $query->result();

    return $result;

}

这很简单,只需获取文件内容并将其作为查询运行即可。

答案 1 :(得分:0)

所以你的目标是制作一个基于输入文件运行查询的php文件,然后将数据输出为html?

这不仅仅是将文件读入php中的字符串然后只是通过ODBC或类似的东西执行吗?