SQL DB Diagram Extract - sql-server

I am using SQL Server 2011 and need to create a visual representation (diagram). The current structure has no relationships (Foreign Keys) between tables and there are tables without any Primary Keys.
I have tried using SQL Database Diagrams but can't add any relationship between tables without the change happening on the DB itself.
I want to draw relationships without it making any changes.
Are there any free DB Diagram software that I can use in order to achieve this? I have tried DbVisualizer but getting same issues as with the diagram within SQL.

In your case I would do the following:
Generate scripts for your database (schema only) (as #Serg suggested already)
You can do this using SSMS: Right click your database - Tasks - Generate Scripts. Select all tables and then under Advanced, select Schema only at the Types of data to script. Save script and run it in some test environment to generate a schema only copy of your database. (If doing this on the same server, you might need to change the script a little, to give the new database another name)
Dynamically try to "guess" the foreign key relationships
Since you have 500+ tables, you could try to make this script work for
you (of course it would need some testing and tuning to adapt it for your
case) but I used it in the following scenario and it worked.
Hopefully you do have a naming convention. In this script it is assumed that the referenced keys are named the same, but this can be configured.
So, I created the following tables:
CREATE TABLE test (testid int identity(1,1) UNIQUE, description varchar(10))
CREATE TABLE test_item (id int identity(1,1) UNIQUE, testid int)
And the following indexes on their primary keys (normally, you should have them too)
CREATE CLUSTERED INDEX [ix_testid] ON [dbo].[test]([testid] ASC)
CREATE CLUSTERED INDEX [ix_testitemid] ON [dbo].[test_item]([id] ASC)
I did not create a foreign key relationship.
Next I ran the script from the Automatically guessing foreign key constraints article and I managed to get the following result:
Executing all the ALTER statements generated from this script you could get your relationships created in your new database - generate the diagram from this database and you are done! :)
ps. I would suggest you test it out step by step, for example with one table first and then adding others and checking the results.
You can try a working demo of my little test here.
Good luck!

Related

SQL Server: foreign key showing one to one relation instead of one to many

From some mystical reason I starter the database design with the inbuilt Database Diagrams GUI designer (Server Management Studio), actually I only did the first 2 tables (users and product) there rest were done using query commands.
It turns out that at the end there’s something I didn’t expect between:
users (table)
product(table)
I’ve created a foreign key column (“users_id”) in the “product” table pointing to the “users” table (column “users_id”).
Instead of having a one to many relation It seem to be a one to one relation?
Users table is referencing the product table and I don’t want this.
What is the problem?
edit: 4-sep-2014 10:48
I've droped the FK_product_TO_users constraint and created a new one, but still the results are the same.
ALTER TABLE product
DROP CONSTRAINT FK_product_TO_users
GO
ALTER TABLE product
ADD
CONSTRAINT FK_product_TO_users
FOREIGN KEY (users_id)
REFERENCES users (users_id)
edit: 4-sep-2014 12:51
I've rebuilt the database, by using just Queries with no GUI help in the table design. The problem related to FK_product_TO_users was fixed, still I don't know why.
It comes out that after the resolution the same issue is present in two other tables with 2 FK relations.
Besides this, inputting data in those tables seems to work fine.
I'm wondering if this is just a bug of the GUI in the Database Diagram?
This is really interesting one.
You can do one thing: just delete the key FK_product_to_users and rebuild the key.
You do NOT need to delete users_id from product table.

Changing columns to identity (SQL Server)

My company has an application with a bunch of database tables that used to use a sequence table to determine the next value to use. Recently, we switched this to using an identity property. The problem is that in order to upgrade a client to the latest version of the software, we have to change about 150 tables to identity. To do this manually, you can right click on a table, choose design, change (Is Identity) to "Yes" and then save the table. From what I understand, in the background, SQL Server exports this to a temporary table, drops the table and then copies everything back into the new table. Clients may have their own unique indexes and possibly other things specific to the client, so making a generic script isn't really an option.
It would be really awesome if there was a stored procedure for scripting this task rather than doing it in the GUI (which takes FOREVER). We made a macro that can go through and do this, but even then, it takes a long time to run and is error prone. Something like: exec sp_change_to_identity 'table_name', 'column name'
Does something like this exist? If not, how would you handle this situation?
Update: This is SQL Server 2008 R2.
This is what SSMS seems to do:
Obtain and Drop all the foreign keys pointing to the original table.
Obtain the Indexes, Triggers, Foreign Keys and Statistics of the original table.
Create a temp_table with the same schema as the original table, with the Identity field.
Insert into temp_table all the rows from the original table (Identity_Insert On).
Drop the original table (this will drop its indexes, triggers, foreign keys and statistics)
Rename temp_table to the original table name
Recreate the foreign keys obtained in (1)
Recreate the objects obtained in (2)

foreign key in database

i am using linq to sql .dbml ,
May i know what is the best way to add foreign key constraint to the database?
ALTER TABLE Staffs
Add CONSTRAINT fk_Staffs FOREIGN KEY(UserId) REFERENCES Users(Id);
i can write this with no problem. But when my database table increases, i have hard time to maintain the Add Constraint foreign script . Each time when i have multiple update to the database columns, then i will crack my head to update those alter table script.
Could there be a simple process for this? In the .dbml, i can drag and drop the association to add the foreign key, i wonder is there a way that i can export those foreign key into script which like what i wrote above? this is good when i want to do the deployment.
Or must i write the alter script and update it whenever there is changes on tables?
please advice
You only need to do this once per database update that actually changes a FK relationship.
In the context of doing a database refactoring this is usually not a big deal of the whole refactoring.
But if you don't like writing your scripts you can use the table designer i SQL Management Studio.
Right click table -> Design
Right click on the appropritate database column (one of the rows in the designer) -> Relationships
In the dialog, add a new relationship and select related tables and columns in the properties editor.
Done.
This is the right way to do it. You can also do it in the designer as written in another answer here but that way if you have to promote from development to production you must do it all by hand and that is very tedious and can easilly lead to errors.
A compromise can be to use the designer to do the changes and in SQL management studio use the right mouse click and select `Script object...´. Than you do not have to type that much.
You mention a change of table names. Well, that should not happen that often!
If it happens a lot, I advise you to create some naming conventions with your team about how to name your columns (and stick to them) and the amount of work will be limited.

Automated Filegroup Migration in SQL Server

Recently I've been trying to restructure an old database that was not designed with filegroups (just the default PRIMARY) and, among other things, move a bunch of tables to a new Data filegroup residing on a SAN. I know how to migrate the data:
ALTER TABLE MyTable
DROP CONSTRAINT PK_MyTable WITH (MOVE TO [MyDB_Data])
ALTER TABLE MyTable
ADD CONSTRAINT PK_MyTable
PRIMARY KEY CLUSTERED (MyID)
ON [MyDB_Data]
But damned if this isn't the most tedious work I've ever had to. And it's error-prone. At one point I was halfway (I assume, since there's no progress indicator) through moving a 30 GB table before I realized that I had accidentally included one of the value columns in the PK. So I had to start all over again.
It's even worse when the table has a lot of dependencies. Then I can't just drop the primary key; I have to drop and recreate every foreign key that references it. This leads to hundreds of lines of boilerplate; multiply by 100 tables and it becomes downright asinine. My wrists hurt.
Has anybody come up with a shortcut for this? Are there maybe any tools out there (priced with the notion of one-time-use in mind) that can do it? Perhaps somebody here has had to go through this process before and wrote their own tool/script that they wouldn't mind sharing?
SSMS won't do it, obviously - it can only generate migration scripts for non-clustered indexes (and they have to be indexes, not UNIQUE constraints - on at least a few tables, for better or for worse, the clustered index is not actually the primary key, it's a different UNIQUE constraint).
It's not that the syntax is so complicated that I can't write a code gen for it. At least for the basic drop-and-recreate-the-primary-key part. But add in the overhead of figuring out all the dependencies and generating drop/recreate scripts for all the foreign keys and this starts to feel like it's just over that threshold where it's more work to automate and fully test than it is to just do every table manually as with the example above.
So, the question is: Can this process be automated in any reasonably straightforward way? Are there any alternatives to what I've written above?
Thanks!
The simplest way to do it, IMO, would be to use one of the schema comparison tools (My tool, red gate's SQL Compare, Apex SQL Diff as a couple of examples) to create a script of your schema. Then, edit that script to create all the objects, empty, in the right file groups. Having done that, you can then use the same tools to compare your new DB with correct filegroups, and they will generate the scripts to migrate the data for you. It's worth testing with multiple ones to find which is the most appropriate for you.

SQL Server Check/NoCheck difference in generated scripts

I am trying to sync up the schemas between to different databases. Basically, I ran tasks->Generate Scripts with SQL Server Management Studio (2005) on both databases and am comparing the output with a diff tool.
For some reason, one script adds the constraint WITH CHECK and one WITH NO CHECK, followed by both constraints being re-enabled.
I for the first database I get:
ALTER TABLE [dbo].[Profile] WITH CHECK ADD CONSTRAINT [FK_Profile_OrganizationID] FOREIGN KEY([OrganizationID])
REFERENCES [dbo].[Organization] ([OrganizationID])
GO
ALTER TABLE [dbo].[Profile] CHECK CONSTRAINT [FK_Profile_OrganizationID]
GO
The second database generates as
ALTER TABLE [dbo].[Profile] WITH NOCHECK ADD CONSTRAINT [FK_Profile_OrganizationID] FOREIGN KEY([OrganizationID])
REFERENCES [dbo].[Organization] ([OrganizationID])
GO
ALTER TABLE [dbo].[Profile] CHECK CONSTRAINT [FK_Profile_OrganizationID]
GO
So I have two questions:
Is the end result the same?
(Edit:
It seems that a lot of people are picking up on only the first statement of the two scripts. I am interested in the end result of the entirety of both scripts.)
If the end result is the same, why does Management Studio generate them differently for different databases?
The end result is not the same!
SQL Server will not trust the uniqueness of the FK is it is not checked. This means additional processing is required if you use the column in a query.
Long story short is that you should get SQL Server to check the column so it's considered trusted.
As for why they're different from different servers, check the isnottrusted column in sys.foreign_keys. This may affect what SSMS is generating?
For more of a rant on this, check my other answer that relates to FK & NO CHECK/ CHECK options.
Yes the two scripts are different
WITH CHECK will check existing data against the new constraint.
WITH NOCHECK will not check existing data against the new constraint. This will allow you to have child records without a corresponding parent.
EDIT:
As for why SSMS is doing this I have no idea
Both are SQL Server 2005 servers? As the result is the same, the code generation tool maybe use different routines based in different versions of the product

Resources