萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

SQL Server 資料輸出至 HTML 頁面:sp_makewebtask 與 TPL 模板實戰

核心概念:TPL 模板檔案

.tpl 模板檔與 HTML 結構相同,關鍵在於三個特殊標記:

  • <%begindetail%>:資料替換起始點
  • <%enddetail%>:資料替換結束點
  • <%insert_data_here%>:資料欄位插入位置,依 SELECT 欄位順序依序替換,每欄每列僅插入一次;需重複使用時,先指派給變數再引用

實作範例:輸出供應商產品清單

1. 建立模板 OutPutHtml.tpl

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>show HTML</title>
<body>
<center><h2>
<table border="1" cellpadding="0" cellspacing="0">
  <tr>
    <th><b>公司名稱</b></th>
    <th><b>聯絡人</b></th>
    <th><b>產品名稱</b></th>
    <th><b>單價</b></th>
  </tr>
  <%begindetail%>
  <tr>
    <td><%insert_data_here%></td>
    <td align="right"><%insert_data_here%></td>
    <td align="right"><%insert_data_here%></td>
    <td align="right"><%insert_data_here%></td>
  </tr>
  <%enddetail%>
</table>
</center></h2></body></html>

2. 執行系統預存程序 sp_makewebtask

EXECUTE sp_makewebtask
  @outputfile = 'D:\SQL Server檔案\OutPutHtml.htm',
  @query = 'SELECT Suppliers.CompanyName, Suppliers.ContactName, Products.ProductName, Products.UnitPrice
            FROM Suppliers INNER JOIN Products ON Suppliers.SupplierID = Products.SupplierID
            WHERE Suppliers.SupplierID = 1',
  @templatefile = 'D:\SQL Server檔案\OutPutHtml.tpl',
  @dbname = 'NorthWind',
  @rowcnt = 0,
  @whentype = 9,
  @lastupdated = 1
GO

參數說明

參數用途
@outputfile輸出 HTML 檔案完整路徑,支援 UNC 路徑
@query要執行的 SQL 查詢,可多條 SELECT 產生多張表格
@templatefile模板檔路徑,含格式與插入標記
@dbname執行查詢的資料庫名稱
@rowcnt最大輸出列數,0 為全部
@whentype執行時機,9 = 立即建立/重建
@lastupdated1 = 顯示「上次更新時間」時間戳

SQL Server 2005+ 需額外啟用權限

sp_configure 'show advanced options', 1; RECONFIGURE;
sp_configure 'Web Assistant Procedures', 1; RECONFIGURE;

輸出結果

執行後產生 OutPutHtml.htm,模板標記已被實際資料取代,直接以瀏覽器開啟即可查看表格化報表。

應用場景

  • 定期產生靜態報表頁面
  • 無需撰寫外部程式,純 T-SQL 完成
  • 搭配排程自動更新網頁內容
copyright © 萬盛學電腦網 all rights reserved