You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中如何将变量/数组成员正确传入SQL查询语句?

问题根因

PowerShell对双引号内的变量插值有默认解析规则:仅会识别$后紧跟的合法变量名部分,不会自动解析后续.连接的对象成员访问逻辑。
你代码中写的$date.month,插值时只会将$date(DateTime类型对象)转换为默认格式的字符串拼入SQL,后续.month会被当作普通SQL文本保留,最终生成的SQL语句语法完全不符合预期,执行必然报错。


可行解决方案

1. 修正字符串插值写法(快速修复)

如果要在双引号字符串中直接嵌入对象的属性/方法返回值,需要将整个变量访问逻辑用$()子表达式运算符包裹,强制PowerShell先计算子表达式的结果,再拼入字符串:

$date = Get-Date
$sql = "SELECT *
  FROM [database].[dbo].[table]
  where ([MONTH] = $($date.Month) and [YEAR] = $($date.Year))"

修正后插值时会正确取到$date.Month、$date.Year的整型数值,不会出现语法破碎问题。

2. 参数化查询(生产环境推荐)

直接拼接SQL语句存在SQL注入风险,也无需额外记忆字符串插值规则,标准数据库访问写法应使用参数传值:

$ConnectionString = "Server=" + $TargetServer + ";Database=" + $TargetDatabase + ";Trusted_Connection=$true;";
$TargetConnection = New-Object System.Data.SqlClient.SqlConnection($ConnectionString);
$TargetConnection.Open();

$date = Get-Date

# SQL文本中用@参数名做占位符,不直接拼接值
$sql = "SELECT *
  FROM [database].[dbo].[table]
  where ([MONTH] = @QueryMonth and [YEAR] = @QueryYear)"

$TargetCommand = New-Object System.Data.SqlClient.SqlCommand($sql, $TargetConnection);
# 绑定参数值,自动匹配类型
$TargetCommand.Parameters.AddWithValue("@QueryMonth", $date.Month) | Out-Null
$TargetCommand.Parameters.AddWithValue("@QueryYear", $date.Year) | Out-Null

$TargetCommand.ExecuteScalar()
$TargetConnection.Close()

这种写法完全规避了SQL语法拼接错误、SQL注入的问题,是数据库查询的规范实现方式。


内容的提问来源于stack exchange,提问作者mouseskowitz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 03:57:32