如何使用PowerShell脚本从SQL Server中的表中删除行?

时间:2017-12-03 09:18:16

标签: sql-server powershell powershell-v3.0 powershell-v4.0

{{1}}

我在远程服务器上安装了SQL Server 2012,并且我想从使用PowerShell脚本的本地计算机中删除特定数据库中特定表的行。有可能这样做吗?

2 个答案:

答案 0 :(得分:2)

一种方法是使用ADO.NET对象,就像在任何.NET应用程序中一样。下面的PowerShell示例并不需要安装SQL工具。

要使用Windows身份验证执行查询,请在连接字符串中指定Integrated Security=SSPI

$connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=SSPI";
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString);
$command = New-Object System.Data.SqlClient.SqlCommand("DELETE FROM dbo.YourTable WHERE YourTableID = 1", $connection);
$connection.Open();
$rowsDeleted = $command.ExecuteNonQuery();
Write-Host "$rowsDeleted rows deleted";
$connection.Close();

要使用SQL身份验证执行查询,请在连接字符串中指定User ID=YourSqlLogin;Password=YourSqlLoginPassword

$connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;User ID=YourSqlLogin;Password=YourSqlLoginPassword";
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString);
$command = New-Object System.Data.SqlClient.SqlCommand("DELETE FROM dbo.YourTable WHERE YourTableID = 1", $connection);
$connection.Open();
$rowsDeleted = $command.ExecuteNonQuery();
Write-Host "$rowsDeleted rows deleted";
$connection.Close();

在任何一种情况下,都需要DELETE表的权限。

我不确定您添加到问题中的脚本中NET USE命令的用途,除非是在工作组环境中对服务器进行身份验证。就个人而言,我只会使用SQL身份验证并删除NET USE丑陋。

修改

如果同一批次中有多个SELECT语句,则每个语句都会返回一个单独的记录集。如果您使用NextRecordset,则需要调用DataReader,当没有更多记录集可用时,将返回false:

$reader = $command.ExecuteReader();
do {
    While($reader.Read()) {
        #process row here;
    }
} while($reader.NextResult());

或者,您可以使用DataAdapter填充数据集'。对于每个结果集,DataSet将包含单独的DataTable

$da = New-Object System.Data.SqlClient.SqlDataAdapter($command);
$ds = New-Object System.Data.DataSet;
$null = $da.Fill($ds);
foreach($dt in $ds.Tables) {
    $dt | Out-GridView;
}

如果列数和数据类型相同,您还可以使用UNION ALL调整SQL查询以将结果连接到单个结果集。这是一个示例代码段:

$sqlQuery = @("
SELECT *
FROM DB926.dbo.Version_Solution 
WHERE Notes ='9.2.7'
UNION ALL
SELECT *
FROM DB_926.dbo.Version_Solution
WHERE Notes ='9.2.7'";
);
$command = New-Object System.Data.SqlClient.SqlCommand($sqlQuery, $connection);

答案 1 :(得分:1)

更改您的代码:

$uncServer = "\\10.243.174.102\e$"
$uncFullPath = "$uncServer\New folder\Demo.txt"
$username = "XYZ"
$password = "xyz"

net use $uncServer $password /USER:$username


$SQLServer = "AP-PUN-SRSTEP29\MSSQLSERVER12" #use Server\Instance for named SQL instances! 
$SQLDBName = "SystemDB"
$SqlQuery = "Delete from V_Solution WHERE Notes ='9.4.4'";

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True"
$SqlConnection.open()


$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection

$SqlCmd.ExecuteNonQuery
$SqlConnection.Close()