Exception calling ExecuteNonQuery in PowerShell to Azure PaaS database - sql-server

I'm having an odd issue using the System.Data.SqlClient in PowerShell. The following works, using MSSMS:
INSERT INTO [dbo].[secDb_AADDevices]
([objectGuid]
,[displayName]
,[deviceGuid])
VALUES
('test','here','now')
But when doing this in PowerShell:
$sqlQuery = "INSERT INTO secDb_AADDevices ('objectGuid','displayName','deviceGuid') VALUES('test','here','now')"
$sqlCmd=new-object system.Data.SqlClient.SqlCommand($sqlQuery, $sqlConn)
$sqlCmd.ExecuteNonQuery()
It fails;
Exception calling "ExecuteNonQuery" with "0" argument(s): "Invalid column name 'objectGuid'.
Invalid column name 'displayName'.
Invalid column name 'deviceGuid'."
At line:4 char:1
+ $sqlCmd.ExecuteNonQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
The column types in MSSQL are nvarchar(50) not null.
I've simplified it as much as possible to reduce complexity while debugging, will parameterize when this part works.
I've triple-verified that MSSQL and PowerShell ($sqlConn object) are connected to the same server and database instance, using the exact same user.

Related

SQL ExecuteReader throws "Incorrect syntax near GO"

I use a T-SQL command which I found here to get the fragmentation of my database tables. When I execute the T-SQL in the Management Studio, everything works. If I use it inside PowerShell, I get the following error (translated from German):
Exception when calling "ExecuteReader" with 0 Argument(s):
"Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'."
In Zeile:17 Zeichen:6
+ $Result = $cmd.ExecuteReader()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
This is the part of my script which throws the error
foreach ($table in $tables)
{
$Data = New-Object System.Data.DataTable
$cmd = New-Object System.Data.SqlClient.SqlCommand
$getFragRate = "
-- SQL Command von Microsoft um die Index Fragmentation zu überprüfen
USE Logik;
GO
SELECT a.index_id, name, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (DB_ID(N'Logik'), OBJECT_ID(N'$($table)'), NULL, NULL, NULL) AS a
JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id;
GO
"
$cmd.CommandText = $getFragRate
$cmd.Connection = $con
$Result = $cmd.ExecuteReader()
$Data.Load($Result)
$Data
}
Why does this error occur?
The User I use to do this has sysadmin, db_ddladmin and db_owner permission.
Edit: Another T-SQL Command to get all tables of my database worked without a problem from PowerShell.
GO is NOT a T-SQL command - therefore you cannot have it in T-SQL statements being executed from PowerShell.
GO is a batch separator used by SQL Server Management Studio.
You need to break up that statement into several individual statements yourself and execute them one by one.

Trying to get the status of mirrored databases using powershell

I am trying to test the following script in powershell which gets the status of the mirrored databases.
#SQL Variables
$sqlservers = "APNSQL01"
#SQL database mirroring status
$body +=echo "------------Originating Server-----------"`r`n""`r`n""
Import-Module "sqlps" -DisableNameChecking
$body +=echo "--------Status of mirrored databases---------"`r`n""`r`n""
foreach ($server in $sqlservers){
$body +=echo "Database mirroring state on $server
"
$body += Invoke-Sqlcmd -Query "USE master
SELECT sys.database_mirroring.mirroring_state_desc
,sys.databases.name
FROM sys.database_mirroring INNER JOIN sys.databases ON sys.database_mirroring.database_id=sys.databases.database_id
WHERE mirroring_state_desc IS NOT NULL" -ServerInstance "$server" | out-string
}
When I run this code, I get the following error :
Invoke-Sqlcmd : A network-related or instance-specific error occurred while establishing a connection to SQL Server.
The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is
configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to
SQL Server)
At C:\Users\ctxadmin\Desktop\SQL.ps1:20 char:11
+ $body += Invoke-Sqlcmd -Query "USE master
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException
+ FullyQualifiedErrorId : SqlExectionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
Invoke-Sqlcmd :
At C:\Users\ctxadmin\Desktop\SQL.ps1:20 char:11
+ $body += Invoke-Sqlcmd -Query "USE master
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Sqlcmd], ParserException
+ FullyQualifiedErrorId : ExecutionFailureException,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
My SQL server is a STANDARD database. It has no mirror. Is that the issue?
What might the error be?

What is the correct way to add a string to SQL Server field of type char[x]?

I am writing a script in PowerShell to utilize a stored procedure in my SQL Server 2000 database. To utilize the stored procedure w/ params I use the AddWithValue() method for sqlcmd.Parameters. I am attempting to insert a string into a column with data type char of size 8. I have been playing around with the AddWithValue() method, but I keep getting one of the two following errors:
Cannot convert value "aamstest" to type "System.Char". Error: "String must be exactly one character long."
At D:\scripts\SCADAViewBulkAdd\scadaview_bulk_add.ps1:196 char:2
+ $SqlCmd.Paramters.AddWithValue("#USNAME",[char]$USNAME);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastParseTargetInvocation
You cannot call a method on a null-valued expression.
At D:\scripts\SCADAViewBulkAdd\scadaview_bulk_add.ps1:197 char:2
+ $SqlCmd.Paramters.AddWithValue("#GRNAME",$GRNAME);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Stored procedure:
CREATE PROCEDURE spAddUserToGroup
#USNAME char(8), #GRNAME char(8)
AS
BEGIN
INSERT INTO GLOBE_USER_GROUP
VALUES (#USNAME, #GRNAME)
END
GO
AddWithValue() called from here:
# Call SQL Stored Procedure spAddUserToGroup
function SpAddUserToGroup ($usnameParam,$grnameParam)
{
$SqlConnection = New-Object System.DATA.SqlClient.SqlConnection;
$SqlConnection.ConnectionString = "SERVER=server01;DATABASE=FIGDB;UID=y;PWD=y";
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand;
# Indicate working with stored procedure
$SqlCmd.CommandType=[System.Data.CommandType]'StoredProcedure';
# Supply name of stored procedure
$SqlCmd.CommandText = "spAddUserToGroup";
$SqlCmd.Connection = $SqlConnection;
# Set stored procedure parameters
$USNAME = $usnameParam;
$GRNAME = $grnameParam;
Write-Host $USNAME
Write-Host $GRNAME
# Add parameters to string
$SqlCmd.Paramters.AddWithValue("#USNAME",[char]$USNAME);
$SqlCmd.Paramters.AddWithValue("#GRNAME",$GRNAME);
# Initialize SQL Adapter
#$SqlAdapter = New-Object System.Data.SqlClient.SqlAdapter;
#$SqlAdapter.SelectCommand = $SqlCmd;
...
}
Question: how can I utilize the stored procedure to insert a string into a column of type char[8] with PowerShell? Are my errors a result of calling AddWithValue() incorrectly or am I handling my variable types poorly?
New Answer
Turns out you can specify the parameter names, but you don't have to. I think your actual issue here is that you've spelled Parameter wrong, which is why SQL Isn't accepting your input.
Change your code to this, and it should work.
$SqlCmd.Parameters.AddWithValue("#USNAME",[char]$USNAME);
$SqlCmd.Parameters.AddWithValue("#GRNAME",$GRNAME);
Old Answer, Wrong
I don't think you are supposed to specify the parameter name when you call a stored procedure. Try this instead:
Change these two lines:
$SqlCmd.Paramters.AddWithValue("#USNAME",[char]$USNAME);
$SqlCmd.Paramters.AddWithValue("#GRNAME",$GRNAME);
To this:
$SqlCmd.Paramters.AddWithValue([char]$USNAME,$GRNAME)
Also, PowerShell doesn't require line ending characters, like a semicolon.

How can I find failure reason for creating Sql Job in Powershell

I have a PowerShell script to create a Sql Job. I have used this script before but for some reason this time it is not working. I don't know how to find the failure reason. I only get this error message:
Exception calling "Create" with "0" argument(s): "Create failed for
Job 'UBASS_LMS - FullSyncCorrespondence'. " At line:75 char:13
+ $job.Create()
+ ~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FailedOperationException
Can I enable anything to see this during the powershell execution? or can this be viewed somewhere in msdb?

powershell set database IndexOutOfRangeException

I'm trying to set a database name in powershell using Microsoft.SqlServer.SMO. When I execute my script it runs in error with the following error text:
format-default : Index was outside the bounds of the array.
+ CategoryInfo : NotSpecified: (:) [format-default], IndexOutOfRangeException
+ FullyQualifiedErrorId : System.IndexOutOfRangeException,Microsoft.PowerShell.Commands.FormatDefaultCommand
The server is set as follows
$srv = New-Object "Microsoft.SqlServer.Management.SMO.Server" $server
$srv.ConnectionContext.LoginSecure=$false;
$srv.ConnectionContext.set_Login("login");
$srv.ConnectionContext.set_Password("password")
$srv.Databases | Select name,
shows me the proper databases, but when setting the database,
$db = $srv.Databases[$database]
the error is thrown.
This scrip does work in other sqlservers.
Any solutions for this issue?
It looks like the database "CRD_DEV" does not exist on the server where the script throws the error.
That or the user does not have access to that database.
The IndexOutOfRangeException is thrown because there is no item in $srv.Databases that matches "CRD_DEV"

Resources