Showing posts with label Sql-server. Show all posts
Showing posts with label Sql-server. Show all posts

Tuesday, November 16, 2010

Finding tables using foreign key constraint for a primary key of particular table.

Database cleanup is a on-going process for any application that has been live for many years. As updation and modification of existing objects in database is done on regular basis there are always some tables that are no more required. So as to perform a database cleanup we mostly delete these unwanted tables. But we are faced with a challenge to identify that in which tables the primary key of the unwanted table is being used as a foreign key constraint. Also another task is to identify the various stored procedures and views that might be using the table. In this post I am going to tell how to perform these tasks.

1. Finding tables that use foreign key constraint on the primary key of the table

First lets identify all the tables that are using the foreign key constraint for the primary key of the unwanted table.The following query will easily list out all these tables along with the foreign-key constraint name:

SELECT  FK_Table = FK.TABLE_NAME
,       FK_Column = CU.COLUMN_NAME
,       PK_Table = PK.TABLE_NAME
,       PK_Column = PT.COLUMN_NAME
,       Constraint_Name = C.CONSTRAINT_NAME
FROM    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
JOIN    INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
ON      C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
JOIN    INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
ON      C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
JOIN    INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
ON      C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
JOIN    (
        SELECT  i1.TABLE_NAME, i2.COLUMN_NAME
        FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
        JOIN    INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
        ON      i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
        WHERE   i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
        ) PT
ON      PT.TABLE_NAME = PK.TABLE_NAME
WHERE   PK.TABLE_NAME = 'Table_Name'

Here Table_Name is the name of the table which needs to be deleted. While running this query just replace the Table_Name with your table name.

For example I want to find out the tables which are using the primary key of table F_Fees as foreign key constraint then on running the above query we would get the output as follows:



Here FK_Table column is having the names of the tables which is having the primary key constraint.
FK_Column is having the name of the column that is having the primary key constraint.
PK_Table is the name of the table that needs to be deleted and PK_Column is the name of the column which is referenced as foreign key in other tables.
Constraint_Name is the name of the constraint.


Hence by using this query one can easily find out the various foreign key constraints that are present which relates to the primary key of the table that needs to be deleted.


2. Identifying all the stored procedure and views that might be using the unwanted table

In order to identify all the stored procedures and views that might be using the unwanted table use the following query:

SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o
ON c.id=o.id
WHERE c.TEXT LIKE '%Table_Name%'

This query will return all the stored procedure and views that are using the particular table. For example if we run this query to find a particular table then its result would be as follows:




Here name denotes the name of the database object found and xtype refers to the type of database object. P denotes stored procedure and V denotes view.

Once identified delete all such foreign constraints, stored procedures, views etc and proceed with dropping the table for cleaning up the database.

Tuesday, June 15, 2010

SQL Server 2008: Editions

Note that SQL Server 2008 has been replaced by SQL Server 2008 R2, which has different editions and price points. For more information, see SQL Server 2008 R2 Editions


SQL Server 2008 is the latest release in Microsoft's enterprise relational database platform series. In this substantial upgrade, they've packed the new database engine full of new features, but fortunately it doesn't pack any additional punch in your wallet: SQL Server 2008 is available at the same price points used by SQL Server 2005.

Let's take a look at the seven different editions of SQL Server 2008 that you can use:
  • SQL Server 2008 Express Edition replaces the Microsoft Data Engine (MSDE) as the free version of SQL Server for application development and lightweight use. It remains free and retains the limitations of MSDE with respect to client connections and performance. It's a great tool for developing and testing applications and extremely small implementations, but that's about as far as you can run with it.
  • SQL Server 2008 Workgroup is billed as a "small business SQL Server" and it offers an impressive array of functionality for a $3,899 price tag per processor. (It's also available under a 5-user license for $739). Workgroup edition maxes out at 2 CPUs with 3GB of RAM and allows for most of the functionality you'd expect from a server-based relational database. It offers limitedreplication capabilities as well.
  • The workhorse SQL Server 2008 Standard Edition remains the staple of the product line for serious database applications. It can handle up to 4 CPUs with an unlimited amount of RAM. Standard Edition 2005 introduces database mirroring and integration services. It's priced at $5,999 for a processor or $1,849 for 5 users.
  • The big kid on the block is SQL Server 2008 Enterprise Edition. With the release of 2005, Enterprise Edition allows unlimited scalability and partitioning. It's truly an enterprise-class database and it's hefty price tag ($24,999 per processor or $13,969 for 25 users) reflects its value.
  • Developers needing the full features of SQL Server 2008 Enterprise Edition for use in a non-production environment may find SQL Server 2008 Developer Edition the right tool for the job. This product has the exact same functionality as Enterprise Edition and only differs in the license. (Oh, and by the way, it's $24,949 cheaper at only $50 per license!) Microsoft also offers a direct upgrade path to convert Developer servers to production licensing
  • SQL Server 2008 Web is a specialized version of SQL Server for use in web hosting environments. Like Standard edition, it has no limitations on the amount of memory used and supports the use of up to 4 CPUs. Pricing for web edition runs $15 per processor per month.
  • SQL Server 2008 Compact is a free version of SQL Server for use in embedded environments, such as mobile devices and other Windows systems.
That sums up the licensing options available for SQL Server 2008. As you've discovered, Microsoft offers a wide variety of licenses and choosing the correct one for your environment can save you thousands of dollars.


For more details refer Microsoft Sqlserver article. Some points from this article are as follows:


Choose the Right Edition for Your Needs


Business today demands a different kind of data management solution—one that offers excellent performance, scalability, and reliability, but is also easy to use and maintain. SQL Server 2008 delivers on this by providing a Trusted, Productive and Intelligent Data Platform that can solve your data management needs.
SQL Server 2008 is available in many editions to help meet the needs of your organization.
Core EditionsSpecialized EditionsFree Editions
EnterpriseStandardWorkgroupWebDeveloperExpressCompact 3.5
Target ScenariosEnterprise workloads that need redundancy and built-in Business IntelligenceShared data scenarios in departments and small to large businessesRemote offices that need local instances of company dataFor web application hostingFull featured edition for development and testing onlyEntry level database, ideal for learning and ISV redistributionEmbedded database for developing desktop and mobile applications
CPU8 CPU4 CPU2 CPU4 CPUOS Maximum1 CPUOS Maximum
Memory2 TB Ram64 GB Ram4 GBOS MaximumOS Maximum1 GBOS Maximum
DB Size524PB524TB524TB524TB524TB10 GB4 GB

Monday, June 7, 2010

Running sql script file from .Net code - C#.net and VB.net

Many a times we get into situations where we have to execute a .sql script file from .NET code on Sql Server for eg. either to create a new database, or creating a new table, or backing up or restoring database etc. But for doing so the SqlCommand class is not useful. We can't execute the batch commands in the .sql script file using the SqlCommand class because the .sql script  file contains 'GO' (batch finalizer command) in it. Since SQL Server 2005 there is another option which is much better and preferred. That option is using SMO library which comes with SQL Server and can be used for managing everything on SQL Server 2005. You can backup, restore databases, configure permissions, replication, etc.

The following example demonstrates how to do it. Here I have my .sql script file as myscript.sql and it is in C:\ directory.

The code for it in C# is as follows:

01using System.IO;
02using Microsoft.SqlServer.Management.Common;
03using Microsoft.SqlServer.Management.Smo;
04
05namespace ConsoleApplication1
06{
07    class Program
08    {
09        private static void Main(string[] args)
10        {
11            string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
12            FileInfo file = new FileInfo("C:\\myscript.sql");
13            string script = file.OpenText().ReadToEnd();
14            SqlConnection conn = new SqlConnection(sqlConnectionString);
15            Server server = new Server(new ServerConnection(conn));
16            server.ConnectionContext.ExecuteNonQuery(script);
17        }
18    }
19}


The code for it in VB.Net is as follows:


01Imports System.Data.SqlClient
02Imports System.IO
03Imports Microsoft.SqlServer.Management.Common
04Imports Microsoft.SqlServer.Management.Smo
05
06Namespace ConsoleApplication1
07    Class Program
08        Private Shared Sub Main(args As String())
09            Dim sqlConnectionString As String "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True"
10            Dim file As New FileInfo("C:\myscript.sql")
11            Dim script As String = file.OpenText().ReadToEnd()
12            Dim conn As New SqlConnection(sqlConnectionString)
13            Dim server As New Server(New ServerConnection(conn))
14            server.ConnectionContext.ExecuteNonQuery(script)
15        End Sub
16    End Class
17End Namespace


Thus this will execute the .sql script file from the .Net code.

LinkWithin

Related Posts with Thumbnails