2008 | SansSQL

Monday, December 29, 2008

@@CONNECTIONS and @@MAX_CONNECTIONS

@@CONNECTIONS returns the number of attempted connections, either successful or unsuccessful since SQL Server was last started.Connections are different from users. For example, Applications can open multiple connections to SQL Server without the user observing the connections.
Syntax: - Select @@CONNECTIONS
@@MAX_CONNECTIONS is the maximum number of connections allowed simultaneously to the SQL server. The number returned is not necessarily the number currently configured. The actual number of user connections allowed also depends on the version of SQL Server installed and the limitations of your applications and hardware.
To Change the max connections, Use sp_configure
Syntax: - Select @@MAX_CONNECTIONS
@@CONNECTIONS is incremented with each login attempt, therefore @@CONNECTIONS can be greater than @@MAX_CONNECTIONS.
 
Example: -
SELECT GETDATE() AS 'Current Date and Time',
@@CONNECTIONS AS 'Login Attempts',
@@MAX_CONNECTIONS AS 'Max Connections Allowed'

Wednesday, December 24, 2008

Code Names of SQL server releases

         SQL Server Release          Project Code Name
 

  1. SQL Server 2008                Katmai
  2. SQL Server 2005                Yukon
  3. SQL Server 2000 64 bit       Liberty
  4. SQL Server 2000 32 bit       Shiloh
  5. SQL Server 7.0                   Sphinx
  6. SQL Server 6.5                   Hydra
  7. SQL Server 6.0                   SQL95

 

Wednesday, December 10, 2008

Add a logo to the Report Manager

Everyone wants to put their custom logo to the Report Manager. Here is how it can be achieved.

You just need to change the below code for .msrs-uppertitle in the ReportingServices.css file which is located at
C:\Program Files\Microsoft SQL Server\MSSQL.3\Reporting Services\ReportManager\Styles

Note : Before doing this please backup the ReportingServices.css file for safety.

Put the below code under .msrs-uppertitle and you will be able to see your custom logo on the report Manager.

.msrs-uppertitle
{
BACKGROUND: url(Image Location) no-repeat;
HEIGHT: 35px;
WIDTH: 120px;
TEXT-INDENT: -5000px;
}

Finding Restore and Backup dates

/*Works for both SQL 2000 and SQL 2005 */

USE msdb

GO

SELECT
destination_database_name AS DBRestored ,
restore_date AS RestoreDate ,
RH.USER_NAME AS RestoredBY,
BS.name AS BackupName,
BS.USER_NAME AS DBBackedUpBY,
BS.server_name SourceServerName,
BackupType= CASE
                       when BS.type='D'  Then 'Database '
                       when BS.type='I'   Then 'Differential database'
                       when BS.type='L'  Then 'Log'
                       when BS.type='F'  Then 'File or filegroup'
                       when BS.type='G'  Then 'Differential file'
                       when BS.type='P'  Then 'Partial '
                       when BS.type='Q'  Then 'Differential partial '
END,
BS.database_name AS SourceDB,
physical_name AS SourceFile,
backup_start_date AS BackupDate
FROM RestoreHistory RH
INNER JOIN BackupSet BS
ON RH.backup_set_id = BS.backup_set_id
INNER JOIN BackupFile BKF
ON BKF.backup_set_id = BS.backup_set_id
WHERE destination_database_name='pubs'
ORDER BY RestoreDate

Tuesday, November 18, 2008

Query to Find time remaining to complete database backup or restore in SQL 2005

USE master
GO

SELECT
          Percent_Complete,
          Start_Time ,
          Command,
          b.Name AS DatabaseName, --Sometimes this will be "Main" as the database will not be accesiable.
          DATEADD(ms,estimated_completion_time,GETDATE()) AS RemainTime,
          (estimated_completion_time/1000/60) AS MinutesToFinish
FROM sys.dm_exec_requests a
          INNER JOIN sys.databases b
          ON a.database_id = b.database_id
WHERE
          Command like '%Restore%'
          OR Command like '%Backup%'
          AND Estimated_Completion_Time > 0

When was my table last scaned or updated?

USE DatabaseName
GO

SELECT
         t.name,
         i.last_user_lookup,
         i.last_user_scan,
         i.last_user_seek,
         i.last_user_update
FROM sys.dm_db_index_usage_stats i
         INNER JOIN sys.tables t
         ON i.object_id = t.object_id
WHERE
         database_id = db_id( 'DatabaseName' )

Monday, November 17, 2008

Find Domain Name Using T-SQL

DECLARE @Domain varchar(100), @key varchar(100)

SET @key = 'SYSTEM\ControlSet001\Services\Tcpip\Parameters\'
EXEC master..xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key=@key,@value_name='Domain',@value=@Domain OUTPUT
SELECT 'Server Name: '+@@servername + ' Domain Name:'+convert(varchar(100),@Domain)

Alternative ways,
1. SELECT DEFAULT_DOMAIN()
2. EXEC Master.dbo.xp_LoginConfig 'Default Domain'

Thursday, November 13, 2008

Which SQL Statements are Currently Executing on my Database?

SELECT [Spid] = session_Id
, ecid
, [Database] = DB_NAME(sp.dbid)
, [User] = nt_username
, [Status] = er.status
, [Wait] = wait_type
, [Individual Query] = SUBSTRING (qt.text, er.statement_start_offset/2,
(CASE WHEN er.statement_end_offset = -1
THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
ELSE er.statement_end_offset END - er.statement_start_offset)/2)
,[Parent Query] = qt.text
, Program = program_name
, Hostname
, nt_domain
, start_time
FROM sys.dm_exec_requests er
INNER JOIN sys.sysprocesses sp ON er.session_id = sp.spid
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle) as qt
WHERE session_Id > 50 -- This is to ignore system SPID's.
AND session_Id NOT IN (@@SPID) -- This is to ignore this current Statement/Session.

Wednesday, October 15, 2008

Issue with renaming the objects using Management Studio 2005

Whenever we rename an object like stored procedure, function, view or trigger using the management studio in SQL server 2005, the syscomments table will not be updated. Hence when we try to get the text/code of the renamed object using the sp_helptext or OBJECT_DEFINITION () we will get the text/code of the object with the old name itself.

Try it yourself:

Use AdventureWorks
Go
CREATE PROC TestRename AS
Print ‘XYZ’
GO

Now, rename this SP using the management studio object list to “RenameTest”
Now Execute the below Query on AdventureWorks Database.

sp_helptext RenameTest

Now if you observer the result pane, the result will be the same statement with the procedure name still not changed even after renaming the SP using the management studio. The result will be as shown below.

CREATE PROC TestRename AS
Print 'XYZ'

Friday, October 10, 2008

When was my database last used???


Use <DatabaseName>
GO

SELECT DB_NAME() as DatabaseName,
s1.sql_handle,
(SELECT TOP 1 SUBSTRING(s2.text,statement_start_offset / 2+1 ,
( (CASE WHEN statement_end_offset = -1
THEN (LEN(CONVERT(nvarchar(max),s2.text)) * 2)
ELSE statement_end_offset END) - statement_start_offset) / 2+1)) AS sql_statement,
execution_count,
plan_generation_num,
last_execution_time,
total_worker_time,
last_worker_time,
min_worker_time,
max_worker_time,
total_physical_reads,
last_physical_reads,
min_physical_reads,
max_physical_reads,
total_logical_writes,
last_logical_writes,
min_logical_writes,
max_logical_writes
FROM sys.dm_exec_query_stats AS s1
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS s2
WHERE s2.objectid is null
ORDER BY s1.sql_handle, s1.statement_start_offset, s1.statement_end_offset

SQL 2005 SSIS and Excel 2007

Most of us know how to use an Office Excel file in an SSIS package. As long as we use an Excel file with the .xls extension it would be fine. But, when it comes to Office Excel 2007 it would be a bit different. The Connection manager for Excel files option that we usually choose will not work.

Since Office Excel 2007 and its .xlsx extension came after a long time after SQL Server 2005 release and since this new format is entirely different from the previous formats we have a little problem in using Connection manager for Excel files option with Excel 2007.This was sorted out with the Service Pack 2. This Service Pack gave us a new driver which could be used for Office Excel 2007 files.
Here are the brief steps on how to create a connection manager for Excel 2007.
In a new or existing package,

1. Add a New Connection and choose the connection manager type either ADO.NET or OLEDB by right-clicking on the Connection Managers tab.

2. Click on New and under the Provider drop-down list, select Microsoft Office 12.0 Access Database Engine OLE DB Provider

3. Click OK

4. Click on “All” which is located on the left side of the connection manager window, and type “Excel 12.0” against the Extended Properties.

5. Now go back to the Connections tab and type in the file path of the Excel 2007 file along with the file name there.


6. Click OK and you are done.
7. The same can be used for Access database 2007.

Thursday, September 25, 2008

SQL Server 2005's 5th system database - MSSQLSystemResource (The Invisible Database)

MSSQLSystemResource is a database that complements the master db. It is like the name smartly impels a resource database.
All system stored procedures, views and functions are stored here.

This database is hidden from the user. We can't view it in Object Explorer or with the use of sp_helpDB or by selecting from a sys.databases view. Resource database does not contain any of user data. This database has to be backed up using file-based backup or by using Drive Backups.

So how do we know its presence?
-Go to the Data directory of your SQL installation [Install Drive]:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data and there you will find the MSSQLSystemResource.mdf and MSSQLSystemResource.ldf.

If you want to see what is there in this database:
  1. Stop the SQL Server service.
  2. Copy both files and rename the copies to MSSQLSystemResource_Test.mdf and MSSQLSystemResource_Test.ldf.
  3. Start the SQL server service
  4. Attach the new files.
  5. Query the database.

Wednesday, August 6, 2008

Search the Database

Searching for an object in a SQL 2000 Database is easier by using this undocumented stored procedure sp_MSobjsearch. This can be used to search any SQL objects such as User Table, System Table, View, SP, triggers, columns, etc...


EXEC sp_MSobjsearch
=============================================
--PARAMETERS
=============================================
@searchkey default NULL
@dbname default current db = db_name(), valid DB name or * (ALL)
@objecttype default 1 (user table), can be valid objtype or 4096 (ALL), see remarks @hitlimit default 100 rows, 0 is all results
@casesensitive default 0, only valid when server is case sensitive
@status default 0 = no status, 1 = send percentage progress status back based
database/step
@extpropname default NULL
@extpropvalue default NULL

=============================================
-- REMARKS
=============================================
@objecttype
user table = 1 from @dbname..sysobjects
system table = 2 from @dbname..sysobjects
view = 4 from @dbname..sysobjects
sp = 8 from @dbname..sysobjects
rf(repl sp) = 16 from @dbname..sysobjects
xp = 32 from @dbname..sysobjects
trigger = 64 from @dbname..sysobjects
UDF = 128 from @dbname..sysobjects
DRI Constraints = 256 from @dbname..sysobjects
log = 512 from @dbname..sysobjects
column = 1024 from @dbname..syscolumns
index = 2048 from @dbname..sysindexes
all = 4096
=============================================

Wednesday, July 16, 2008

Delete from Registry using SQL

xp_regdeletekey and xp_regdeletevalue are the two undocumented stored procedures that helps in deleting values and keys from registry. These stored procedures should be used very vary carefully as there are chances of harming the system and system may crash.

xp_regdeletekey
This is an extended stored procedure that will delete an entire key from the registry.
EXEC xp_regdeletekey @rootkey,@key
Example:-
EXEC master..xp_regdeletekey @rootkey='HKEY_LOCAL_MACHINE',
@key='SOFTWARE\Test'

xp_regdeletevalue

This is an extended stored procedure that will delete a particular value for a key in the registry.

EXEC xp_regdeletevalue @rootkey,@key,@value_name

Example:-

EXEC master..xp_regdeletevalue @rootkey='HKEY_LOCAL_MACHINE', @key='SOFTWARE\Test', @value_name='TestValue'

Registry writing and regisrty reading through SQL

In SQL server we have 2 undocumented stored procedures for reading from registry and for writing into registry. For reading from registry we use the xp_regread and for writing into registry we use xp_regwrite undocumneted extended stored procedures. These two SP`s can be found in master database of a particular server.

Usage :-
EXEC xp_regread @rootkey, @key,[@value_name],[@Value]
Example:-
EXEC master.dbo.xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key= 'SOFTWARE\Microsoft\Microsoft SQLServer\80\Replication\Subscriptions\',
@value_name= 'SubscriberEncryptedPasswordBinary'

EXEC xp_regwrite @rootkey,@key,@value_name,@type,@value
Example:-
EXEC master..xp_regwrite @rootkey='HKEY_LOCAL_MACHINE', @key='SOFTWARE\Test',
@value_name='TestValue', @type='REG_SZ', @value='Test'

Undocumented stored procedure for retrieving SQL Agent properties

sp_get_sqlagent_properties is and undocumented stored procedure to retrive the SQL Agent properties of a particular server. This stored procedure can be found in msdb database.

Usage:
EXEC msdb..sp_get_sqlagent_properties

Undocumented stored procedure:: sp_MS_upd_sysobj_category

sp_MS_upd_sysobj_category is an undocumneted stored procedure which Enables or disables a special system mode where all newly created objects are automatically shown as system objects in enterprise manager. sp_MS_upd_sysobj_category accepts a parameter @Mode. @Mode can either be 1 or 2. Setting the value of @Mode to 1 enables this special system mode and setting it to 2, disables it. Among other things, sp_MS_upd_sysobj_category allows the creation of user-defined INFORMATION_SCHEMA views.

Usage:
EXEC master.dbo.sp_MS_upd_sysobj_category @Mode
@Mode = 1 or 2
1=Enable
2=Disable

Enable special system mode:
EXEC master.dbo.sp_MS_upd_sysobj_category 1

Disable special system mode:
EXEC master.dbo.sp_MS_upd_sysobj_category 2

Friday, July 11, 2008

UnDocumented stored proc to read the error log

EXEC sp_readerrorlog

sp_readerrorlog is an undocumented stored procedure which helps in reading the SQL server error log.

UnDocumented stored proc to find the primary key and foreign key Constraints defined on a table

EXEC sp_MStablekeys @TableName

sp_MStablekeys is an undocumented stored procedure to find all the primary keys and foreign keys defined on a particular table in SQL 2000 and SQL 2005.
This Stored procedure accepts a parameter @TableName and gives the primary keys and foreign keys defined on a that table.

UnDocumented stored proc to find the Check Constraints used in a table

EXEC sp_MStablechecks TableName

sp_MStablechecks is an undocumented Stored Procedure in SQL 2000 and SQL 2005 which helps in finding the various Check constraints used in a particular table. This stored proc accepts a parameter TableName and gives the various check constraints used in that table.

UnDocumented stored proc to find the Table references.

EXEC sp_MStablerefs Table_Name

sp_MStablerefs is an undocumented Stored procedure in SQL 2000 and SQL 2005 to find the referenced tables of the given table (Table name passed to the SP).

Tuesday, July 8, 2008

Stored Procedure to find Primary keys and foreign keys of a table.

Here are the Stored Procedures to find the Primary keys and Foreign keys of a table.

1. SP to find Primary keys on a particular table

EXEC sp_pkeys 'Table_Name'

2. SP to find Foreign keys on a particular table

EXEC sp_fkeys 'Table_Name'

Tuesday, July 1, 2008

Recovery model and status of all databases

SELECT name,
DATABASEPROPERTYEX(name, 'Recovery') as [Recovery Model],
DATABASEPROPERTYEX(name, 'Status') as Status
FROM master.dbo.sysdatabases
ORDER BY 1

Use this query to get the recovery model and status of all the databases present in the server.

OR

EXEC sp_msforeachdb 'Select databasepropertyex(''?'', ''recovery'')as ''Recovery Model of ? Database'''

To find only the recovery model of all the databases.

Monday, June 16, 2008

An easy way to track the growth of your database

Create Proc GTrack (@DBName varchar(40))
AS
Select @DBName as [Growth Track of database]
Select BackupDate = convert(varchar(10),backup_start_date, 111) ,SizeInGigs=floor( backup_size/1024000000) from msdb..backupset where database_name = @DBName and type = 'd' order by backup_start_date desc


--EXEC GTrack 'PUBS'

Thursday, June 12, 2008

What is an execution plan? When would you use it? How would you view the execution plan?

An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by the SQL Server query optimizer for a stored procedure or ad-hoc query and is a very useful tool for a developer to understand the performance characteristics of a query or stored procedure since the plan is the one that SQL Server will place in its cache and use to execute the stored procedure or query. From within Query Analyzer is an option called "Show Execution Plan" (located on the Query drop-down menu). If this option is turned on it will display query execution plan in separate window when query is ran again.

Virtual Tables a Trigger uses

Inserted and Deleted are the two tables that are virtual and is used by a trigger in order to store the data that is inserted and deleted using a trigger.

What is the basic functions for master, msdb, model, tempdb databases?

The Master database holds information for all databases located on the SQL Server instance and is the glue that holds the engine together. Because SQL Server cannot start without a functioning master database, you must administer this database with care.
The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping.
The tempdb holds temporary objects such as global and local temporary tables and stored procedures.
The model is essentially a template database used in the creation of any new user database created in the instance.

What is the basic functions for master, msdb, model, tempdb databases?

The Master database holds information for all databases located on the SQL Server instance and is the glue that holds the engine together. Because SQL Server cannot start without a functioning master database, you must administer this database with care.
The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping.
The tempdb holds temporary objects such as global and local temporary tables and stored procedures.
The model is essentially a template database used in the creation of any new user database created in the instance.

Rebuild Master Database

Shutdown Microsoft SQL Server 2000, and then run Rebuildm.exe. This is located in the Program Files\Microsoft SQL Server\80\Tools\Binn directory.
In the Rebuild Master dialog box, click Browse.
In the Browse for Folder dialog box, select the \Data folder on the SQL Server 2000 compact disc or in the shared network directory from which SQL Server 2000 was installed, and then click OK. Click Settings. In the Collation Settings dialog box, verify or change settings used for the master database and all other databases.Initially, the default collation settings are shown, but these may not match the collation selected during setup. You can select the same settings used during setup or select new collation settings. When done, click OK.
In the Rebuild Master dialog box, click Rebuild to start the process. The Rebuild Master utility reinstalls the master database. To continue, you may need to stop a server that is running.

What is the STUFF function and how does it differ from the REPLACE function?

STUFF function to overwrite existing characters. Using this syntax, STUFF(string_expression, start, length, replacement_characters), string_expression is the string that will have characters substituted, start is the starting position, length is the number of characters in the string that are substituted, and replacement_characters are the new characters interjected into the string. REPLACE function to replace existing characters of all occurance. Using this syntax REPLACE(string_expression, search_string, replacement_string), where every incidence of search_string found in the string_expression will be replaced with replacement_string.

What are the OS services that the SQL Server installation adds?

  • MS SQL SERVER SERVICE
  • SQL AGENT SERVICE
  • DTC (Distribution transac co-ordinator)

What are the different types of replication?

The SQL Server 2000-supported replication types are as follows:·
  • Transactional
  • Snapshot
  • Merge

Snapshot replication distributes data exactly as it appears at a specific moment in time and does not monitor for updates to the data. Snapshot replication is best used as a method for replicating data that changes infrequently or where the most up-to-date values (low latency) are not a requirement. Whensynchronization occurs, the entire snapshot is generated and sent to Subscribers.
Transactional replication, an initial snapshot of data is applied at Subscribers, and then when data modifications are made at the Publisher, the individual transactions are captured and propagated to Subscribers.
Merge replication is the process of distributing data from Publisher to Subscribers, allowing the Publisher and Subscribers to make updates while connected or disconnected, and then merging the updates between sites when they are connected.

What is sp_configure commands and set commands?

Use sp_configure to display or change server-level settings. To change database-level settings, use ALTER DATABASE. To change settings that affect only the current user session, use the SET statement.

What command do we use to rename a db?

sp_renamedb 'oldname' , 'newname'

What is the difference between a local and a global variable?

A local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for the duration of the compound statement.
A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection are closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time.

What is log shipping?

Log shipping is the process of automating the backup of database and transaction log files on a production SQL server, and then restoring them onto a standby server. Enterprise Editions only supports log shipping. In log shipping the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same db can be used this as the Disaster Recovery plan. The key feature of log shipping is that is will automatically backup transaction logs throughout the day and automatically restore them on the standby server at defined interval.

What is Raiseerror?

Stored procedures report errors to client applications via the RAISERROR command. RAISERROR
doesn't change the flow of a procedure; it merely displays an error message, sets the @@ERROR
automatic variable, and optionally writes the message to the SQL Server error log and the NT
application event log.

What is @@ERROR?

The @@ERROR automatic variable returns the error code of the last Transact-SQL statement. If there was no error, @@ERROR returns zero. Because @@ERROR is reset after each Transact-SQL statement,it must be saved to a variable if it is needed to process it further after checking it.

What is SQL server agent?

SQL Server agent plays an important role in the day-to-day tasks of a database administrator (DBA). It is often overlooked as one of the main tools for SQL Server management. Its purpose is to ease the implementation of tasks for the DBA, with its full-function scheduling engine, which allows you to schedule your own jobs and scripts.

Which command using Query Analyzer will give you the version of SQL server and operating system?

SELECT SERVERPROPERTY('productversion'),
SERVERPROPERTY('productlevel'),
SERVERPROPERTY('edition')

Where are SQL server users names and passwords are stored in sql server?

They get stored in master db in the sysxlogins table

What are the authentication modes in SQL Server? How can it be changed?

Windows mode and mixed mode (SQL & Windows).

To change authentication mode in SQL Server click Start, Programs, Microsoft SQL Server and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group.Select the server then from the Tools menu select SQL Server Configuration Properties, and choose the Security page.

Which TCP/IP port does SQL Server run on? How can it be changed?

SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties –> Port number.both on client and the server.

What is SQL Profiler?

SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance ofMicrosoft SQL Server. You can capture and save data about each event to a file or SQL Server table toanalyze later. For example, you can monitor a production environment to see which stored procedures are hampering performance by executing too slowly.

What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?

Specifies a search condition for a group or an aggregate. HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

Difference between Function and Stored Procedure?

UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be. UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables. Inline UDF's can be though of as views that take parameters and can be used in JOINs and otherRowset operations.

What is difference between DELETE & TRUNCATE commands?

Delete command removes the rows from a table based on the condition that we provide with a WHEREclause. Truncate will actually remove all the rows from a table and there will be no data in the tableafter we run the truncate command.
TRUNCATE
TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.TRUNCATE removes the data by deallocating the data pages used to store the table’s data, and only thepage deallocations are recorded in the transaction log.TRUNCATE removes all rows from a table, but the table structure and its columns, constraints, indexesand so on remain. The counter used by an identity for new rows is reset to the seed for the column.You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint.Because TRUNCATE TABLE is not logged, it cannot activate a trigger.TRUNCATE can not be Rolled back.TRUNCATE is DDL Command.TRUNCATE Resets identity of the table.
DELETE
DELETE removes rows one at a time and records an entry in the transaction log for each deleted row.If you want to retain the identity counter, use DELETE instead. If you want to remove table definitionand its data, use the DROP TABLE statement.DELETE Can be used with or without a WHERE clauseDELETE Activates Triggers.DELETE Can be Rolled back.DELETE is DML Command.DELETE does not reset identity of the table.

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships.

One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships.

Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.

What's the difference between a primary key and a unique key?

Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

What is Collation?

Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying casesensitivity,accent marks, kana character types and character width.

What is a Linked Server?

Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server databases using T-SQL Statements. With a linked server, you can create very clean, easy to follow, SQL statements that allow remote data to be retrieved, joined and combined with local data. Storped Procedure sp_addlinkedserver, sp_addlinkedsrvlogin will be used add new Linked Server.

What is the use of DBCC commands?

DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks.
E.g.
DBCC CHECKDB - Ensures that tables in the db and the indexes are correctly linked.DBCC CHECKALLOC - To check that all pages in a db are correctly allocated.DBCC CHECKFILEGROUP - Checks all tables file group for any damage.

What is cursors?

Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis,instead of the typical SQL commands that operate on all the rows in the set at one time.
In order to work with a cursor we need to perform some steps in the following order:
  • Declare cursor
  • Open cursor
  • Fetch row from the cursor
  • Process fetched row
  • Close cursor
  • Deallocate cursor

What are the different index configurations a table can have?

A table can have one of the following index Configurations:
  1. No indexes
  2. A clustered index
  3. A clustered index and many nonclustered indexes
  4. A nonclustered index
  5. Many nonclustered indexes

What is the difference between clustered and a non-clustered index?

A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.

A nonclustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows

What is Index?

An index is a physical structure containing pointers to the data. Indices are created in an existing tableto locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes, they are just used to speed up queries. Effective indexes are one of the best ways to improve performance in a database application. A table scan happens when there is no index available to help a query. In a table scan SQLServer examines every row in the table to satisfy the query results. Table scans are sometimes unavoidable, but on large tables, scans have a terrific impact on performance.
Clustered indexes define the physical sorting of a database table’s rows in the storage media. For this reason, each database table may have only one clustered index.
Non-clustered indexes are created outside of the database table and contain a sorted list of referencesto the table itself.

What is View?

A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does data in the view, as views are the way to look at part of the original table. The results of using a view are not permanently stored in the database. The data accessed through a view is actually constructed using standard T-SQL select command and can come from one to many different base tables or even other views.

What is Trigger?

A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs. Triggers are stored in and managed by the DBMS.Triggers are used to maintain the referential integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed;the DBMS automatically fires the trigger as a result of a data modification to the associated table.Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is stored at the database level. Stored procedures, however, are not event-drive and are not attached to a specific table as triggers are. Stored procedures are explicitly executed by invoking a CALL to theprocedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures.

Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when thetrigger is fired because of data modification it can also cause another data modification, thereby firinganother trigger. A trigger that contains data modification logic within itself is called a nested trigger.

What is Stored Procedure?

A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database.
e.g. sp_helpdb, sp_renamedb, sp_depends etc.

What are different normalization forms?

1NF: Eliminate Repeating Groups
Make a separate table for each set of related attributes, and give each table a primary key. Each field contains at most one value from its attribute domain.
2NF: Eliminate Redundant Data
If an attribute depends on only part of a multi-valued key, remove it to a separate table.
3NF: Eliminate Columns Not Dependent On Key
If attributes do not contribute to a description of the key, remove them to a separate table. All attributes must be directly dependent on the primary key
BCNF: Boyce-Codd Normal Form
If there are non-trivial dependencies between candidate key attributes, separate them out into distinct tables

What is normalization?

Database normalization is a data design and organization process applied to data structures based on rules that help build relational databases. In relational database design, the process of organizing data to minimize redundancy. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions,and modifications of a field can be made in just one table and then propagated through the rest of the database via the defined relationships.

What is RDBMS?

Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers.This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage.

Saturday, June 7, 2008

Stored Proc to list all object dependencies

EXEC sp_depends 'Object Name'
Go
sp_depends displays information about database object dependencies.
sp_depends displays two result sets. First One shows the objects on which the 'given
object' depends and the second shows the objects that depend on the 'given object'

Friday, June 6, 2008

Query to Check if a table is system table or User table

SELECT OBJECTPROPERTY(OBJECT_ID('TableName'), 'IsMSShipped')
0 --> Indicates User Table
1 --> Indicates System Table

Query to mark a user table as a system table

EXEC sp_ms_marksystemobject 'TableName' Go

dtproperties Table in SQL Server 2000

dtproperties is a system table that stores the information about the Database Diagrams created in a particular database. Whenever a Database diagram is created or modified this table
gets updated automatically.

Basically this is a system table but when we run the below query we will get the name of
dtproperties table in the result set, indicating that this is user table.Microsoft has
confirmed that this is a bug in the Microsoft SQL Server.

Select * from sysobjects where xtype='u'

Thursday, June 5, 2008

Finding Difference between Tables in SQL 2005

In SQL 2005 the difference between tables can be easily found by using the tool
TableDiff.exe.
TableDiff.exe is a comparison tool that is provided with the sql server.
It will be found in the following location:
"C:\Program Files\Microsoft SQL Server\90\COM\TableDiff.exe"
The Drive name depends on where the SQL is Installed.
This tool compares 2 tables of the same database on the same server and creates a new
table called new Table that holds the differences.

"C:\Program Files\Microsoft SQL Server\90\COM\tablediff.exe"
-sourceserver ServerName
-sourcedatabase DatabaseName
-sourcetable TableName
-destinationserver ServerName
-destinationdatabase DatabaseName
-destinationtable TableName
-et NewTableName

For more information on this utility check out the microsoft website:
http://msdn2.microsoft.com/en-us/library/ms162843.aspx

Undocumented Stored Procedure to get SQL Version

EXEC master..sp_MSgetversion

Different ways of finding SQL Version

1. EXEC master..sp_MSgetversion
2. SELECT SERVERPROPERTY('productversion'),SERVERPROPERTY ('productlevel')
3. SELECT @@version
4. EXEC master..xp_msver

The sp_MSgetversion is an Undocumented Stored Proc to find the SQL Version.

Where are Temp tables found???

Temp tables are found in the Tempdb database. we can find the names of the temp tables that are created by executing the below Query

Select * from tempdb..sysobjects where type = 'U'

Status of the Database

The Different Statuses that a database can undergo

1 = autoclose (ALTER DATABASE)
4 = select into/bulkcopy (ALTER DATABASE using SET RECOVERY)
8 = trunc. log on chkpt (ALTER DATABASE using SET RECOVERY)
16 = torn page detection (ALTER DATABASE)
32 = loading
64 = pre recovery
128 = recovering
256 = not recovered
512 = offline (ALTER DATABASE)
1024 = read only (ALTER DATABASE)
2048 = dbo use only (ALTER DATABASE using SET RESTRICTED_USER)
4096 = single user (ALTER DATABASE)
32768 = emergency mode
4194304 = autoshrink (ALTER DATABASE)
1073741824 = cleanly shutdown

Friday, May 9, 2008

Easy way to copy table structure

Hey friends what you people do you do to copy the structure of your table.I have an simple idea to do that.

1.Go to your Enterprise Manager
2.Go to the database where the required table is located
3.Select the table of your choice
4.Simply press Ctrl+C
5.Then go to Query Analyser and do Ctrl+V
6.Then Press F5
You are done...

Saturday, May 3, 2008

Emergency mode

sp_configure 'allow update', 1
Reconfigure with override

update sysdatabases set status=32768 where name=

sp_configure 'allow update', 1
Reconfigure with override

Use this query to take the database to Emergency Mode whenever it is marked as suspect.
When the database is in Emergency mode, you can query the database and export the data into a new database.

Backup without affecting LSN

/*In SQL server 2005 you can take backup without affecting logshipping . You can use WITH COPY_ONLY option in BACKUP command, this command will take backup without affecting LSN.*/
BACKUP DATABASE Yourdbname TO DISK='backup path' WITH COPY_ONLY
--Don't forget to change the dbname and backup path before using the above command.

Error in replication::subscription(s) have been marked inactive and must be reinitialized

Whenever there is an error as mentioned above then, you can try to update the status column in the MSsubscriptions table in the distribution database. The status column for the expired subscription indicated a value of 0 meaning inactive. The value of 2 in the status column means Active.

Try the following steps:
1. Select * from MSsubscriptions to locate the expired subscription.
2. Use the query below to reset the status in MSsubscriptions table. Fill in the values for the publisher_id, publisher_db, publication_id, subscriber_id and subscriber_db in the query below with the values from the expired subscription in the MSsubscriptions table.

update distribution..MSsubscriptions set status=2 where publisher_id='x' andpublisher_db='x' and publication_id='x' and subscriber_id='x' and subscriber_db='x'

Status of the subscription:
0 = Inactive
1 = Subscribed
2 = Active

Virtual LOG info

DBCC LOGINFO
It is used to get the number of virtual log file for a database.

How to get current database name

Use the below Query

SELECT db_name()

How to Change the Owner of a DTS package?

USE MSDB
sp_reassign_dtspackageowner [@name =] 'name', [@id =] 'id', [@newloginname =] 'newloginname'

sp_reassign_dtspackageowner is an undocumented stored procedure which is present in MSDB database.

Get the List of Failed Jobs

use msdb
SELECT name FROM msdb.dbo.sysjobs A, msdb.dbo.sysjobservers B WHERE A.job_id = B.job_id AND B.last_run_outcome = 0

How to get the version of SQL server

Simply execute the below query to get the SQL server version you are running.

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

How to find the SQL Server Version?

Simply execute the below query to get the version of SQL Server you are running.



SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

How to change the server wide date format

Many times, when you install windows and sql server 2000 or 2005 in the fresh machine. generally application which is pointing to your database fails to insert the dd/mm/yyyy
date to your database. even you put the write syntex in your application program and the insert query. Why ?

It is due to server level date settings. As a default your server settings would be in mm/dd/yyyy format, which needs to be changed in the server.

How to do this?
Follow these simple steps...

1. Start -> Control Pannel -> Reginal settings ->Customize
after that go the date format and set the short date = dd/mm/yyyy
and long date format = dd mmmm, yyyy

After doing this, Your application will be able to insert the exact date to your database.As there is no sql server level settings to change the date format. But apart from thatyou can use SET option while firing the insert command to your database
Like this...

SET dd/mm/yyyy
Insert into table (date1) value ('29/04/2008')

Wednesday, April 9, 2008

SQL Magic

Execute the Below Query and enjoy the results that is obtained by this query every time when it is executed.
This Query gives a random list everytime u run it

select * from table_name order by newid()

Thursday, March 20, 2008

Retrieve Processes Using Specified Database

If you want to know how many processes are there in any particular database, it can be retrieved querying sysprocesses in master database.
1st Method
USE master
GO
DECLARE @dbid INT
SELECT @dbid = dbid
FROM sysdatabases
WHERE name = ‘DBName’
IF EXISTS (SELECT spid
FROM sysprocesses
WHERE dbid = @dbid)
BEGIN
SELECT ‘These processes are using current database’ AS Note,
spid, last_batch,
status, hostname, loginame
FROM sysprocesses
WHERE dbid = @dbid
END
GO

2nd Method
SELECT 'These processes are using database ' AS Note,
[Database] =DB_NAME (dbid), spid, last_batch,
status, hostname, loginame
FROM sysprocesses
WHERE dbid = DB_ID (‘DBName')

Tuesday, March 18, 2008

Script to Script Out all Publication Stored Procs

You may come across a situation where in your replication is failing with the error “could not find the stored procedure ‘sp_MSupd_TableName’ ”
or
With the error “could not find the stored procedure ‘sp_MSins_TableName’ ”

To fix this replication errors run the following command in the publication database

sp_scriptpublicationcustomprocs ‘Publication Name’

After running the above stored proc, obtain the results from the result set and run them in the subscription database. Now restart the agent and this should fix the error.

Wednesday, January 9, 2008

Steps to Help Secure SQL Server 2000

Here are some things you can do today to improve the security of your SQL Server installation:

1.Install the most recent service pack

The single most effective action you can take to improve the security of your server is to upgrade to SQL Server 2000 Service Pack 4 (SP4)

2.Use Windows Authentication Mode.

Whenever possible, you should require Windows Authentication Mode for connections to SQL Server. This will shield your SQL Server installation from most Internet-based attacks by restricting connections to Microsoft Windows user and domain user accounts. Your server will also benefit from Windows security enforcement mechanisms such as stronger authentication protocols and mandatory password complexity and expiration. Also, credentials delegation (the ability to bridge credentials across multiple servers) is only available in Windows Authentication Mode. On the client side, Windows Authentication Mode eliminates the need to store passwords, which is a major vulnerability in applications that use standard SQL Server logins.

To set up Windows Authentication Mode security with Enterprise Manager in SQL Server:
Expand a server group. Right-click a server and then click Properties. On the Security tab, under Authentication, click Windows only.

For more information, see the "Authentication Mode" topic in SQL Server Books Online or on MSDN.

3.Isolate your server and back it up regularly.

Physical and logical isolation make up the foundation of SQL Server security. Machines hosting a database should be in a physically protected location, ideally a locked machine room with monitored flood detection and fire detection/suppression systems. Databases should be installed in the secure zone of your corporate intranet and never directly connected to the Internet. Back up all data regularly and store copies in a secure off-site location.


4.Assign a strong sa password.

The sa account should always have a strong password, even on servers that are configured to require Windows Authentication. This will ensure that a blank or weak sa password is not exposed in the future if the server is reconfigured for Mixed Mode Authentication.

To assign the sa password:
Expand a server group, and then expand a server.
Expand Security, and then click Logins.
In the details pane, right-click SA, and
then click Properties. In the Password box, type the new password.

5.Limit privilege level of SQL Server Services.

SQL Server 2000 and SQL Server Agent run as Windows services. Each service must be associated with a Windows account, from which it derives its security context. SQL Server allows users of the sa login, and in some cases other users, to access operating system features. These operating system calls are made with the security context of the account that owns the server process. If the server is cracked, these operating system calls may be used to extend the attack to any other resource to which the owning process (the SQL Server service account) has access. For this reason, it is important to grant only necessary privileges to SQL Server services.

The following settings are recommended:

SQL Server Engine/MSSQLServer
If there are named instances, they will be named MSSQL$InstanceName. Run as a Windows domain user account with regular user privileges. Do not run as local system, local administrator, or domain administrator accounts.

SQL Server Agent Service/SQLServerAgent
Disable if not required in your environment; otherwise run as a Windows domain user account with regular user privileges. Do not run as local system, local administrator, or domain administrator accounts.

Important: SQL Server Agent will need local Windows administrator privileges if one of the following is true:

SQL Server Agent connects to SQL Server using standard SQL Server Authentication (not recommended). >SQL Server Agent uses a multiserver administration master server (MSX) account that connects using standard SQL Server Authentication. SQL Server Agent runs Microsoft ActiveX® script or CmdExec jobs owned by users who are not members of the sysadmin fixed server role.

If you need to change the account associated with a SQL Server service, use SQL Server Enterprise Manager. Enterprise Manager will set appropriate permissions on the files and registry keys used by SQL Server. Never use the Services applet of Microsoft Management Console (in Control Panel) to change these accounts, because this requires manual adjustment of dozens of registry and NTFS file system permissions and Microsoft Windows user rights.

Changes to account information will take effect the next time the service is started. If you need to change the account associated with SQL Server and SQL Server Agent, you must apply the change to both services separately using Enterprise Manager.

6.Disable SQL Server ports on your firewall.

Default installations of SQL Server monitor TCP port 1433 and UDP port 1434. Configure your firewall to filter out packets addressed to these ports. Additional ports associated with named instances should also be blocked at the firewall.

7.Use the most secure file system.

NTFS is the preferred file system for installations of SQL Server. It is more stable and recoverable than FAT file systems, and enables security options such as file and directory ACLs and file encryption (EFS). During installation, SQL Server will set appropriate ACLs on registry keys and files if it detects NTFS. These permissions should not be changed.

With EFS, database files are encrypted under the identity of the account running SQL Server. Only this account can decrypt the files. If you need to change the account that runs SQL Server, you should first decrypt the files under the old account, then re-encrypt them under the new account.

8.Delete or secure old setup files.

SQL Server setup files may contain plain-text or weakly encrypted credentials and other sensitive configuration information that has been logged during installation. The location of these log files varies depending on which version of SQL Server has been installed. In SQL Server 2000, the following files may be affected: sqlstp.log, sqlsp.log, and setup.iss in the :\Program Files\Microsoft SQL Server\MSSQL\Install folder for a default installation, and the :\Program Files\Microsoft SQL Server\ MSSQL$\Install folder for named instances.

If the current system is an upgrade from SQL Server version 7.0 installations, the following files should be checked as well: setup.iss in the %Windir% folder, and sqlsp.log in the Windows Temp folder.

9.Audit connections to SQL Server.

SQL Server can log event information for review by the system administrator. At a minimum, you should log failed connection attempts to SQL Server and review the log regularly. When possible, save these logs to a different hard drive than the one on which data files are stored.

To enable auditing of failed connections with Enterprise Manager in SQL Server:

Expand a server group.
Right-click a server, and then click Properties.
On the Security tab, under Audit Level, click Failure.

Tuesday, January 1, 2008

How to Install SQL server 2005???

How to find DTS package Name from JOB step

To find the Name of the DTS Package from Job step, do the following

Right click on the job and click on Generate SQL Script. Click the Preview button and look at the preview for the line:
--Add the job

Now take a look at the variable @description. It should state the package name that the job is executing:
@description = N'Execute package:Test'

Ads