Rename SQL Azure database? - tsql

How can i rename the database in sql Azure?
I have tried Alter database old_name {MODIFY NAME = new_name} but not worked.
Is this feature available in SQL Azure or not?

Just so people don't have to search through the comments to find this... Use:
ALTER DATABASE [dbname] MODIFY NAME = [newdbname]
(Make sure you include the square brackets around both database names.)

Please check that you've connected to master database and you not trying to rename system database.
Please find more info here: https://msdn.microsoft.com/en-US/library/ms345378.aspx

You can also connect with SQL Server Management Studio and rename it in Object Explorer. I just did so and the Azure Portal reflected the change immediately.
Do this by clicking on the database name (as the rename option from the dropdown will be greyed out)

Connect with SQL Server Management Studio to your Azure database server, right-click on the master database and select 'New Query'. In the New Query window that will open type ALTER DATABASE [dbname] MODIFY NAME = [newdbname].

It's Very simple for now - Connect to DB via SQL Management Studio and Just rename as you generally doing for DB [Press F2 on DB name]. It will allow you to do this and it will immediately reflect the same.

I can confirm the
ALTER DATABASE [oldname] MODIFY NAME = [newname];
works without connecting to master first BUT if you are renaming a restored Azure database; don't miss the space before the final hyphen
ALTER DATABASE [oldname_2017-04-23T09 -17Z] MODIFY NAME = [newname];
And be prepared for a confusing error message in the Visual Studio 2017 Message window when executing the ALTER command
Msg 0, Level 20, State 0, Line 0
A severe error occurred on the current command. The results, if any, should be discarded.

You can easily do it from SQL Server Management Studio, Even from the community edition.

Related

Installation of pg_cron on Azure Flexible PostgeSQL

I am trying to install pg-cron extension for Azure PostgreSQL Flexible server.
According to documentation found here:
https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/concepts-extensions#postgres-13-extensions
pg_cron is available extension, but when I am trying to install it:
create schema cron_pg;
CREATE EXTENSION pg_cron SCHEMA cron_pg;
What I get is:
SQL Error [0A000]: ERROR: extension "pg_cron" is not allow-listed for "azure_pg_admin" users in Azure Database for PostgreSQL
Hint: to see the full allow list of extensions, please run: "show azure.extensions;"
When executing:
show azure.extensions;
pg_cron is missing:
address_standardizer,address_standardizer_data_us,amcheck,bloom,btree_gin,btree_gist,citext,cube,dblink,dict_int,dict_xsyn,earthdistance,fuzzystrmatch,hstore,intagg,intarray,isn,lo,ltree,pageinspect,pg_buffercache,pg_freespacemap,pg_partman,pg_prewarm,pg_stat_statements,pg_trgm,pg_visibility,pgaudit,pgcrypto,pgrowlocks,pglogical,pgstattuple,plpgsql,postgis,postgis_sfcgal,postgis_tiger_geocoder,postgis_topology,postgres_fdw,sslinfo,tablefunc,tsm_system_rows,tsm_system_time,unaccent,uuid-ossp,lo,postgis_raster
What am I doing wrong?
You can tell pg_cron to run jobs in another database by updating the database column job in the jobs table.
For example:
UPDATE cron.job SET database = 'wordpress' WHERE jobname = 'wordpress-job';
Pretty late but this issue showed up when I was searching for same problem but with pg_trgm extension. After some looking around eventually realised you just need to update the database settings.
Go to Database in Azure Portal, then to Server parameters and search for azure.extensions parameter. You can then click on the list and enable/disable desired extensions (PG_CRON is available), the server will restart on save and then you will be able to enable the extensions in database.
Seems that the pg_cron extension is already enabled, by default, in the default 'postgres' database.
The reason why I was not seeing this is because I am not using the default 'postgres' database. I have created my own DB which I was connected to.
This actually does not resolve my problem, because I can't execute jobs from pg_cron across databases...

Error installing Moodle 3.0

I am unable to complete Moodle installation. I am hosting the site on NearlyFreeSpeech and using PHP 5.6. Moodle doesnt seem to be able to connect to the database and write any tables.
I created the moodledata folder in /protected/moodledata and moodle is in /public/moodle
I receive this error after accepting the terms and conditions.
Error reading from database
More information about this error
It is usually not possible to recover from errors triggered during installation, you may need to create a new database or use a different database prefix if you want to retry the installation.
Normally my first instinct would point to the config.php file but if it's getting as far as telling you that a connection is established with the database but there's a read error ("Error reading from database"), then that generally means your config.php file is probably healthy, but your database is not.
Firstly, check that you're using one of the following database servers that Moodle is compatible with (minimum version)
PostgreSQL 9.1
MySQL 5.5.31
MariaDB 5.5.31
Microsoft SQL Server 2008
Oracle Database 10.2
source.
Secondly, ensure that the user assigned to access your database in config.php has ALL PRIVILEGES set on that database.
Moving on... If this is a fresh install and you have no data to lose, your best bet is to start with a clean database.
You can either delete your existing database and set up a new one, or you can drop all tables from your existing database.
Option 1. Delete your existing database.
Delete your config.php file
Jump to phpMyAdmin (from the 'actions' tab on the MySQL process page)
Click on "Databases"
Delete your existing database
Hit "Create database" to generate a fresh, empty database
Go to http://your.url/install.php and follow the instructions for a fresh install.
Option 2. Clear your existing database
Jump to phpMyAdmin and run the following query:
DECLARE #sql NVARCHAR(max)=''
SELECT #sql += ' Drop table '+TABLE_SCHEMA+'.'+ TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
Exec Sp_executesql #sql
source.
Then go to http://your.url/install.php and follow the instructions for a fresh install.
If you managed to start with a fresh database and you get the same error, please ensure that you have all the prerequisites available from your host. You can find a list of Moodle PHP requirements here.
The only time I've seen that error is when using the wrong MySQL version. Eg currently MySQL 5.5 is supported but if you have 5.1 you would get that error.
Source: http://realtechtalk.com/moodle_install_error_Error_reading_from_database_-2072-articles

Database MSDB can not be opened

I have got this problem in local instance of SQL Server 2008 R2 on my machine. There are several databases on this instance. But I am not able to see any of them from the object explorer.
I am able to query my databases from the new query window. But not able to see any of them.
Whenever I try to explore the databases I get this error :
Database 'msdb' cannot be opened. It has been marked SUSPECT by recovery. See the SQL Server errorlog for more information. (Microsoft SQL Server, Error: 926).
I have tried
Refreshing the connection
Reconnecting the connection
Restarting the service Sql Server (MSSQLSERVER).
Restarting the SQL Server Management Studio
Restarting my machine
I have also tried combinations of above, but nothing works.
My operating system is Windows 7 Ultimate (64 bit).
SQL Server Management Studio Version is 10.50.2500.0.
I found my answer in this link.
EDIT : Including both the solutions from link because of possible Linkrot in future.
Login with sa account, for both the solutions.
Solution 1
Open new query window
EXEC sp_resetstatus 'DB_Name'; (Explanation :sp_resetstatus turns off the suspect flag on a database. This procedure updates the mode and status columns of the named database in sys.databases. Also note that only logins having sysadmin privileges can perform this.)
ALTER DATABASE DB_Name SET EMERGENCY; (Explanation : Once the database is set to EMERGENCY mode it becomes a READ_ONLY copy and only members of sysadmin fixed server roles have privileges to access it.)
DBCC checkdb('DB_Name'); (Explanation : Check the integrity among all the objects.)
ALTER DATABASE DB_Name SET SINGLE_USER WITH ROLLBACK IMMEDIATE; (Explanation : Set the database to single user mode.)
DBCC CheckDB ('DB_Name', REPAIR_ALLOW_DATA_LOSS); (Explanation : Repair the errors)
ALTER DATABASE DB_Name SET MULTI_USER; (Explanation : Set the database to multi user mode, so that it can now be accessed by others.)
Solution 2
In Object Explorer --> The opened connection item --> rightclick --> Stop
Open Control Panel --> Administrative Tools --> Services
Select Sql Server (MSSQLSERVER) item from services --> rightclick --> Stop
Open C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA
Move MSDBData.mdf & MSDBlog.ldf to any other place
Then Copy this Files Again from new place and put it in older place
C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA
In opened connection in object Explorer --> rightclick --> Start
Then Refresh DataBase.
Then you can Detach the MSDB File
The 2nd solution worked for me.
Note : I had to get "msdb" database mdf and ldf files from another working machine to get it working.
What instantly fixed my issue was to replace existing MSDBData.mdf & MSDBlog.ldf files
in C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA. I got these 2 files copied from another working machine, Stopped the SQL service running in my machine, removed the above existing 2 files from their location and added the new 2 copied. Once I restarted the service , issues has been fixed.
Try this
Set the database into single user mode:
Alter database dbname set single_user
Now set the database into emergency mode:
Alter database dbname set emergency
Repair missing log file or corrupted log file with data loss.
DBCC CHECKDB ('dbname', REAPIR_ALLOW_DATA_LOSS)
Now set the db in multi user mode;
Alter database dbname set multi_user
You may loss the data by using this command. It also depends on client's approval. To avoid this you may use some other dedicated software ( As Mentioned here ) to recover from suspect mode.

CREATE DATABASE permission denied in database 'master' (EF code-first)

I use code-first in my project and deploy on host but I get error
CREATE DATABASE permission denied in database 'master'.
This is my connection string:
<add name="DefaultConnection"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-test-2012615153521;Integrated Security=False"
providerName="System.Data.SqlClient;User ID=test;Password=test"/>
I had the same problem. This what worked for me:
Go to SQL Server Management Studio and run it as Administrator.
Choose Security -> Then Logins
Choose the usernames or whatever users that will access your database under the Logins and Double Click it.
Give them a Server Roles that will give them credentials to create database. On my case, public was already checked so I checked dbcreator and sysadmin.
Run update-database again on Package Manager Console. Database should now successfully created.
Here is an image so that you can get the bigger picture, I blurred my credentials of course:
Be sure you have permission to create db.(as user2012810 mentioned.)
or
It seems that your code first use another (or default) connection string.
Have you set connection name on your context class?
public class YourContext : DbContext
{
public YourContext() : base("name=DefaultConnection")
{
}
public DbSet<aaaa> Aaaas { get; set; }
}
I got the same problem when trying to create a database using Code First(without database approach). The problem is that EF doesn't have enough permissions to create a database for you.
So I worked my way up using the Code First(using an existing database approach).
Steps :
Create a database in the Sql server management studio(preferably without tables).
Now back on visual studio, add a connection of the newly created database in the server explorer.
Now use the connection string of the database and add it in the app.config with a name like "Default Connection".
Now in the Context class, create a constructor for it and extend it from base class and pass the name of the connection string as a parameter.
Just like,
public class DummyContext : DbContext
{
public DummyContext() : base("name=DefaultConnection")
{
}
}
5.And now run your code and see the tables getting added to the database provided.
Run Visual Studio as Administrator, it worked for me
This error can also occur if you have multiple projects in the solution and the wrong one is set as the start-up project.
This matters because the connection string used by Update-Database comes from the start-up project, rather than the "Default project" selected in the package manager console.
(credits to masoud)
I have resolved this problem in my way.
Try connection string in this way:
<add name="MFCConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MFC.mdf;Initial Catalog=MFC;Integrated Security=false;User ID=sa;Password=123"
providerName="System.Data.SqlClient" />
remember to set default db from master to MFC (in your case, aspnet-test-2012615153521).
Double check your connection string. When it points to non-existing database, EF tries to create tables in master database, and this error can occur.
In my case there was a typo in database name.
As the error suggests, the SQL login has no permission to create database. Permissions are granted when the login have the required roles. The role having permission to create, alter and drop database is dbCreator. Therefore it should be added to the login to solve the problem. It can be done on SQL Management Studio by right-clicking the user then go to Properties>Server Roles. I encountered the same error and resolved it by doing exactly that.
I encountered what appeared to be this error. I was running on windows and found my administrator windows user did not have administrator privileges to database.
Shut down SQL Server from ‘Services’
Open cmd window (as administrator) and run single-user mode as local admin with this command (the version of MSSQL may differ):
"C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\Binn\sqlservr.exe" -m -s SQLEXPRESS
Open another cmd window (as administrator)
Open sqlcmd on that terminal with:
sqlcmd -S .\SQLEXPRESS
Now add the sysadmin role to your user:
sp_addsrvrolemember 'domain\user', 'sysadmin'
GO
Re-enable SQL Server from ‘Services’
Credit to:
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/76fc84f9-437c-4e71-ba3d-3c9ae794a7c4/
Create the empty database manually.
Change the "Integrated Security" in connection string from "true" to
"false".
Be sure your user is sysadmin in your new database
Now I hope you can execute update-database successfully.
If you're running the site under IIS, you may need to set the Application Pool's Identity to an administrator.
Run Visual Studio as Administrator and put your SQL SERVER authentication login (who has the permission to create a DB) and password in the connection string, it worked for me
run this on your master database
ALTER SERVER ROLE sysadmin ADD MEMBER your-user;
GO
I'm going to add what I've had to do, as it is an amalgamation of the above.
I'm using Code First, tried using 'create-database' but got the error in the title.
Closed and re-opened (as Admin this time) - command not recognised but 'update-database' was so used that. Same error.
Here are the steps I took to resolve it:
1) Opened SQL Server Management Studio and created a database "Videos"
2) Opened Server Explorer in VS2013 (under 'View') and connected to the database.
3) Right clicked on the connection -> properties, and grabbed the connection string.
4) In the web.config I added the connection string
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=MyMachine;Initial Catalog=Videos;Integrated Security=True" providerName="System.Data.SqlClient"
/>
</connectionStrings>
5) Where I set up the context, I need to reference DefaultConnection:
using System.Data.Entity;
namespace Videos.Models
{
public class VideoDb : DbContext
{
public VideoDb()
: base("name=DefaultConnection")
{
}
public DbSet<Video> Videos { get; set; }
}
}
6) In Package Manager console run 'update-database' to create the table(s).
Remember you can use Seed() to insert values when creating, in Configuration.cs:
protected override void Seed(Videos.Models.VideoDb context)
{
context.Videos.AddOrUpdate(v => v.Title,
new Video() { Title = "MyTitle1", Length = 150 },
new Video() { Title = "MyTitle2", Length = 270 }
);
context.SaveChanges();
}
Check that the connection string is in your Web.Config. I removed that node and put it in my Web.Debug.config and this is the error I received. Moved it back to the Web.config and worked great.
Step 1: Disconnect from your local account.
Step 2: Again Connect to Server with your admin user
Step 3: Object Explorer -> Security -> Logins -> Right click on your server name -> Properties -> Server Roles -> sysadmin -> OK
Step 4: Disconnect and connect to your local login and create database.
I have no prove for my solution, just assumptions.
In my case it is caused by domain name in connection string. I have an assumption that if DNS server is not available, it is not able to connect to database and thus the Entity Framework tries to create this database. But the permission is denied, which is correct.
The solution that worked for me was to use the Entity Framework connection string that is created when I ran the database first wizard when creating the edmx file. The connection string needs the metadata file references, such as "metadata=res:///PSEDM.csdl|res:///PSEDM.ssdl|res://*/PSEDM.msl". Also, the connection string needs to be in the config of the calling application.
HT to this post for pointing me in that direction: Model First with DbContext, Fails to initialize new DataBase
For me I just close all current session including the SQL Server Management Studio and then I reopened execute the script below works fine
IF EXISTS (SELECT NAME FROM master.sys.sysdatabases WHERE NAME = 'MyDb')
DROP DATABASE mydb RESTORE DATABASE SMCOMDB FROM DISK = 'D:/mydb.bak'
I had the same problem and I tried everything available on the internet. But SSMS RUN AS ADMINISTRATOR work for me.
If you still face some issue, make sure you must have downloaded the SQL SERVER.
the reason for this error may be originate from forwarding of version dependent localdb in visual sudio 2013 to the version independent localDB in VS 2015 onwards, so
simply change your web.config file connectionStrings from (localDb)\v11.0 to (localDB)\MSSQLLocalDB and it will certainly work.
and this is a good explaination for that Version independent local DB in Visual Studio 2015
If you are using .\SQLExpress as Data Source, you can add "User Instance=True" attribute to your connection string, to fix the error mentioned in the title.
For example,
Data Source=.\\SQLExpress;Integrated Security=true;
User Instance=true;
AttachDBFilename=|DataDirectory|\app_data\Northwind.mdf;
Initial Catalog=Northwind;
User instances allow users who are not administrators on their local computers to attach and connect to SQL Server Express databases. Each instance runs under the security context of the individual user, on a one-instance-per-user basis.
Reference: MSDN Link for SQL Server Express User Instances
This is so wrong - never over-elevate your permissions (use SA) where you don't need to do so.
To create database all you need is: CREATE DATABASE, CREATE ANY DATABASE, or ALTER ANY DATABASE permission as per
documentation or the login to be a member of the dbcreator
server level role.
Next - you need to make sure that mssql service login (NT Service\MSSQLServer by default) has permission to modify the file
system in the location where you want to create your database
(usually 1 .mdf file for data pages and 1 .ldf file for database
logs).
Then make sure you know where you create your databases! EF by
default sends the laziest query possible, defining only database
name: CREATE DATABASE [db_name] and then assuming all of the rest -
applying default settings. Make sure you either change these to reflect locations mssql engine service has access to or elevate
service permissions. Either way this modification requires mssql
restart tyo apply the setting.
Finally, make sure that you connect to the mssql using that login.
If you perform an EXECUTE AS USER statement to switch your login it
will fail. This method allows only to interpersonate DB user, not
the server level login. An attemp of doing it will give you CREATE DATABASE permission denied in database 'master' error message.
To get permission to create database in your local account follow the below given steps.
Disconnect from your local account.
Again Connect to Server with Login : sa and Password : pwd(pwd given to your local login).
Object Explorer -> Security -> Logins -> Right click on your server name -> Properties -> Server Roles -> sysadmin -> OK
Disconnect and connect to your local login and create database.
P.s: For me even without connect/disconnect to server, it worked!
I had the same issue, I tried couple of other methods, but none of them worked. I just simply exit the SSMS and run it as an administrator and it worked perfectly.
The solution to this problem is as simple as eating a piece of cake.This issue generally arises when your user credentials change and SQL server is not able to identify you .No need to uninstall the existing SQL server instance .You can simply install a new instance with a new instance name . Lets say if your last instance name was 'Sqlexpress' , so this time during installation , name your instance as 'Sqlexpress1' . Also don't forget to select the mix mode (i.e Sql Server Authentication & Windows Authentication) during the installation and provide a system admin password which will be handy if such a problem occurs in future.
This solution will definitely resolve this issue. Thanks..
Permission denied is a security so you need to add a "User" permission..
Right click you database(which is .mdf file) and then properties
Go to security tab
Click Continue button
Click Add button
Click Advance button
Another window will show, then you click the "Find Now" button on the right side.
On the fields below, go to the bottom most and click the "Users". Click OK.
Click the permission "Users" that you have been created, then Check the full control checkbox.
There you go. You have now permission to your database.
Note: The connection-string in the above questions is using SQL-server authentication. So, Before taking the above step, You have to login using windows-authentication first, and then you have to give permission to the user who is using sql-server authentication. Permission like "dbcreator".
if you login with SQL server authentication and trying to give permission to the user you logged in. it shows, permission denied error.

"use database_name" command in PostgreSQL

I am beginner to PostgreSQL.
I want to connect to another database from the query editor of Postgres - like the USE command of MySQL or MS SQL Server.
I found \c databasename by searching the Internet, but its runs only on psql. When I try it from the PostgreSQL query editor I get a syntax error.
I have to change the database by pgscripting. Does anyone know how to do it?
When you get a connection to PostgreSQL it is always to a particular database. To access a different database, you must get a new connection.
Using \c in psql closes the old connection and acquires a new one, using the specified database and/or credentials. You get a whole new back-end process and everything.
You must specify the database to use on connect; if you want to use psql for your script, you can use "\c name_database"
user_name=# CREATE DATABASE testdatabase;
user_name=# \c testdatabase
At this point you might see the following output
You are now connected to database "testdatabase" as user "user_name".
testdatabase=#
Notice how the prompt changes. Cheers, have just been hustling looking for this too, too little information on postgreSQL compared to MySQL and the rest in my view.
In pgAdmin you can also use
SET search_path TO your_db_name;
The basic problem while migrating from MySQL I faced was, I thought of the term database to be same in PostgreSQL also, but it is not. So if we are going to switch the database from our application or pgAdmin, the result would not be as expected.
As in my case, we have separate schemas (Considering PostgreSQL terminology here.) for each customer and separate admin schema. So in application, I have to switch between schemas.
For this, we can use the SET search_path command. This does switch the current schema to the specified schema name for the current session.
example:
SET search_path = different_schema_name;
This changes the current_schema to the specified schema for the session. To change it permanently, we have to make changes in postgresql.conf file.
Use this commad when first connect to psql
=# psql <databaseName> <usernamePostgresql>
set search_path = 'schema name here'
while connecting to the postgres, you have to opt for default database to connect. If you have nothing, you can use 'postgres' as default.
You can use dbeaver to connect to postgres. UI is good
PgAdmin 4, GUI Tool: Switching between databases
In the PgAdmin Browser on the left hand side, right click on the database you are willing to switch to.
Select a QueryTool from the drop down menu (or any other option that you need, I will stick with the QueryTool for now).
You will see the QueryTool in the PgAdmin window, and on top you will see the active database and the role name.
Now you can write queries against the chosen database.
You can open multiple QueryTools for multiple database, and work with them as you do with your graphical text editor.
In order to be sure that you are querying the proper database, issue the following query:
SELECT session_user, current_database();