更新查询中的案例声明

时间:2015-12-01 15:09:00

标签: powershell powershell-ise

这适用于SQL Server,但是当我尝试在我的PowerShell环境中运行它时,它会在d附近给出错误的语法错误。为了让这个在PowerShell中运行,我必须改变什么?

Function Run-Query
{
    param([string[]]$queries)

        $server='Server'
        $dbname='Database'
        $connStr='Server={0};Database={1};Integrated Security=SSPI;' -f $server,$dbname
        For ($i = 0; $i -lt $queries.count; $i++)
        {
            $Command = New-Object System.Data.SqlClient.SqlCommand
            $conn=New-Object System.Data.SqlClient.SQLConnection($connStr)
            $conn.Open()            
            $Command.Connection = $conn
            $Command.CommandText=$queries[$i]
            $Command.ExecuteNonQuery() 
            $conn.Close()
        }
}

$updatequery = "UPDATE d
                 SET [updatedate] = GETDate(),
                 [shipped] =
                         (
                            CASE WHEN NOT EXISTS(Select 1 *
                                                 from [server].[db].[dbo].[viewname] vw
                                                 WHERE vw.customername = d.customername)                    
                                THEN 'Yes'
                            ELSE
                                'PreviousCustomer'
                            END
                         )
                 FROM $fulllocation
                 WHERE ([shipped] IS NULL) 
                 AND ([managerapproved] IS NOT NULL)  
                 AND [readytoship] IN ('Go', 'Ready', 'Send')"


 Run-Query -queries $updatequery

1 个答案:

答案 0 :(得分:0)

将查询定义为字符串文字,如下所示:

$updatequery = @"
                     UPDATE d
                     SET [updatedate] = GETDate(),
                     [shipped] =
                             (
                                CASE WHEN NOT EXISTS(Select 1 
                                                     from [server].[db].[dbo].[viewname] vw
                                                     WHERE vw.customername = d.customername)                    
                                    THEN 'Yes'
                                ELSE
                                    'PreviousCustomer'
                                END
                             )
                     FROM $fulllocation
                     WHERE ([shipped] IS NULL) 
                     AND ([managerapproved] IS NOT NULL)  
                     AND [readytoship] IN ('Go', 'Ready', 'Send')
"@