SSMS And Visual Basic Express .... cannot backup - sql-server

Let us start with...yes I am new to SQL and really only a lightweight programmer. So I am assuming that I am doing something horribly wrong. I have spent days on the MS forums looking for an answer to no avail. So I am going to give as much info as possible.
Application language is VBExpress 2010 and using SQLExpress 2008. The Database contain basic tables, no stored procs, no views, no diagrams. The Application has configured diagrams where one of the tables has inner joins... Tables origninally built in SSMS, but have been altered in VBE.
Anytime I run the application, even after exiting the application, if I then go to SSMS I can see the database name but I cannot open it up (no + beside it). If I try I get an error that says:
One or more files do not match the primary file of the database. If you are attempting to attach a database retry the operation with the correct files. If this is an existing database the file may be corrupted and should be restored from a backup."
When I look at the files, I see two log files, one with _1 appended on to it. If I delete the logfiles before opening SSMS, everything opens fine. If I had already opened SSMS then I have to delete the files, reboot my computer and then I can access the database through SSMS...
I recently found that if I go into SSMS, take the database offline and then bring it back online I can get access back.
Anytime I open SSMS, I have to completely reboot my computer before VBE will reconnect the database.
The bottom line is that I cannot back up the database without either deleting the log files or doing an offline/online cycle in SSMS....
This is driving me nuts. I cannot possilby deploy the application if I cannot achieve a normal backup procedure. And I cannot seem to get any kind of answer about why this is happening.
What am I doing so WRONG?

If you are using SQL Server 2008 then, reattach the database files and it will must be stored in C:\Program Files\Microsoft SQL Server\MSSQL 10.MSSQLSERVER\MSSQL\DATA.
And recheck the database on that folder and it will take backup and restore point of Primary files of Database. Don't modify/delete the database files. If the location of log files are changed the it will shows the error. Please give your mail id I'll send a program to restore and backup of database files in winrar.
Thank you
Regards,
Naresh.

Related

Copy SQL Server database between two servers

I have a productive SQL Server database on one server. Also on this server there are the databases for test and development, which was over a long period no big deal for performance. But now I have to test some quite expensive selects for a nightly report and so my users get heavy trouble using the database during working hours.
We have a redundant server with SQL Server running which we never really used, but now we think his time has come. Until now, to get a fresh copy of the production system I do a full backup, copy it into a folder on Server A and connect the folder as network drive an Server B. Then I copy the file into a folder where SQL Server has read permissions and import the backup into the database on B.
On Server A I have made some maintenance plans for backing up the production system into one of the other systems by executing the plan.
I want some solution like this for my B Server, but it doesn't seem to get running. I can do a Select from server A in a table on server B, so they both do know each other and can see them.
I've tried the copy database wizard but it crashes because it couldn't delete the database on server B even if I had removed it manually before the try.
I also tried importing the Database on Server B from Server A but it didn't work either.
Googling my problem didn't work out because I always get solutions to the problem making backup files onto some kind of server.
Hope someone of you could help automating this process.

SSMS database disappearing after accessing it in VS

After I access the database in VS 2015. I log into localdb SSMS to find that the database is no longer there and I must right click database and attach it. Is this normal? Btw I am using SSMS 2016
I have never heard of a disappearing database. I suppose you could have accidentally detached it, though.
What Is Detach or Attach and How do They Work?
We'll start with detach. When you detach a database in SQL Server, you are taking the database offline and removing it from the SQL Server instance from which you are detaching it. The databases data and log files remain in tact and are left in a consistent state so you can then attach the database at a later point or to another SQL Server instance. Attach connects the data and log files from a database that has been properly detached (or that were copied from a cleanly shut down instance of SQL Server) to an instance of SQL Server and brings the database online.
How Do I Detach a Database?
You can do this in T-SQL or from the SQL Server Management Studio GUI.
In the GUI, you right click on the database you wish to detach, select All Tasks and click on Detach. From there you'll get the detach dialog. You can choose to drop connections first to forcibly disconnect any active connections and rollback work they were in the middle of executing. You can also choose to update statistics before the detach. Detaching through - Choose Detach...
In T-SQL:
-- You don't want to be in the database you are trying to detach
USE Master
GO
-- Optional step to drop all active connections and roll back their work
ALTER DATABASE DatabaseName
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
-- Perform the detach
EXEC sp_detach_db 'DatabaseName'
GO
For the system stored procedure sp_detach_db there are two paramaters that you can pass in optionally:
#skipchecks - acceptable input is 'True' or 'False' if 'True', SQL Server will update statistics before detach. If 'False', it won't. If you don't specify anything here the statistics will be updated in SQL Server 2005 or later.
#keepfulltextindexfile - The default here is 'True' - if this is set to true, the full text index metadata will not be dropped during the detach.
To see a lot more about detach and some more details on the risks I highlight below, the Books Online article for sp_detach_db is a good place to start.
How Do I Attach a Database?
You can also do this in T-SQL or from the SQL Server Management Studio GUI.
(NOTE: If you have the data and log files from a database that was not properly detached, your attach may not work. When detach occurs, the database is brought offline and the log and data files are put into a consistent state. This also happens when a service is cleanly shut down.)
In the GUI, you right click on the top level Databases folder for your instance and select Attach. In the next dialog you would then select the primary data file (.MDF) of the database you wish to attach and ensure you have the other files selected and their appropriate locations specified, and click OK, attaching your database.
In T-SQL the best way to do this in SQL Server 2005 and forward is through the CREATE DATABASE command. This is the method that is supported beyond SQL Server 2012. If you want to see how to use sp_attach_db, you can see that in the books online articles for [sp_attach_db][3] or [sp_attach_single_file_db][4]
When you have your log file and data files available and they are consistent this is the T-SQL approach:
-- Using Create Database and the FOR ATTACH clause to attach
CREATE DATABASE DatabaseName
ON (FILENAME = 'FilePath\FileName.mdf'), -- Main Data File .mdf
(FILENAME = 'FilePath\LogFileName.ldf'), -- Log file .ldf
(FILENAME = 'FilePath\SecondaryDataFile.ndf) -- Optional - any secondary data files
FOR ATTACH
GO
You can see more about the Create Database statement in books online as well.
How Do I Detach/Attach in SQL Server Express?
It's actually the same. If you are using SQL Server Management Studio Express you can use the detach/attach dialog in the GUI described above or the T-SQL steps through SSMS Express described above as well. No difference with Express there.
If you don't have SSMS Express, you can download it (Here is the SQL Server 2012 Express version).
Of you can enter into a SQLCMD session and use the same T-SQL constructs described above.
When Should I Consider Doing a Detach or Attach?
First a word on what detach and attach is not meant to be used for: Backup and Recovery Detach and Attach is not a way to backup your database for routine recovery purposes. There are no transaction log backups this way, it puts your database into a state where the database files can be deleted accidentally and is not a good way at all for this purpose.
That said, detach and attach are good for a few use cases (not exhaustive, feel free to edit to add or create a new answer with more):
Sometimes for migrations (although I prefer backup/restore for those as discussed in my answer here)
When you want to remove a database that is no longer actively used but have the ability to attach later as needed.
In certain troubleshooting situations, this may be called upon
Don't have the space to backup or to restore both a data and log files to another environment (you shouldn't ever be here but I've used it to move dev databases around environments at times.. Didn't want or need the log so did an attach/rebuild of the log file)
Risks and Warnings
Again, books online is a good resource here, but I'll call out some specific considerations to have in mind with detaching or attaching a database -
Detach
You are taking your database offline. It won't be accessible anymore. This should be obvious, but worth calling out. This is why it isn't a great backup option.
When your database is online, SQL Server locks the files. I wouldn't recommend trying this to prove me wrong, because there could be some other situation at play, but you typically can't delete a database file (data, secondary data or log file) while SQL Server is online. This is a good thing. When you detach, you have no such protection - this can be a bad thing.
If you are dealing with database corruption and you find some article someplace that has a first step of Detach - it's wrong - if you detach a corrupt database, that may be it. You may not be attaching that database again.
Cutting and pasting your production database files throughout your network is a way to potentially introduce file level corruption.. Another reason I prefer backup/restore when doing migrations.
It might cause a maintenance plan to fail. The situation is that you have, as I did, set up a maintenance plan to carry out regular backups of all databases without checking best practice. This works fine so you stop thinking about it. Someone else then decides to take a database they're not using offline. The maintenance plan will fail from that point forwards until you modify the maintenance plan by checking the "ignore databases whose state is not online" option in the "Database(s)" dialog. Note that it won't just fail for the offline database - the maintenance plan will fail with an error at the point when it tries to backup the offline database so some online databases might not be backed up. (different author for this point so treat with suspicion)
Attach - Just like you shouldn't run scripts from the internet or accept packages from strangers at the airport, you shouldn't attach a database you got from someone else without some steps to verify it. This database could have code inside of it in triggers, stored procedures, etc. that could compromise your environment. You should review a database you want to attach in a safe, and firewalled environment, not your production system.
What About Different Versions or Editions of SQL Server?
These are no different than the rules around restoring databases between versions. You can generally restore up to the next version for 3 versions (SQL Server 2008 to SQL Server 2012, for example will work. SQL Server 2000 to SQL Server 2012 will not). You cannot go backwards at all via backup/restore or detach/attach - you'd have to script out objects and script out the inserts and do it manually or with a tool that does this. For editions, you can generally move between the main SKUs of SQL Server - for instance you can move a database from Standard to Enterprise with no extra work. If you are using Enterprise features (Say, compression or partitioning), you'll need to disable those features before you make the move, though. You can get an idea of the features you'd need to consider disable by looking here.
https://dba.stackexchange.com/questions/30440/how-do-i-attach-a-database-in-sql-server

SSMA/SQL Server: Need to alter or backup from GoDaddy

So I have a site hosted on GoDaddy (not my call...) that I'm working on an upgrade that required simply adding a column in a table. Did it locally, tested and worked like a charm. Connected to the remote DB and found I couldn't add a column. Called and after a lot of back and forth, I was told that they don't allow modifications to a db after it's created. Ummmmmmmm... okay, can I run an alter script? No...
OK, I'm not a dba so we're rapidly exceeding my comfort level but I thought I'd run a backup, restore it locally, make the modification, back that up and restore it on the host. Apparently I can't run backup from SSMS on their server. So I tried their backup tool from their control panel and it gives me a .txt file which doesn't appear to be a backup at all.
Just now I tried scripting the entire db and that isn't looking good either... throwing some kind of error as well.
What the heck else can I do to either make the changes I need or get my data the hell off there and tell my user that we simply MUST change hosts?
This is a little late..
One thing you could do from MSSMS...
Right click on your Database select Tasks->Generate Scripts.
Select a location on your PC.
Under Set Script Options click Advanced.
Change the option Types of data to script to Schema and Data. Then generate your script
Its not the best case scenario...but its better then nothing.
As for not being able to ALTER the Table...I would most definitely check the use rights of the user your logging in with. I am able to make changes to GoDaddy tables.
Instead of backup, you can try Extract data tier application from the database, which generates a bacpac file (containing schema and data) and Deploy this bacpac locally.
Make schema changes to this database and take backup of the same and restore in GoDaddy.
More information on extracting data tier application

Restore a SQL Express database from a file backup

I'm using a SQL Express database on my development machine. Unfortunately, I had to re-install the operating system and all the software on the machine. Now I need help to restoring the database that I was using before the re-installation. I have a backup of all files on the computer from before re-installing, but how do I find and restore the database from it?
You say you have a backup, but I'm not convinced that you do. Do you have any *.BAK files on your machine?
If not, you need to locate the data file (and preferably the log file as well). Depending on how you created the database originally, the files /should/ be in the form of <database name>[_data].mdf (data file) and <database name>[_log].ldf (log file).
Once you've found the files, you can use CREATE DATABASE ... FOR ATTACH and if the log file is damaged you can use the option FOR ATTACH_REBUILD_LOG instead.
A couple of notes:
(a) if you have a backup of the database, the link Rick Liddle created will be useful. Depending on whether your new instance of SQLExpress is located in the same location, you may need to use WITH MOVE to move the data and/or log file to valid folders in order to restore your databases.
(b) depending on what happened to your old machine (e.g. did it crash and die, how was the backup obtained, etc.), the mdf and/or ldf files may not be restorable. This is what proper database backups are designed to insure against.
Are you sure you have an actual backup (.BAK)?
Create a new database.
Right click
Select Tasks
Restore
Files and FileGroups...
Select File

Keeping development databases in multiple environments in sync

I'm early in development on a web application built in VS2008. I have both a desktop PC (where most of the work gets done) and a laptop (for occasional portability) on which I use AnkhSVN to keep the project code synced. What's the best way to keep my development database (SQL Server Express) synced up as well?
I have a VS database project in SVN containing create scripts which I re-generate when the schema changes. The original idea was to recreate the DB whenever something changed, but it's quickly becoming a pain. Also, I'd lose all the sample rows I entered to make sure data is being displayed properly.
I'm considering putting the .MDF and .LDF files under source control, but I doubt SQL Server Express will handle it gracefully if I do an SVN Update and the files get yanked out from under it, replaced with newer copies. Sticking a couple big binary files into source control doesn't seem like an elegant solution either, even if it is just a throwaway development database. Any suggestions?
There are obviously a number of ways to approach this, so I am going to list a number of links that should provide a better foundation to build on. These are the links that I've referenced in the past when trying to get others on the bandwagon.
Database Projects in Visual Studio .NET
Data Schema - How Changes are to be Implemented
Is Your Database Under Version Control?
Get Your Database Under Version Control
Also look for MSDN Webcast: Visual Studio 2005 Team Edition for Database Professionals (Part 4 of 4): Schema Source and Version Control
However, with all of that said, if you don't think that you are committed enough to implement some type of version control (either manual or semi-automated), then I HIGHLY recommend you check out the following:
Red Gate SQL Compare
Red Gate SQL Data Compare
Holy cow! Talk about making life easy! I had a project get away from me and had multiple people in making schema changes and had to keep multiple environments in sync. It was trivial to point the Red Gate products at two databases and see the differences and then sync them up.
In addition to your database CREATE script, why don't you maintain a default data or sample data script as well?
This is an approach that we've taken for incremental versions of an application we have been maintaining for more than 2 years now, and it works very well. Having a default data script also allows your QA testers to be able to recreate bugs using the data that you also have?
You might also want to take a look at a question I posted some time ago:
Best tool for auto-generating SQL change scripts
You can store backup (.bak file) of you database rather than .MDF & .LDF files.
You can restore your db easily using following script:
use master
go
if exists (select * from master.dbo.sysdatabases where name = 'your_db')
begin
alter database your_db set SINGLE_USER with rollback IMMEDIATE
drop database your_db
end
restore database your_db
from disk = 'path\to\your\bak\file'
with move 'Name of dat file' to 'path\to\mdf\file',
move 'Name of log file' to 'path\to\ldf\file'
go
You can put above mentioned script in text file restore.sql and call it from batch file using following command:
osql -E -i restore.sql
That way you can create script file to automate whole process:
Get latest db backup from SVN
repository or any suitable storage
Restore current db using bak file
We use a combo of, taking backups from higher environments down.
As well as using ApexSql to handle initial setup of schema.
Recently been using Subsonic migrations, as a coded, source controlled, run through CI way to get change scripts in, there is also "tarantino" project developed by headspring out of texas.
Most of these approaches especially the latter, are safe to use on top of most test data. I particularly like the automated last 2 because I can make a change, and next time someone gets latest, they just run the "updater" and they are ushered to latest.

Resources