Is there any way to configure SQL Server so that the function FileTableRootPath() returns an IP address instead of the host name?
Some of our servers are not in the domain and are accessible only by their IP address.
I think you have a few options, this should give you the IP of the SQL box:
SELECT
client_net_address = CASE WHEN client_net_address = '<local machine>'
THEN '127.0.0.1'
ELSE client_net_address
END
, local_net_address = ISNULL(local_net_address, '127.0.0.1')
, server_name = ##SERVERNAME
, machine_name = SERVERPROPERTY('MachineName')
FROM sys.dm_exec_connections
WHERE session_id = ##SPID;
or if you have xp_cmdshell enabled, you could do something like:
exec xp_cmdshell 'ipconfig'
Related
I want to connect Azure MS SQL Database with Azure Databricks via python spark. I could do this with pushdown_query if I run Select * from.... But I need to run ALTER DATABASE to scale up/down.
I must change this part
spark.read.jdbc(url=jdbcUrl, table=pushdown_query, properties=connectionProperties)
otherwise I get this error Incorrect syntax near the keyword 'ALTER'.
Anyone can help me. Much appreciated.
jdbcHostname = "xxx.database.windows.net"
jdbcDatabase = "abc"
jdbcPort = 1433
jdbcUrl = "jdbc:sqlserver://{0}:{1};database={2}".format(jdbcHostname, jdbcPort, jdbcDatabase)
connectionProperties = {
"user" : "..............",
"password" : "............",
"driver" : "com.microsoft.sqlserver.jdbc.SQLServerDriver"
}
pushdown_query = "(ALTER DATABASE [DBNAME] MODIFY (SERVICE_OBJECTIVE = 'S0')) dual_down"
df = spark.read.jdbc(url=jdbcUrl, table=pushdown_query, properties=connectionProperties)
display(df)
I have a scenario, in which I am using -q option to change the collation of SQL Server Instance. The command is as follows:
sqlservr.exe -m -T4022 -T3659 -s"SQLexpress" -q"SQL_Latin1_General_CP1_CI_AI"
The above command works perfectly, where I have an instance name as ".\SQLExpress". But if I want to use the instance name using TCP port number, such as ".,52407", then how can I execute it above command, because I get the following error:
SQL Server
Your SQL Server installation is either corrupt or has been tampered with (Error: Instance name exceeds maximum length). Please uninstall then re-run setup to correct this problem
I was thinking to get the instance name from this port number to solve this issue. Is it possible to get the instance name from TCP port number through any query? Or is there any other way to execute the above command through TCP port number?
Following piece of code can handle the above situation:
If($ServerInstanceName -like "*,*")
{
Write-Host "SQL Server Instance Name containts TCP Port Number"
$SQLQuery=#"
SET NOCOUNT ON
Declare #key Varchar(100), #PortNumber varchar(100)
if charindex('\',CONVERT(varchar(200),
SERVERPROPERTY('servername')),0<>0
begin
set #key = 'SOFTWARE\MICROSOFT\Microsoft SQL Server\'+##servicename+'\MSSQLServer\Supersocketnetlib\TCP'
end
else
begin
set #key = 'SOFTWARE\MICROSOFT\MSSQLServer\MSSQLServer\Supersocketnetlib\TCP'
end
EXEC master..xp_regread #rootkey='HKEY_LOCAL_MACHINE', #key=#key,#value_name='Tcpport',#value=#PortNumber OUTPUT
SELECT CONVERT(varchar(200), SERVERPROPERTY('servername')) AS ServerName
"#
$ServerInstanceName = (Invoke-Sqlcmd -ServerInstance
$ServerInstanceName -Database 'master' -Query $SQLQuery).ServerName
Write-Host "Compatible ServerName (without TCP Port) to change its Collation:" $ServerInstanceName
Am trying to restore the database from python 3.7 in Windows using below script.
Drop database functions correctly as expected.
The restore database doesn't work as expected, database always shows "Restoring...." and never completes.
Database files are there in the specified path, but database is not usable.
How to fix this?
import pyodbc
try:
pyconn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=MY-LAPTOP\\SQLEXPRESS;DATABASE=master;UID=sa;PWD=sa123')
cursor = pyconn.cursor()
pyconn.autocommit = True
sql = "IF EXISTS (SELECT 0 FROM sys.databases WHERE name = 'data_test') BEGIN DROP DATABASE data_test END"
pyconn.cursor().execute(sql)
sql = """RESTORE DATABASE data_test FROM DISK='G:\\dbbak\\feb-20-2020\\data_test_backup_2020_02_20_210010_3644975.bak' WITH RECOVERY,
MOVE N'Omnibus_Data' TO N'd:\\db\\data_test.mdf',
MOVE N'Omnibus_Log' TO N'd:\\db\\data_test_1.ldf';"""
print(sql)
pyconn.cursor().execute(sql)
while pyconn.cursor().nextset():
pass
pyconn.cursor().close()
except Exception as e:
print(str(e))
You're not using a single cursor, and so your program is exiting before the restore is complete, aborting it in the middle.
Should be something like:
conn = pyodbc.connect(' . . .')
conn.autocommit = True
cursor = conn.cursor()
cursor.execute(sql)
while cursor.nextset():
pass
cursor.close()
0
After hours I found solution. It must be performed no MASTER, other sessions must be terminated, DB must be set to OFFLINE, then RESTORE and then set to ONLINE again.
def backup_and_restore():
server = 'localhost,1433'
database = 'myDB'
username = 'SA'
password = 'password'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE=MASTER;UID='+username+';PWD='+ password)
cnxn.autocommit = True
def execute(cmd):
cursor = cnxn.cursor()
cursor.execute(cmd)
while cursor.nextset():
pass
cursor.close()
execute("BACKUP DATABASE [myDB] TO DISK = N'/usr/src/app/myDB.bak'")
execute("ALTER DATABASE [myDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;")
execute("ALTER DATABASE [myDB] SET OFFLINE;")
execute("RESTORE DATABASE [myDB] FROM DISK = N'/usr/src/app/myDB.bak' WITH REPLACE")
execute("ALTER DATABASE [myDB] SET ONLINE;")
execute("ALTER DATABASE [myDB] SET MULTI_USER;")
I have 3 SQL Server instances running on 3 different servers. I want to be able to automatically drop any database that has not been logged in for more than 30 days.I am trying to do this in power-shell see below code:
$SQLInstances = "sql2016", "sql2014", "sql2012"
$SQLQuery = "SELECT * FROM sys.databases WHERE name not in ('tempdb','model', 'msdb', 'master','EVN') and name not like '%report%'"
foreach($sqLInstance in $SQLInstances) {
$ListOfDatabases = Invoke-Sqlcmd -ServerInstance $sqLInstance -Database "master" -Query $SQLQuery
ForEach ($Database in $ListOfDatabases ) {
Invoke-Sqlcmd -ServerInstance $sqLInstance -Database "$Database" -Query "IF (SELECT * FROM sys.dm_exec_sessions WHERE DATEDIFF(day, LOGIN_TIME , GETDATE()) > 30 )
BEGIN
DROP DATABASE $Database
END "
}
}
I'm getting stuck on how to drop the databases. The last thing I would need is to send an email with a list of databases that will be/have been dropped.
Any suggestions on how my code should be like?
The exact thing you need is mentioned in this article.
You can find the no used DB based on the number of connections and the login time.
You can schedule it as a SQL Job, so you do not need external scheduling and powershell to manage it.
There is option to send email from within Stored Procudure. You just need to configure the SMTP details for the outgoing EMail.
https://www.mssqltips.com/sqlservertip/3171/identify-sql-server-databases-that-are-no-longer-in-use/
Using R I am trying to connect to MS SQL 2014 on an Azure VM (not windows authentication)
library(RODBC)
conn <- odbcDriverConnect(connection = "Driver=SQL Server;Server=someinternetmachine.cloudapp.net;Database=MyDatabase;Uid=MyUsername;Pwd=MyPassword;")
queryResult <- sqlQuery(conn, "SELECT top 10 * FROM sometable")
With RODBC is there anywhere to do this using just a connection string (no DSN)?
Using the above I get the below errors
Warning messages:
1: In odbcDriverConnect("driver={SQL Server};server=servername\\instancename,port;database=testing;uid=abc;pwd=123456") :
[RODBC] ERROR: state 08001, code 6, message [Microsoft][ODBC SQL Server Driver][DBNETLIB]Specified SQL server not found.
2: In odbcDriverConnect("driver={SQL Server};server=servername\\instancename,port;database=testing;uid=abc;pwd=123456") :
[RODBC] ERROR: state 01000, code 11001, message [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()).
3: In odbcDriverConnect("driver={SQL Server};server=servername\\instancename,port;database=testing;uid=abc;pwd=123456") :
ODBC connection failed
Did you choose public provisioning for the VM in Azure? Additionally, you need to open the ports for SQL Server in Windows Firewall (port number depends on default or named instance). Also, in case of named instance if you are using dynamic ports then SQL Browser also needs to be opened up. More information can be found in the link here.
Managed to get this working with
driver.name <- "SQL Server"
db.name <- "master"
host.name <- "someinternetmachine.cloudapp.net"
port <- ""
server.name <- "someinternetmachine.cloudapp.net"
user.name <- "MyUsername"
pwd <- "MyPassword"
# Use a full connection string to connect
con.text <- paste("DRIVER=", driver.name,
";Database=", db.name,
";Server=", server.name,
";Port=", port,
";PROTOCOL=TCPIP",
";UID=", user.name,
";PWD=", pwd, sep = "")
con1 <- odbcDriverConnect(con.text)
res <- sqlQuery(con1, 'select * from information_schema.tables')
odbcCloseAll()