Powershell和BTEQ工具实现带多组参数和标签的Teradata数据库批量数据导出程序

news/2025/3/4 16:30:13/

设计一个基于多个带标签SQL模板作为配置文件和多组参数的Powershell代码程序和BTEQ工具,实现根据不同的输入参数,自动批量地将Teradata数据库的数据导出为CSV文件到指定目录上,标签和多个参数(以“_”分割)为组成导出数据文件名,文件已经存在则覆盖原始文件。Powershell程序需要异常处理,输出带时间戳和每个运行批次和每个导出文件作业运行状态的日志文件,每天单独一个带日期的和.log扩展名日志文件,放在logs子目录中,参数全部设置在json配置文件中。

完整解决方案:

注意事项

  1. 确保BTEQ客户端已正确安装并配置环境变量
  2. 数据库密码以明文存储,生产环境建议使用加密方式
  3. SQL模板中的参数占位符必须与参数组数量严格匹配
  4. 建议在测试环境验证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.pathtry {$sqlTemplate = Get-Content $templatePath -Raw -ErrorAction StopWrite-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 = $sqlTemplatefor ($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 -ForceWrite-Log "[$batchId] Removed existing file: $exportFile"}$output = & bteq < $btqScriptPath 2>&1 | Out-Stringif ($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 ==="
}

使用说明

  1. 配置文件:按实际环境修改config.json中的数据库连接信息和模板配置
  2. SQL模板:在templates目录中创建.sql文件,使用{{0}}、{{1}}等占位符
  3. 执行脚本
.\Export-TeradataData.ps1 -ConfigPath .\config.json

功能特性

  1. 自动化导出:根据配置文件自动处理所有模板和参数组合
  2. 文件管理:自动覆盖已存在文件,自动创建输出目录
  3. 日志记录
    • 每天生成独立的日志文件(logs/yyyyMMdd.log)
    • 包含详细的时间戳和操作状态
    • 支持多级日志级别(INFO/ERROR/CRITICAL)
  4. 异常处理
    • 模板加载错误
    • BTEQ执行错误
    • 文件操作错误
  5. 参数化配置:支持通过JSON配置灵活管理数据库连接、模板和参数

http://www.ppmy.cn/news/1576583.html

相关文章

摄像头应用编程(四):ARM Linux LCD实时预览UVC摄像头画面

文章目录 1、前言2、环境介绍3、步骤4、应用程序编写4.1、lcd初始化4.2、摄像头初始化4.3、jpeg解码4.4、开启摄像头4.5、完整的程序如下 5、测试5.1、编译应用程序5.2、运行应用程序 6、总结 1、前言 本次应用程序主要针对支持MJPEG格式输出的UVC摄像头。 2、环境介绍 rk35…

GPT-4.5震撼登场,AI世界再掀波澜!(3)

GPT-4.5震撼登场&#xff0c;AI世界再掀波澜! GPT-4.5震撼登场&#xff0c;AI世界再掀波澜!(2) &#xff08;一&#xff09;伦理困境&#xff1a;如何抉择 GPT-4.5 的强大功能在为我们带来诸多便利的同时&#xff0c;也引发了一系列深刻的伦理问题&#xff0c;这些问题犹如高…

【pytest框架源码分析四】pluggy源码分析之hook执行

pluggy的主要执行方法在_callers.py中&#xff0c;这里简单介绍下。 def _multicall(hook_name: str,hook_impls: Sequence[HookImpl],caller_kwargs: Mapping[str, object],firstresult: bool, ) -> object | list[object]:"""Execute a call into multipl…

Unity 内置渲染管线各个Shader的用途和性能分析,以及如何修改Shader(build in shader 源码下载)

文章目录 所有Shader分析路径&#xff1a;Standard路径&#xff1a;Nature/路径&#xff1a;UI/路径&#xff1a;Particles/Particles/Standard SurfaceParticles/Standard Unlit 路径&#xff1a;Unlit/Unlit/TextureUnlit/ColorUnlit/TransparentUnlit/Transparent CutoutUnl…

android12 屏幕亮度控制修改为线性变化

由于高版本的亮度调节不是线性变化了,有客户反馈在Android11或者12上使用代码获取亮度不对,比如我们在设置中查看屏幕亮度是80%,读出来的亮度值是100,客户认为亮度值是39%。 获取屏幕亮度adb shell settings get system screen_brightness 或者 adb shell cat /sys/class…

STM32G431RBT6——(2)浅析Cortex-M4内核

本篇博客是一个对Cortex-M4内核了解性的简介&#xff0c;不会涉及到深奥的理论&#xff0c;请大家放心食用。 我们所学习的STM32G431RBT6单片机是基于ARM的Cotex-M4内核&#xff0c;因此我们有必要对此内核做一个大概了解。其实M4内核和M3内核有很大的相似之处&#xff0c;很多…

广州4399游戏25届春招游戏策划管培生内推

【热招岗位】 游戏策划管培生、产品培训生、游戏文案策划、游戏数值策划、游戏系统策划、游戏产品运营、游戏战斗策划、游戏关卡策划 【其他岗位】产品类&#xff08;产品培训生、产品运营等&#xff09;、技术类&#xff08;开发、测试、算法、运维等&#xff09;、运营市场类…

【计算机网络基础】-------计算机网络概念

1.什么是计算机网络 定义&#xff1a; 图解&#xff1a; 2.最简单的计算机网络 其中&#xff1a; 结点可以是计算机、集线器、交换机、路由器等链路可以是有线链路、无线链路 2.1集线器 2.2交换机 3.互连网&#xff08;internet&#xff09;与 路由器 路由器 与 家用路由…