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

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd

I have SQL Server 2012 installed on a remote server and I want to delete a row from a particular table in a specific database, from a local machine using a PowerShell script. Is is possible to do that?

2
  • 2
    SO doesnt work for you, what is you code? What have you tried? Commented Dec 3, 2017 at 10:30
  • Hey hi esperento, Actually i didn't had the code with me at that time so i could not upload it but now i have edited the question and uploaded the code as well which i tried by searching on google but it doesn't work, so could please help me with it. Commented Dec 4, 2017 at 5:32

2 Answers 2

2

One method is using ADO.NET objects as you would in any .NET application. The PowerShell example below doesn't require SQL tools to be installed.

To execute the query using Windows authentication, specify Integrated Security=SSPI in the connection string:

$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();

To execute the query using SQL authentication, specify User ID=YourSqlLogin;Password=YourSqlLoginPassword in the connection string.

$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();

In either case, DELETE permissions on the table are required.

I'm not sure of the purpose of the NET USE command in the script you added to your question, unless that is to authenticate to the server in a workgroup environment. Personally, I would just use SQL authentication and remove the NET USE ugliness.

EDIT:

In the case of multiple SELECT statements in the same batch, each will return a separate recordset. This will require invoking NextRecordset if you are using a DataReader, which will return false when no more recordsets are available:

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

Alternatively, you could use a DataAdapter to fill a 'DataSet'. The DataSet will contain a separate DataTable for each resultset:

$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;
}

You could also tweak your SQL query to concatenate the results into a single resultset using UNION ALL if the number of columns and data types are identical. Here's an example snippet:

$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);
Sign up to request clarification or add additional context in comments.

7 Comments

Same error occurs while using the above code as well mentioned in the comment above.
Yes, Even i added the user id and password in connection string and tried it and also removed the unwanted code of NET USE which i thought would be needed because the SQLServer is installed on remote machine and after all this changes code was working perfectly, anyways thank you for your help :-)
Hi Dan Guzman, Is it possible to delete the entry from a Table present in two different databases? , like i tried giving two different database name for eg- Initial Catalog="DB1","DB2" but it is giving me error. How should i add a code for another Database instead of repeating the same code again for deleting entry from other DB aswell.
@SRP, if you databases are on the same server, qualify the table names with the database name and execute multiple DELETE statements in the same batch: DELETE FROM DB1.dbo.YourTable WHERE YourTableID = 1;DELETE FROM DB2.dbo.YourTable WHERE YourTableID = 1;
It worked for delete statement but for Select statement it does not work, for select statement is their any another syntax? This the statement i have added in the code "Select * from DB926.dbo.Version_Solution WHERE Notes ='9.2.7';Select * from DB_926.dbo.Version_Solution WHERE Notes ='9.2.7'"
|
1

Change your code like this :

$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()

7 Comments

Hi Esperento57, the above code is giving exception at "$SqlConnection.open()" saying Exception calling "Open" with "0" argument(s) "Login failed for user 'XYZ' . I think i also need to give username and password for SqlServer as well. The above username and password is for Remote machine where SQLServer is installed. If i need to give credentials of SQLServer as well then where and how should i give it?
Hi Esperento57, Is it possible to delete the entry from a Table present in two different databases? , like i tried giving two different database name for eg- Initial Catalog="DB1","DB2" but it is giving me error. How should i add a code for another Database instead of repeating the same code again for deleting entry from other DB aswell.
No, It is possible to delete, the above answer given by Dan Guzman in comments worked successfully it deleted the entries from tables present in two different databases and the databases were on the same server.
Its okay Sir :-), But the select statement doesn't seem to run on the same server for tables in two database.
select or delete? Do you want join 2 tables ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.