代码之家  ›  专栏  ›  技术社区  ›  Stefan0309

如何在SQL Invoke命令中实现Where对象

  •  0
  • Stefan0309  · 技术社区  · 6 年前

    我正在尝试从解决方案文件夹中的数据库中筛选一些表。我想筛选从SQL Server提取的所有表:

    $existingTables = "Table1", "Table2", "Table3", "Table4"
    
    #getting all tables except existing ones
    #SqlQuery = "SELECT name FROM sys.Tables order by name asc"
    $filteredTables = ((Invoke-SQL -DataSource $ServerName -DatabaseName $DatabaseName -UserID $UserID -Password $Password -SqlCommand $SQLQuery).name | ? {$_ -notcontains $existingTables})
    #$filteredTables returns all tables, including the existing ones...
    

    我试过了 $_.name 这是同样的结果。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Ansgar Wiechers    6 年前

    您正在使用 -notcontains operator 按错误的顺序。正确的语法是

    reference_array -notcontains item
    

    就你而言:

    $existingTables -notcontains $_
    

    $existingTables -notcontains $_.Name
    

    Name .

    -notin operator :

    $_ -notin $existingTables
    

    但是,该操作员在PowerShell v3之前不可用。

    或者,您可以向SQL语句中添加一个exclude子句,如下所示 @vonPryz 在评论中建议。当心不要向别人敞开心扉 SQL injection

    不要

    $SQLQuery = @"
    SELECT ...
    FROM ...
    WHERE name NOT IN ('$($existingTables[0])', '$($existingTables[1])', ...)
    "@

    使用 prepared statement (或者微软称之为“参数化查询”)。但是,我不认识您正在使用的cmdlet(似乎不认识) Invoke-Sqlcmd