Best way to remove all tables from a sql 2005 database - sql

I have been developing an asp.net mvc site on a local version of sql server express 2008 and about a month ago I set up the web host and got everything working, the host uses sql server 2005. The site is not live.
Now a month down the track I need to do a fairly big update and the database is way out of date.
I would like to know how I can retain the database but blow everything else away (tables etc.) so I can run the set up script again.
When I try a few things I find on the internet it complains about the foreign keys and doesn't delete.
Thanks in advance

if you truly don't need to retain anything (including users, roles, UDTs, etc), then just drop the db and create a new one.

Take a look at this answer to a question about disabling FK constraints, and rejoice! :)

my guess: it's all about the order you drop the tables
ex
table1
key
fKeyTable2 (foreignkey from table 2)
table2
key
first drop table 2, then drop table1
if its hard to figure out the order you can try this:
ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol;
(fk_symbol = the foreign key that is being complained about)

Related

MSSQL Import/Export/Copy IDENTITY_INSERT problems

Using MS SQL Server Management Studio 2008.
I have a db (say ip 10.16.17.10 and called db1) and a second one (say ip 10.16.17.25 called db2).
I am trying to copy one table (and its contents) from db1 into db2.
I have the database on both (but empty in db2).
The problem is no matter how I copy/export/import, no matter what options I set in MS SQL Server Management Studio 2008 when I click 'table'->'Design' (on db2) it ALWAYS says 'Identity Spefication: NO' even tho the db1 table has it on.
From db1 I go to 'Tasks'->'export'->'source/db' and 'destination/db'->'Edit Mapping'->'Enable identity Insert' and click it on.
But no joy. ALWAYS exports without it.
I try similar thing from IMPORT on db2. Similar thing if I use COPY.
I have read MANY of the STACKOVERFLOW articles on this, they all suggest setting IDENTITY_INSERT setting to ON but when I do run below:
SET IDENTITY_INSERT [dbo].[mytable] ON
The table either doesn't exist yet or has already copied WITHOUT the identity setting on so see the error:
does not have the identity property. Cannot perform SET operation.
I have tried setting it as a property (under database properties) for db2 but when I copy/import/export never works.
Would appreciate any help here as lots of StackOverflow articles so far all seem to be having an easier time than me.
I am planning on doing this for another 50 or so tables in this database so am hoping to find a way which doesnt involve running scripts for each table.
thanks
The process of using the Export Data Wizard to copy the data from one table to another will NOT replicate all aspects of the schema (like identity and auto-increment). If you want to replicate the schema, script out your table into a create statement, change the name to db2, and create it. Then you should be able to run the export/import wizard with the identity insert option on and insert into your new table that replicates the schema of your old table.
Ended up sorting this out using MS SQL Management Studio.
Thanks to #kevin for the help regarding Import Data and Export Data. Schemas are NOT transferred across however they are the best means to transport the data once schema is up.
Found best way to MASS import/export db table schemas using below (Saved SQL create scripts to file):
Tasks->Generate Scripts->All Tables To File->with Identity on
Ran 200kb SQL file on db2 for schema.
Then ran Import Data from db1 to db2.
Done, all Identity_Inserts maintained.
thanks for help
According to the Error message I think your table does not have an IDENTITY column. Make sure that [dbo].[mytable] does have an IDENTITY column before you executing SET IDENTITY_INSERT.
SET IDENTITY_INSERT [dbo].[mytable] ON
DEMO1 (Trying to set identity ON when there is NO identity column)
--Error
'Table 'T' does not have the identity property. Cannot perform SET operation.: SET IDENTITY_INSERT T ON'
DEMO2 (Trying to set identity ON when there is identity column)
--No Errors
Follow following Steps :
From db1 I go to 'Tasks'->'export'->'source/db' and 'destination/db'->'Edit Mapping'->'Enable identity Insert' and Edit SQL - > You will able to see query structure of Table.
IN the query for eg. ID int NOT NULL, do the next step ID int NOT NULL IDENTITY(1,1)
Then proceed.
I bet it will work.

EF 4.3 DB first model not importing associations

We moved our DB from an instance of SQL 2005 to a new SQL 2008r2 server. We changed the connection strings in our app to point to new database, even modified the ProviderManifestToken from 2005 to 2008. Everything was working fine until we tried to add entities from our database to our existing edmx model. I'm using the 'update model from database' wizard to add tables to the edmx diagram. The tables will appear in the diagram but only some have their associations and/or foreign keys imported. If I switch the connection string to point back to the old 2005 sql instance everything imports correctly and associations are present. I'm happy to provide additional details if necessary. I can't find a pattern to this at all. What gives?
Update: I created a new project, added an edmx, pointed it to the 2008r2 db instance, selected tables that I know have associations but the designer failed to pick up the associations. Is there something I need to install on the SQL server to get EF to work?
It's working for now. Deleting the connection string from the web.config and then using 'Update Model from Database' and going through the 'Add new connection' dialog to point to the database on the new server seemed to make it behave. If this stops working I'll post back.
Update: Turns out I had two problems. The second was that one of the tables in our DB had two nearly identical redundant indexes on the same column; a clustered PK index and a unique, non-clustered index. So any time I created a foreign key pointing to this table the database chose the unique non-clustered index to enforce the constraint (why? I don't know). But Entity Framework didn't like it and would not create or even recognize the foreign key association. I had to delete the extra non-clustered index and re-create all the foreign keys so they would point to the clustered index. Once that was done I updated my model from the database and all associations were present.
Here's the SQL query I used to check which indexes my foreign keys were using:
SELECT *
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
ORDER BY CONSTRAINT_NAME
The UNIQUE_CONSTRAINT_NAME column for the FK in question should point to a clustered PK for it to work.
How did you move the database to the 2008 Server? Sounds like some or all of the relationships/constraints were not migrated. That would explain why the associations are not showing up when you point to the 2008 database.

Order SQL Azure Table Columns via SSMS

I know you can go into the design view of a table in SQL Server Management Studios and reorder columns as they appear in the design view, however this isn't possible with SQL Azure as the option is disabled. Is there a way to modify SQL Azure tables so that you can reorder their columns as they appear in the design view?
I have been running a number of database upgrades over the last few months to support new requirements and would like to reorder the way the columns appear in design view so they're easier to read, i.e. so they start with a primary key, followed by foreign keys, then normal columns and end with the added by, modified by fields. Its purely to make the tables more readable as I manage them over time.
Just run a script against the table. Its a bit of pseudocode but you should get the idea.
CREATE TABLE TableWithDesiredOrder(PK,FK1,FK2,COL1,COL2)
INSERT INTO TableWithDesiredOrder(PK,FK1,FK2,COL1,COL2....)
SELECT PK,FK1,FK2,COL1,COL2.... FROM OriginalTable
DROP TABLE OriginalTable
Finally Rename the table
sp_Rename TableWithDesiredOrder, OriginalTable
Just another option: I use SQL Delta to propagate my db changes from dev db up to Azure db. So in this case, I just change the col order locally using SSMS GUI, and SQL Delta will do the createnew>copytonew>dropold for me, along with my other local changes. (In Project Options, I set Preserve Column Order=Yes.)
I experienced the same with Azure SQL Database, basically my view changes with ALTER were not taken when did a SELECT * from the view, or the column headers were mixed with the column values.
In order to fix it I dropped the view and re-created it again. That worked.

SQL Server: export data via SQL query?

I have FK and PK all over my db and table data needs to be specified in a certain order or else I get FK/PK insertion errors. I'm tired of executing the wizard again and again to transfer data one table at a time.
In the SQL Server export data wizard there is an option to "Write a query to specify the data to transfer". I'd like to write the query myself and specify the correct order.
Will this solve my problem?
How do I do this? Can you provide a sample query (or link to one)
The databases are on two different servers - SQL Server 2008 on each ; The database names & permissions are the same ; each table name & col is the same ; I need Identity Insert for each table.
Disable foreign keys before importing, enable them after the import:
ALTER TABLE tablename NOCHECK CONSTRAINT ALL
ALTER TABLE tablename WITH CHECK CHECK CONSTRAINT ALL
Update: Thanks for the comments, I fixed the syntax.
You could always save the package and then open and edit the package to put things in the right order (you might have to copy the data flow several times and put dependencies between them)
You can use 3rd party tools to transfer a data; these tools disable/enable constraints automatically.

Dropping a group of tables in SQL Server

Is there a simple way to drop a group of interrelated tables in SQL Server? Ideally I'd like to avoid having to worry about what order they're being dropped in since I know the entire group will be gone by the end of the process.
At the risk of sounding stupid, I don't believe SQL Server supports the delete / cascade syntax. I think you can configure a delete rule to do cascading deletes (http://msdn.microsoft.com/en-us/library/ms152507.aspx), but as far as I know the trick with SQL Server is to just to run your drop query once for each table you're dropping, then check it worked.
I'm not sure, if Derek's approach works. You haven't mark it as best answer yet.
If not: with SQL Server 2005 it should be possible, I guess.
There they introduced exceptions (which I've not used yet). So drop the table, catch the exception, if one occurs and try the next table till they are all gone.
You can store the list of tables in a temp-table and use a cursor to traverse it, if you want to.
A diferent approach could be: first get rid of the constraints, then drop the tables in a single shot.
In other words, a DROP CONSTRAINT for every constraint, then a DROP TABLE for each table; at this point the order of execution shouldn't be an issue.
This requires the sp___drop___constraints script you can find at Database Journal:
sp_MSforeachtable #command1="print 'disabling constraints: ?'", #command2="sp_drop_constraints #tablename=?"
GO
sp_MSforeachtable #command1="print 'dropping: ?'", #command2="DROP TABLE ?"
GO
NOTE this - obviously - if you meant to drop ALL of the tables in your database, so be careful
I don't have access to SQL Server to test this, but how about:
DROP TABLE IF EXISTS table1, table2, table3 CASCADE;
I ended up using Apache's ddlutils to perform the dropping for me, which sorted it out in my case, though a solution which worked only within sql server would be quite a bit simpler.
#Derek Park, I didn't know you could comma separate tables there, so that's handy, but it doesn't seem to work quite as expected. Nether IF EXISTS nor CASCADE are recognised by sql server it seems, and running drop table X, Y, Z seems to work only if they should be dropped in the stated order.
See also http://msdn.microsoft.com/en-us/library/ms173790.aspx, which describes the drop table syntax.
The thing holding you back from dropping the tables in any order are foreign key dependencies between the tables. So get rid of the FK's before you start.
Using the INFORMATION_SCHEMA system views, retrieve a list of all foreign keys related to any of these tables
Drop each of these foreign keys
Now you should be able to drop all of the tables, using any order that you want.