Powershell和SQL:如何在变量中存储查询的值?

时间:2017-12-27 08:42:41

标签: sql sql-server powershell

我编写了一个运行两个SQL查询的powershell脚本,将结果保存在2个变量中并进行比较。如果结果彼此不同,我会收到一封电子邮件 但是,我注意到结果总是一样的。当我写这两个变量时,我得到了这个:Happiness <- c(0, 80, 39, 0, 69, 90, 100, 30) City <- as.factor(c("New York", "Chicago", "Chicago", "New York", "Chicago", "Chicago", "New York", "New York")) Gender <- as.factor(c(0, 1, 0, 1, 1, 1, 0, 1)) # 0 = man, 1 = woman. Employment <- c(0,1, 0, 0, 1 ,1 , 1 , 1) # 0 = unemployed, 1 = employed. Worktype <- as.factor(c(0, 2, 0, 0, 1, 1, 2,2)) levels(Worktype) <- c("Unemployed", "Bluecolor", "Whitecolor") Holiday <- as.factor(c(0, 1, 0, 0, 2, 2, 2, 1)) levels(Holiday) <- c("Unemployed", "1 day a week", "2 day a week") data <- data.frame(Happiness, City, Gender, Employment, Worktype, Holiday) reg <- lm(Happiness ~ City + Gender + Employment:Worktype + Employment:Holiday) summary(reg) install.packages("censReg") library(censReg) tobitreg <- censReg(Happiness ~ City + Gender + Employment:Worktype + Employment:Holiday) summary(tobitreg) 。我假设当我比较这两个变量时,我实际上是将System.Data.DataRowSystem.Data.DataRow进行比较。

我使用的IF非常简单:

System.Data.DataRow

我做错了,还是有办法将SQL查询的实际值存储在变量中? 当我写输出变量时,我得到:

if ($resultDB = $resultCube) {$SMTPClient.Send( $emailMessageSuccess )} ELSE {$SMTPClient.Send( $emailMessageFailure )}

这个数字正是我要找的。

1 个答案:

答案 0 :(得分:3)

这种情况发生了,因为赋值和比较运算符是混合的。在Powershell中,=是赋值,-eq是相等的。因此,

if ($resultDB = $resultCube) { ... }

被解析为

if $resultCube was assigned into $resultDB without any issues, do...

如果您想知道赋值如何失败,请考虑只读变量:

New-Variable -Name myConstant -Value 1
$myConstant
1
if($myConstant = 2) { "aye"} else { "nay" } # Try and assign new value
aye
$myConstant # It works
2
Remove-Variable -Name myconstant
New-Variable -Name myConstant -Value 1 -Option readonly # Now, let's try with a read-only variable
if($myConstant = 2) { "aye"} else { "nay" } # Kaboom!
Cannot overwrite variable myConstant because it is read-only or constant.
At line:1 char:4
+ if($myConstant = 2) { "aye"} else { "nay" }
+    ~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (myConstant:String) [], SessionStateUnauthorizedAccessException
    + FullyQualifiedErrorId : VariableNotWritable

如何比较列值,尝试类似的东西

if ($resultDB["myColumn"] -eq $resultCube["myColumn"]) { ... }