Monday, December 29, 2008
@@CONNECTIONS and @@MAX_CONNECTIONS
Wednesday, December 24, 2008
Code Names of SQL server releases
- SQL Server 2008 Katmai
- SQL Server 2005 Yukon
- SQL Server 2000 64 bit Liberty
- SQL Server 2000 32 bit Shiloh
- SQL Server 7.0 Sphinx
- SQL Server 6.5 Hydra
- SQL Server 6.0 SQL95
Wednesday, December 10, 2008
Add a logo to the Report Manager
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
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
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?
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
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?
, 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
Try it yourself:
Go
CREATE PROC TestRename AS
Print ‘XYZ’
GO
Now, rename this SP using the management studio object list to “RenameTest”
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>
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
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.
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 OK4. 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)
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]
If you want to see what is there in this database:
- Stop the SQL Server service.
- Copy both files and rename the copies to MSSQLSystemResource_Test.mdf and MSSQLSystemResource_Test.ldf.
- Start the SQL server service
- Attach the new files.
- Query the database.
Wednesday, August 6, 2008
Search the Database
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
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
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
Usage:
EXEC msdb..sp_get_sqlagent_properties
Undocumented stored procedure:: sp_MS_upd_sysobj_category
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
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
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
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.
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.
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
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
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?
Virtual Tables a Trigger uses
What is the basic functions for master, msdb, model, tempdb databases?
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 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
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?
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?
- 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?
What is the difference between a local and a global variable?
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?
What is Raiseerror?
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?
What is SQL server agent?
Which command using Query Analyzer will give you the version of SQL server and operating system?
SERVERPROPERTY('productlevel'),
SERVERPROPERTY('edition')
Where are SQL server users names and passwords are stored in sql server?
What are the authentication modes in SQL Server? How can it be changed?
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?
What is SQL Profiler?
What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
Difference between Function and Stored Procedure?
What is difference between DELETE & TRUNCATE commands?
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-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?
What is Collation?
What is a Linked Server?
What is the use of DBCC commands?
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?
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?
- No indexes
- A clustered index
- A clustered index and many nonclustered indexes
- A nonclustered index
- Many nonclustered indexes
What is the difference between clustered and a non-clustered index?
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?
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?
What is Trigger?
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?
e.g. sp_helpdb, sp_renamedb, sp_depends etc.
What are different normalization forms?
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?
What is RDBMS?
Saturday, June 7, 2008
Stored Proc to list all object dependencies
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
0 --> Indicates User Table
1 --> Indicates System Table
Query to mark a user table as a system table
dtproperties Table in SQL Server 2000
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
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
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???
Select * from tempdb..sysobjects where type = 'U'
Status of the Database
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 Manager2.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
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
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
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
It is used to get the number of virtual log file for a database.
How to Change the Owner of a DTS package?
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
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?
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')
How to change the server wide date format
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
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
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
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
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
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 find DTS package Name from JOB step
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'