What does a *.sql file contain - c#

In Vsual Studio => Server Explorer I created a new SQL Server database (dbo) and I right clicked on the option "publish to provider".
It generated a file with sql extension which includes sql commands (SELECT, UPDATE).
I want to know what does this file contain.
Is it the whole database?
Can I import this file to SQL Server Management Studio later?
And does it store everything in database (relations, default values, rules)?
I have written some of the text from the file
/****** Object: ForeignKey [FK__aspnet_Me__Appli__21B6055D] Script Date: 06/30/2013 12:01:32 ******/
IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo]. [FK__aspnet_Me__Appli__21B6055D]') AND parent_object_id = OBJECT_ID(N'[dbo]. [aspnet_Membership]'))
ALTER TABLE [dbo].[aspnet_Membership] DROP CONSTRAINT [FK__aspnet_Me__Appli__21B6055D]
GO
/****** Object: ForeignKey [FK__aspnet_Me__UserI__22AA2996] Script Date: 06/30/2013 12:01:32 ******/
IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo]. [FK__aspnet_Me__UserI__22AA2996]') AND parent_object_id = OBJECT_ID(N'[dbo]. [aspnet_Membership]'))
ALTER TABLE [dbo].[aspnet_Membership] DROP CONSTRAINT [FK__aspnet_Me__UserI__22AA2996]
GO
/***

i clicked [...] can i import this file to sql server management studio later?
Then look at the manual for what you clicked on:
The Database Publishing Wizard in Visual Studio enables you to deploy a SQL Server database (both schema and data) to a hosting environment. You can run the wizard by right-clicking a database in Server Explorer and then clicking Publish to provider.
The tool supports the following ways to deploy a database:
It can generate a single SQL script file that you can manually run on the target server to re-create the database schema and the database contents.
So, yes.

This file contains a list of SQL statements that will transform the DB you selected during the process.
This file will work only for a DB in the same state as the one you selected.
If you will run this process twice, the script that will be generated will be different, since the first script changed your db, and some operations will not be performed.
This file does not contain all the data in the DB.

Related

The Sql Database is not deleted

I'm getting an error deleting a database I created about a year ago. in the error, when I run these codes, it says:
USE MASTER;
GO
DROP DATABASE StoreDatabase;
GO
Cannot drop the database 'StoreDatabase', because it does not exist or you do not have permission.
when I try to manually delete it manually
Right-click => Delete => Delete Backup and restore history information for database and Close Existing connections
in the error message it says:
The object of type "Database" named "StoreDatabase" does not exist on the server (SqlManagerUI)
how can I solve this error. thank you for your help.
The Sql Database is not deleted
You do not delete a database but DROP it
Cannot drop the database 'StoreDatabase', because it does not exist or you do not have permission.
Error includes two parts: (1) database does not exist or (2) you do not have permission. Please connect the server using SSMS or Azure Data Studio
(1) Use SSMS and execute the following query in order to confirm that the database exists
select DatabaseName = [name] FROM sys.databases
where [name] = 'StoreDatabase'
GO
(2) In order to DROP a database you need to have CONTROL permission on the database, or ALTER ANY DATABASE permission on the server, or to be membership in the db_owner fixed database role. Execute the following query to check that you have the permissions
USE StoreDatabase;
SELECT * FROM fn_my_permissions (NULL, 'DATABASE')
where permission_name = 'CONTROL'
GO
SELECT * FROM fn_my_permissions(NULL, 'SERVER')
where permission_name = 'ALTER ANY DATABASE'
GO
USE master;
select DatabaseName = [name], DatabaseOwner = suser_sname(owner_sid)
FROM sys.databases
where [name] = 'StoreDatabase'
GO
Try to DROP the database when you are connected as sysadmin (for example the USER sa)

Alter database in Entity Framework migration

I want to enable broker for my database in an Entity Framework migration. I add a migration to my project and write this code in the Up method :
Sql("ALTER DATABASE current SET ENABLE_BROKER", true);
This code runs correctly for SQL Server 2014, but when I change my target database to SQL Server 2008 R2 Express, I get this error:
Incorrect syntax near the keyword 'current'
How do I change the code to run properly for all type of SQL Server instances?
Before SQL 2012 you have to use the database name. Something like this batch:
declare #sql nvarchar(max) = N'ALTER DATABASE ['+db_name()+N'] SET ENABLE_BROKER;'
exec( #sql );
should work.

How to export database and import it locally by C# code?

How to "clone" a database from a remote server to LocalDB database by a C# application? No relationships back to the remote database are needed.
Background
Application is written in C# using .NET 4.5.2 and supports two modes - online which connects to a remote MS SQL Server database, and offline which connects to a LocalDB database. The application primarily targets newer versions of the servers (if it matters, supporting only version 2014 is ok).
Before the user goes offline it should ask the application to clone the remote database to the LocalDB database (the local database is completely overwritten). The local database should be independent on the remote database, i.e. no slave nor replication.
Both the online and offline connection string contains name of the respective database. The application itself has no direct knowledge of the database name nor of the table names as this is managed by the connection strings and by the Entity Framework.
Question
How to "clone" the remote database to a LocalDB database (the remote database name and the LocalDB database name might be different)?
I prefer a solution which does not require to launch an external program, but this is not a hard requirement.
Issues
Copying through Entity Framework no tracking entities is unacceptable slow.
I am aware of the BACKUP DATABASE and RESTORE DATABASE commands, but I have found the following difficulties:
They require me to specify the name of the database. Is there a way how to default them to the initial database specified as part of the connection string?
The RESTORE DATABASE command contains names and paths of the respective data files on the disc (MOVE parts). Is there a way how to process it with specifying just the database name without providing the data files path? Or how to get the data files paths via SQL commands (to get the file names, I will just create a blank database, got the file names, optionally drop the database and use the retrieved file names)?
Is there a better way doing this?
I use a stored procedure i created, but first you need to create a linked server:
IF EXISTS(SELECT name FROM sys.servers WHERE name = 'SERVER')
BEGIN--
EXEC sp_dropserver 'SERVER', 'droplogins'
END
/****** Object: LinkedServer [SERVER] create LinkedServer ******/
EXEC master.dbo.sp_addlinkedserver
#server = N'SERVER',
#srvproduct=N'SQLNCLI',
#provider=N'SQLNCLI',
#datasrc=N'192.168.1.1' -- IP address of a server
/* Add login data*/
EXEC sp_addlinkedsrvlogin
#useself='FALSE',
#rmtsrvname='SERVER',
#rmtuser='User',
#rmtpassword='Pass'
Then you can create stored procedure on local server or execute the query directly from application, also for safety I am using a transaction in this example:
USE [DB]
GO
/****** Object: StoredProcedure [dbo].[backupdatabase] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[backupdatabase]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION
TRUNCATE TABLE [dbo].[table_1]
INSERT INTO [dbo].[table_1]
SELECT * FROM [SERVER].[DB].[dbo].[table_1]
TRUNCATE TABLE [dbo].[table_2]
INSERT INTO [dbo].[table_2]
SELECT * FROM [SERVER].[DB].[dbo].[table_2]
TRUNCATE TABLE [dbo].[table_3]
INSERT INTO [dbo].[table_3]
SELECT * FROM [SERVER].[DB].[dbo].[table_3]
COMMIT
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION
DECLARE #ErrMsg nvarchar(4000), #ErrSeverity int
SELECT #ErrMsg = ERROR_MESSAGE(),
#ErrSeverity = ERROR_SEVERITY()
RAISERROR(#ErrMsg, #ErrSeverity, 1)
END
END CATCH
END

Can't create a database in SQL Server 2012

I have recently installed SQL Server 2012 on my machine. When I try to create a database in SSMS by right clicking on Databases and selecting New Database, it prompts me for various items in order to create the database. After entering the name of the database and clicking OK, I get an exception:
"Create failed for Database 'aaaa'. (Microsoft.SqlServer.Smo)
ADDITIONAL INFORMATION:
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
A file activation error occurred. The physical file name 'aaaa.mdf' may be incorrect. Diagnose and correct additional errors, and retry the operation. CREATE DATABASE failed. Some file names listed could not be created. Check related errors. (Microsoft SQL Server, Error: 5105)"
It seems the problem is only with the wizard because when I execute Create Database query it successfully creates the database.
I figured it out that when Database is created from wizard, a file path is to be provided in Path column. If it is blank by default then it means there is no path specified in Database settings.
In Object Explorer, right-click a server and click Properties.
In the left panel, click the Database settings page.
In Database default locations, view the current default locations for new data files and new log files. To change a default location, enter a new default path name in the Data or Log field, or click the browse button to find and select a path name.
We can change the file path while creating Database.
The actual database file permissions were set to read_only,please try unchecked the read_only checkbox on the file permissions.
I also had this problem and I can in this link where I've created any string values (DefaultData and DefaultLog) in regedit in this path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\MSSQLServer.
In this "string values" you must put the path where your SQL data and log must stay.
As you realized there is a Path column in the grid view for each file (.mdf and .ldf).
This is set to <default>.
At the first usage of the server this default path may not be set, so the full-path of the new database cannot be computed.
Solution:
Based on this article you can set it via the interface of SSMS. You just need to:
right click on your server name (e.g.: (LocalDB)\v11.0),
select Properties,
select Database Settings,
Fill up all 3 entry of Database default locations with valid directory paths. (Defining top 2 paths: Data and Log is enough to create databases.)
This will create the right registry entries for you, without touching regedit.exe.
What path to choose?
Either the location that is proposed along installation:
C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data
Or the location of system databases:
C:\Users\[UserName]\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\v11.0
Or better choices for non-system databases are:
C:\Users\[UserName]\My Documents\Databases
C:\Users\[UserName]\My Documents\SQL Server Management Studio\Databases
Note 1: [UserName] can be "Public" to make it common data (please correct me if this causes multiple copy of the database, but I think it won't).
Note 2: I don't know whether latter is deleted along uninstallation of SSMS.

Programmatically detach SQL Server database to copy mdf file

I have a small SQL Server database that I need to copy on command -- I need to be able to take the mfd and ldf files at any given moment, copy them, zip them, and make them available to an end user.
Right now this is possible by manually:
1) Logging onto the SQL server via Remote Desktop
2) Detaching the database via SQL Management Studio. I have to fiddle around with a combination of setting the database to single_user and/or restarting the service so I can get it to detach since the app server is normally logged into it.
3) While detached I go through the file system and copy the mdf and ldf files.
4) I re-attach the database via SQL Management Studio
5) I zip the copied files, and I move them to an FTP server so the people who need them can get them.
It's a horrible, inefficient process. It's not just a matter of needing the schema, but rather a need for people to work with snapshots of real, production data on their own local machines for the purpose of destructive experimentation. Luckily the zipped database is very small -- maybe 30 megs with the log.
So ideally, I'd like to create a page in the ASP .NET web application that has a button the user can press to initiate the packaging of the current database into a zip file, and then I'd just provide the link to the file download.
Why not make a ordinary backup (easy to do with sqlcommand) and add a feature for the users to easy restore that backupfile with a click on a button?
You can backup the database with sql-commands
You can shell out and zip the backupfile with sql-commands
You can also shell out and ftp the backupfile automagically to an webserver if you want.
What are the end users using to consume your db? A winform-program? Then it easy done to do everything with a button click for the user.
Here are some example code for that:
Declare #CustomerID int
declare #FileName nvarchar(40)
declare #ZipFileName nvarchar(40)
declare #ZipComand nvarchar(255)
set #CustomerID=20 --Get from database instead in real life application
SET #FileName='c:\backups\myback'+ cast(#customerID as nvarchar(10))+'.bak'
SET #ZipFileName='c:\backups\myback'+ cast(#customerID as nvarchar(10))+'.zip'
--Backup database northwind
backup database northwind to DISK=#FileName
--Zip the file, I got a commanddriven zip.exe from the net somewhere.
set #ZipComand= 'zip.exe -r '+#ZipFileName+' '+#FileName
EXEC xp_cmdshell #zipcomand,NO_output
--Execute the batfile that ftp:s the file to the server
exec xp_cmdshell 'c:\movetoftp.bat',no_output
--Done!
You have to have a movetoftp.bat that contains this (change ftp-server to your):
ftp -s:ftpcommands.txt ftp.myftp.net
And you have to have a ftpcommands.txt that contains this (You can have this file created dnamically with just the right zip-file by sqlcommands too, but I let you do that yourself):
ftpusername
ftppassword
binary
prompt n
mput c:\backups\*.zip
quit
Look at the dialogues you use in SQL Management Studio, near the top of each is a button which will generate a scrip to perform the action. This is a quick way to discover how to do this in SQL which can be executed from a database connection.
E.g. to detach database db1:
EXEC master.dbo.sp_detach_db #dbname = N'db1'
Easy - check into the "SQL management objects" SMO that come with SQL Server - nice C# / VB.NET classes and methods to do all of this.
See: SMO - manage your SQL Server!
or:
SQL Server 2005 Database Backup and Restore using C# and .NET 2.0
Marc
Personally I'd generate backups of the database and zip those and send them to the users. Perhaps you could write a small script to restore.
Reason being detaching the database makes it unavailable for others.
I'd use SQL Dumper console version and compress the sql dump.
IMHO it's always better to have a plain text copy instead of a binary file. If something goes wrong, at least you can rewrite your data by hand, because you can read it.
First Connect to SQL Server With no Attach any DB File and with no use Database name.
ConnectionString = #"Data Source=XXX;Integrated Security=True;Connect Timeout=30";
Note: XXX = . OR .\SQLEXPRESS OR .\MSSQLSERVER OR (local)\SQLEXPRESS OR (localdb)\v11.0 &...
then by under Query Detach your DB file.
"ALTER DATABASE [your DB] SET OFFLINE WITH ROLLBACK IMMEDIATE \n\r exec sp_detach_db #dbname = [your DB]";
Ok.
My Sample code:
sql_connect1.ConnectionString = #"Data Source=.\sqlexpress;Integrated Security=True;Connect Timeout=30";
sql_command.CommandText = "ALTER DATABASE [IRAN] SET OFFLINE WITH ROLLBACK IMMEDIATE \n\r exec sp_detach_db #dbname = [IRAN]";
sql_command.Connection = sql_connect1;
sql_connect1.Open();
sql_command.ExecuteNonQuery();
sql_connect1.Close();

Categories