Powershell和BTEQ工具实现带多组参数和标签的Teradata数据库批量数据导出程序
设计一个基于多个带标签SQL模板作为配置文件和多组参数的Powershell代码程序和BTEQ工具,实现根据不同的输入参数,自动批量地将Teradata数据库的数据导出为CSV文件到指定目录上,标签和多个参数(以“_”分割)为组成导出数据文件名,文件已经存在则覆盖原始文件。Powershell程序需要异常处理,输出带时间戳和每个运行批次和每个导出文件作业运行状态的日志文件,每天单独一个带日期的和.log扩展名日志文件,放在logs子目录中,参数全部设置在json配置文件中。
完整解决方案:
注意事项
- 确保BTEQ客户端已正确安装并配置环境变量
- 数据库密码以明文存储,生产环境建议使用加密方式
- SQL模板中的参数占位符必须与参数组数量严格匹配
- 建议在测试环境验证SQL模板和参数组合的正确性
文件结构
├── config.json
├── Export-TeradataData.ps1
├── templates/
│ └── sales.sql
├── logs/
│ └── 20231015.log
└── exports/
├── SalesReport_2023_Q4.csv
└── SalesReport_2023_Q3.csv
config.json
{
"database": {
"host": "teradata.server.com",
"username": "myuser",
"password": "mypassword"
},
"templates": [
{
"label": "SalesReport",
"path": "templates/sales.sql",
"parameters": [
["2023", "Q4"],
["2023", "Q3"]
]
}
],
"export_directory": "exports",
"log_directory": "logs"
}
templates/sales.sql
SELECT * FROM Sales
WHERE Year = {{0}}
AND Quarter = {{1}};
Export-TeradataData.ps1
<#
.SYNOPSIS
Automated Teradata data export tool using BTEQ
.DESCRIPTION
This script executes parameterized SQL templates against Teradata and exports results to CSV files.
#>
param(
[Parameter(Mandatory=$true)]
[string]$ConfigPath = "config.json"
)
# 初始化配置
$config = Get-Content $ConfigPath -Raw | ConvertFrom-Json
# 创建必要目录
New-Item -ItemType Directory -Path $config.export_directory -Force | Out-Null
New-Item -ItemType Directory -Path $config.log_directory -Force | Out-Null
# 初始化日志
$logDate = Get-Date -Format "yyyyMMdd"
$logFile = Join-Path $config.log_directory "$logDate.log"
function Write-Log {
param(
[string]$Message,
[string]$Level = "INFO"
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "[$timestamp][$Level] $Message"
Add-Content -Path $logFile -Value $logEntry
}
Write-Log "=== Script Start ==="
# 主处理逻辑
try {
foreach ($template in $config.templates) {
$label = $template.label
$templatePath = $template.path
try {
$sqlTemplate = Get-Content $templatePath -Raw -ErrorAction Stop
Write-Log "Loaded template: $label"
} catch {
Write-Log "Error loading template [$label]: $_" -Level "ERROR"
continue
}
foreach ($paramGroup in $template.parameters) {
$batchId = [guid]::NewGuid().ToString().Substring(0,8)
$paramString = $paramGroup -join "_"
$exportFile = "${label}_${paramString}.csv"
$exportPath = Join-Path $config.export_directory $exportFile
# 参数替换
$sqlQuery = $sqlTemplate
for ($i=0; $i -lt $paramGroup.Count; $i++) {
$sqlQuery = $sqlQuery -replace "\{\{$i\}\}", $paramGroup[$i]
}
# 生成BTEQ脚本
$btqScript = @"
.LOGON $($config.database.host)/$($config.database.username),$($config.database.password)
.set separator ','
.set titledashes off
.set format off
.EXPORT REPORT FILE=$exportPath
;
$sqlQuery
;
.IF ERRORCODE <> 0 THEN .QUIT ERRORCODE
.EXPORT RESET
.LOGOFF
.QUIT 0
"@
$btqScriptPath = [System.IO.Path]::GetTempFileName()
Set-Content -Path $btqScriptPath -Value $btqScript
# 执行导出
try {
Write-Log "[$batchId] Starting export: $exportFile"
if (Test-Path $exportPath) {
Remove-Item $exportPath -Force
Write-Log "[$batchId] Removed existing file: $exportFile"
}
$output = & bteq < $btqScriptPath 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
throw "BTEQ Error ($LASTEXITCODE): $output"
}
Write-Log "[$batchId] Successfully exported: $exportFile"
} catch {
Write-Log "[$batchId] Export failed: $_" -Level "ERROR"
} finally {
Remove-Item $btqScriptPath -ErrorAction SilentlyContinue
}
}
}
} catch {
Write-Log "Fatal error: $_" -Level "CRITICAL"
} finally {
Write-Log "=== Script End ==="
}
使用说明
- 配置文件:按实际环境修改config.json中的数据库连接信息和模板配置
- SQL模板:在templates目录中创建.sql文件,使用{{0}}、{{1}}等占位符
- 执行脚本:
.\Export-TeradataData.ps1 -ConfigPath .\config.json
功能特性
- 自动化导出:根据配置文件自动处理所有模板和参数组合
- 文件管理:自动覆盖已存在文件,自动创建输出目录
- 日志记录:
- 每天生成独立的日志文件(logs/yyyyMMdd.log)
- 包含详细的时间戳和操作状态
- 支持多级日志级别(INFO/ERROR/CRITICAL)
- 异常处理:
- 模板加载错误
- BTEQ执行错误
- 文件操作错误
- 参数化配置:支持通过JSON配置灵活管理数据库连接、模板和参数