Where Used Statements in SQL - sql

I have data used primarily in one table in a database and referenced in several different tables. I need to correct the data. Is it possible to write a "where-used" statement that will search every table in the database and return all tables where the data is referenced?
I am using SQL 2005.
Thanks.

I've found this sql statement here:
SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,
SCHEMA_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
type_desc AS ConstraintType
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT'
AND OBJECT_NAME(OBJECT_ID) LIKE 'FK_%'
NOTE:- I name all foreign key constraints starting with FK_ so it is easy to filter them.

Try adding a diagram to the database, and drop all of the tables onto it. If I've interpreted your question correctly you're trying to understand a database schema that already exists? IF you use the diagram it will draw on the references for you which will allow you to see where the data is linked in your table structure.
As for SQL you can use joins, or where conditions to link data from different tables.
What are you trying to "correct"?

In Management Studio you can right click on a table/view/stored procedure and select View Depenencies. In the dependencies window you can choose to view objects that the selected item depends on or view the items which depend on the selected item.

You can't do it after the fact, but at the table design time you can set up relationships to "ON UPDATE CASCADE".

You could reverse engineer the database (see this posting for a script that does this) if it has foreign keys physically present in the database. If this is not the case then you are up for some manual detective work.
Visio professional has a tool for reverse engineering a database. 2003 doesn't play nicely with SQL Server 2005, so you will need either:
Visio 2007
Modify the script linked to above so it doesn't generate schema references and load the script into a SQL Server 2000 database. Then, reverse engineer from the SQL 2000 DB.
If you don't have foreign keys or have incomplete foreign key coverage, you can look for them manually (for example, look for fields with similar looking codes to reference data) and manually annotate the keys in the diagram. Don't try to do this with the diagramming tool that comes in SSMS as it can attempt to populate the FKs back into the database.

Related

Copy Table Constraints/Keys along with Data and Structure

I have table "TableA", I want to make a copy of it "TableA_Copy", when I use the below script, it creates Table and data, but Constraints are not copied, is it possible copy the constraints along with Structure and Data
SELECT * INTO TableA_Copy FROM TableA
Note am using SQL Server 2016
Right click on the database and go to tasks->Generate script.
Select the table you want TableA, go to next step and ynder advanced options select data and schema.
Save the script or have it in a new query window.
Once the script is generated, replace TableA with TableA_copy
This way you will get data, schema and all the constraints. Remember to change the name of constraints to avoid any errors.
If you mean programmatically, then yes there are a number of ways in tsql to accomplish this by using the INFORMATION_SCHEMA views. The particular ones you will need for the table/columns are INFORMATION_SCHEMA.TABLES, and INFORMATION_SCHEMA.COLUMNS. For the constraints you can use INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE which will provide you the PK and FKs and INFORMATION_SCHEMA.CHECK_CONSTRAINTS for all check constraints.
Using these you can rebuild the table, complete, for use as you indicate above.

Update audit database name in triggers and views of main database?

I have a a system with two databases, main database and audit database. A lot of the triggers and table views in the main database and audit database are referencing from one database to the other. No I needed to change both databases names but unfortunately they failed to work because they still have the old names in the code.
Is there a code to search and replace the old name used for referencing or in dependence?
Thank you,
You will have to manually fix the references but you can leverage some sql to find the offending objects.
select OBJECT_NAME(id) as ObjectName
, text as ObjectCode
from sys.syscomments
where text like '%YourReplacedDatabaseName%'
That will give you a list of functions, procedures, views etc that have the old database name in the code. You will however have to recompile each object after you have updated the code. You could probably utilize some dynamic sql around this to do it for you but I would be nervous about changes on that scale automatically.

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.

Using name of a database inside a sql script for a full table name

I struggled for a while with a bug, and then found out the reason for it in a database stored procedure code, which contained the old name of a database in a table name, whereas the current database name was already different. So, I'd like to ask:
Is there a situation in which using a database name as a part of a full table name (database name + schema name + table name) can be justified (provided we don't touch tables in other databases) or is it always a bad practice? How to correctly use a database name in sql scripts to keep code neutral to a specific database?
Code just for an illustration:
CREATE PROCEDURE [dbo].[MyProc]
AS
BEGIN
DELETE FROM [MyDatabase].[dbo].[MyTable]
END
No, you shouldn't use database names in a stored procedure unless you need to address two databases.
It causes exactly the kinds of bugs you're seeing. When the database name changes, all your SP code breaks, or continues working, but on the old database.
It does make sense if you are sending a SQL query to the database, but only if the application dynamically picks the database name to insert into the query.
My suggestion is that you do a full export of your database schema, and search for database names that are hardcoded and remove them.
It really depends on how your scripts are implemented.
Even if you don't refer to a table as
[MyDatabase].[dbo].[MyTable]
you will still need to refer to the database by:
USE [MyDatabase]
earlier in the script.
It is possible to mix trusted database tables in a single query. When someone do this,it is justified and mandatory to include database on table 'path'.
I don't found a reason out of this scenario if stored procedure and table is on the same database.
You can search all database name occurencies through database catalog in order to fix your development. For SQL Server 2005:
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%databasename%'
GO
For SQL Server 2000:
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%databasename%'
GO

MySql to Sql Server migration questions

I did a succesful migration from MySql to Sql Server using the migration tool.
Unfortunately for some reason it labels the tables database.DBO.tablename instead of just database.tablename
I have never used Sql Server so perhaps this is just the way they name their tables.
When I do:
SELECT TOP 1000 [rid]
,[filename]
,[qcname]
,[compound]
,[response]
,[isid]
,[isidresp]
,[finalconc]
,[rowid]
FROM [test].[calibration]
it does not work
But, when I do:
SELECT TOP 1000 [rid]
,[filename]
,[qcname]
,[compound]
,[response]
,[isid]
,[isidresp]
,[finalconc]
,[rowid]
FROM [test].[dbo].[calibration]
it works.
Does anyone know why it prefixes with DBO?
dbo is the standard database owner for anything you create (tables, stored procedures, etc,..), hence the migration tool automatically prefixing everything with it.
When you access something in Sql Server, such as a table called calibration, the following are functionally equivalent:
calibration
dbo.calibration
database_name.dbo.calibration
server_name.database_name.dbo.calibration
MySql doesn't, as far as I remember (we migrated a solution from MySql to SqlServer about 12 months ago using custom scripts executed by nant) support database owner's when referencing objects, hence you're probably not familiar with four part (server_name.database_name.owner_name.object_name) references.
Basically, if you want to specify the database you're accessing, you also need to specify the "owner" of the object. i.e, the following are functionally identical:
USE [master]
GO
SELECT * FROM [mydatabase].[dbo].[calibration]
USE [mydatabase]
GO
SELECT * FROM [calibration]
SqlServer uses an owner name when it references tables. In this case, dbo is the owner.
MySQL doesn't use owner for table names, which is why you didn't see those names before.
SQL Server has something called schemas, in this case the default schema is dbo but it could be anything you wanted. Schemas are used to logically group objects. So you can create a Employee schema and have all the Employee tables, views, procs and functions in there, this then also enables you to give certain users only access to certain schemas
Tell me your migration tool you have used, and let me know the version of from and to databases.
Regards
Eugene
You do have an issue here with the default schema, if it's set to 'dbo' for the user you logged in as you don't need to specify it. See http://msdn.microsoft.com/en-us/library/ms176060.aspx