Powershell invoke_sqlcmd is not closing connection - sql-server

I am using Powershell to a script to dynamically restore a database (sql server 2012).
set-location "SQLSERVER:\sql\$host_name\$inst\databases\.$db_target"
$db = Invoke-Sqlcmd -Query "select type_desc,name,physical_name from sys.master_files where database_id=db_id(N'$db_target') order by type_desc desc "
When I execute the script I get the following error message :
DBMS MSG - ODBC return code <-1>, SQL State <37000>, SQL Message
<3101><[Microsoft][SQL Server Native Client 10.0][SQL Server]Exclusive
access could not be obtained because the database is in use.>.
I then use SSMS to make the database offline
alter database [db_target] set offline with rollback immediate
After this my script works fine.
Question :
Why is invoke_sqlcmd not closing the session?
Can I execute the alter database .... command from my powershell script?
Thanks

Related

Use Invoke-Sqlcmd to run SQL script to create table in Synapse Workspace SQL Pool

I am running into issues where I am trying to run an Invoke-Sqlcmd command to run create table SQL queries. I used different ServerInstances names such as the Synapse workspace name, the Dedicated SQL, Serverless SQL and Development endpoint. I have been testing these scripts in a PowerShell CLI on the Azure Portal before moving them into an ADO pipeline.
The command that is run is as below:
Invoke-sqlcmd -Query 'CREATE TABLE #DUMMYTABLE(USERNAME varchar(50));'
-SeverInstance {endpoints or Synapse Workspace resource name} `
-Database {dedicated SQL Pool name (not master db)}
-Username {Synapse Workspace username}
-Password {Synapse Workspace password}
-QueryTimeout 36000
-Verbose
I got an error code 25 or 35 or even just a general SQL Connection String error. Any support on this would be greatly appreciated. Using the Dedicated endpoint would result in a 'cannot log in username error'.
Cheers
Getting Error because of wrong credentials.
You can get connection string from here:
from this connection string use Servername as ServerInstance and Initial Catalog as Database
Invoke-sqlcmd -Query 'CREATE TABLE DUMMY (USERNAME varchar(50));' -ServerInstance <synapseworkspacename>.sql.azuresynapse.net -Database <Inital catlog name from connection string or dedicated sql pool name> -Username <username> -Password <password> -QueryTimeout 36000 -Verbose
Output
DUMMY Database created successfully.

SQL Server could not obtain information about Windows NT group/user 'DOMAIN\user_account'

I have cloned our Microsoft SQL to a new server. The server contains a few databases and "SQL Server Agent" jobs that run on a scheduled basis. I have tried changing all existing references to this new server name and use accounts on this new server. However I am still getting the following error in my error log and my jobs fails to run (btw, this is through Microsoft SQL Management Studio),
[298] SQLServer Error: 15404, Could not obtain information about Windows NT group/user 'DOMAIN\user_account', error code 0x534. [SQLSTATE 42000] (ConnIsLoginSysAdmin)
I've got a couple of Maintenance Plans which are pointing to the old server. For some unknown reason I can't edit the existing connection and I can't delete it. I can add a new one but the other connection can not be removed.
I need to know where I need to change for this error to go away and the jobs start running.
This may be because SQL has the wrong server name in Master. Here is another article on the subject.
SQL Server Central Article
In order to fix this, run a search on Master with the following code:
use master
select SERVERPROPERTY('servername')
select ##SERVERNAME
select SERVERPROPERTY('machinename')
go
If you see the old server name in the list you will have to drop the server and add the new one
use master
exec sp_dropserver "OldServerNmae"
go
use master
exec sp_addserver "NewServerName","local"
go

AzureSQL- Could not find stored procedure 'sp_configure' while installing Sitecore9.1

I am installing Sitecore9.1 with powershell using Azure SQL server and databases. While running script, it creates databases and while creating/updating MarketingAutomation databases it is giving error about 'contained database authentication'
error is - The command started with the following:
"exec sp_configure 'contained database authenticati"
Could not find stored procedure 'sp_configure'.
Install-SitecoreConfiguration : Command C:\Program Files\iis\Microsoft Web Deploy V3\msdeploy.exe returned a non-zero exit code - (-1)
I am running below command to Azure SQL server for this issue:
sp_configure 'contained database authentication', 1;
GO
RECONFIGURE;
GO
but while executing it throws error about syntax.
I could not find commands for AzureSQL or SQL2017 for contained database authentication.
I want commands for contained database authentication for Azure SQL.Please help.
sp_configure is not available on Azure SQL Database and you should use ALTER DATABASE SCOPED CONFIGURATION instead to configure Azure SQL Database options and parameters.
The following query should tell which databases have contained database authentication enabled.
select [name] as databasename, containment, containment_desc from sys.databases
As you can read on this documentation, the containment value of zero applies to Azure SQL Database, but value1 cannot be set on Azure SQL Database. However you can create contained database users on Azure SQL Database without the need to enable containment, and the contained database user model is the recommended model instead of the traditional connection model as mentioned here.

bcp error with sql server

I have created a stored procedure in sql server 2005 to export data from a query to a network path. The user is a sql user and it is also created in the AD. The server that I am logged in is a remote server, with sysadmin privilege. I am encountering the following error while executing the procedure or even the query:
output
SQLState = 08001, NativeError = 53
Error = [Microsoft][SQL Native Client]Named Pipes Provider: Could not open a connection to SQL Server [53].
SQLState = 08001, NativeError = 53
Error = [Microsoft][SQL Native Client]An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
SQLState = S1T00, NativeError = 0
Error = [Microsoft][SQL Native Client]Login timeout expired
NULL
It looks like I have no access to the remote server, while I am executing the query while I am logged in the server. The procedure also executes automatically at 01.30 am. The command that is executed is a bcp command :
DECLARE #SQLCommand [varchar](max)
,#Query [varchar](max)
,#SERVER VARCHAR(1000)
SET #Query = 'SELECT * FROM INFINITY_SYSTEM.[dbo].[CTI_WFM_LILO_View]'
SET #SERVER = '[server_name]'
SET #SQLCommand = 'EXEC xp_cmdshell ''bcp "' + #Query + '" queryout "\\network_path\lilo'+CONVERT(VARCHAR,GETDATE(),112)+'.csv" -Uusername -Ppassword -c -t, -r, -S"'+#SERVER+'"''' --also tried with -T in stand of the -Uusername -Ppassword
EXEC (#SQLCommand)
The command works when I try it from a local DB in my local sqlserver to the same path.
Thanks
Make sure that you can telnet to the remote server. I would also try to connect to the remote server via sqlcmd. You may have a firewall blocking the connection. Also the sql server services will need permissions to the share/directory, in order for you to write a file to it.
Another thing you should consider is using an SSIS package to export the data to the remote share. Generally is not a great practice to use xp_cmdshell to export the data. You can do everything you are trying to do via a simple SSIS package. As an added benefit this also minimizes security risk because you can disable xp_cmdshell.

SQL Server: Database stuck in “Restoring” state with PHP

I tried to backup my database following the instruction from SQL Server: Database stuck in "Restoring" state. but i have my database stuck in "Restoring" state. php code below:
$database = "container";
$uid = "sa";
$pwd = "12345" ;
try {
$conn = new PDO( "sqlsrv:Server=localhost\SQLEXPRESS;Database=$database",
$uid,
$pwd
//,array(PDO::ATTR_PERSISTENT => true)
);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); }
catch( PDOException $e ) {
die( "Error connecting to SQL Server" ); }
echo "Connected to SQL Server\n";
$backfile = 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\sql server bk' ;
echo "Connected to SQL Server\n";
$backfile = 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\sql server bk' ;
$query = "RESTORE DATABASE child_database FROM DISK = '$backfile' WITH REPLACE, RECOVERY ";
$conn->exec($query);
After running this code I got my child_database stuck in restoring state.however I copy the sql command
RESTORE DATABASE child_database FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\sql server bk' WITH REPLACE, RECOVERY
and run in microsoft sql server management tool it works just fine.
I try to run add php code
$conn->exec("RESTORE DATABASE child_database WITH RECOVERY");
I got an exception.
please help.
It seems have problem with PDO driver, this problem may be in the ODBC/SNAC layer on which the driver is built. But this database restoring works well with other drivers.
I tried with sqlsrv and mssql, they worked well.
For more detail, see Restoring a SQL Server Database from PHP

Resources