Anda di halaman 1dari 68

Difference between sql server 2005 and 2008 In sql server 2005,There is no option to compress backup files, but

in sql server 2008,there you find it. storing backup file takes 5 minutes without compression in sqlserver 2005,but it takes only 3 minutes in sql server 2008 for storing backup files with compression. cpu is used to compress the data before it is written to disk,so less data is written to disk.

There are many new features, so it depends on what you need. If you store large files in SQL Server, migrated from Oracle and want to use date and time data types, need to encrypt your databases, etc you will definitely want to look at 2008. The nice thing is that it upgrading should be much easier from 2005 to 2008 than it was from 2000 to 2005.

Server 2008 also added CMS which is Central Management Server. It only works with Windows Authentication but it allows you to management multiple SQL Servers at once. If SQL Server systems are popping up like weeds it will appear in the CMS provided that they point to the CMS via SSMS. Its a really cool feature. PBM Policy-Based Management is another added feature introduced with SQL Server 2008. PBM allows you to define and enforce policies for configuring and managing SQL Server across your enterprise. It goes hand-in-hand with CMS.

One of my favorite is that fact that Reporting Services no longer requires IIS as it makes direct calls to HTTP.SYS.

As Rajiv mentioned there are many improvements to performance, data handling, security, administration, etc... there is not much diference... just higher version but still companies develop projects in 2005 only SQL2008 has support for additional datatypes: date time geospatial timestamp with internal timezone in additon it has geospatial functions so it can compute differences based on GPS co-ordinates

Features: Activity Monitor

When troubleshooting a performance issue or monitoring a server in real time, it is common for the DBA to execute a number of scripts or check a number of sources to collect general information about what processes are executing and where the problem may be. SQL Server 2008 Activity Monitor consolidates this information by detailing running and recently executed processes, graphically. The display gives the DBA a high-level view and the ability to drill down on processes and view wait statistics to help understand and resolve problems.

To open up Activity Monitor, just right-click on the registered server name in Object Explorer and then clickActivity Monitor, or utilize the standard toolbar icon in SQL Server Management Studio [SQL Server] Audit

Having the ability to monitor and log events, such as who is accessing objects, what changes occurred, and what time changes occurred, can help the DBA to meet compliance standards for regulatory or organizational security requirements. Gaining insight into the events occurring within their environment can also help the DBA in creating a risk mitigation plan to keep the environment secure.

Within SQL Server 2008 (Enterprise and Developer editions only), SQL Server Audit provides automation that allows the DBA and others to enable, store, and view audits on various server and database components. The feature allows for auditing at a granularity of the server and/or database level.

Backup Compression

Central Management Servers Data Collector and Management Data Warehouse Data Compression Policy-Based Management Predictable Performance and Concurrency

Resource Governor

Define statistics Statistics determine the selectivity of the indexes. If an indexed column has unique values then the selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses these indexes in determining whether to choose an index or not while executing a query. Some situations under which you should update statistics: 1) If there is significant change in the key values in the index 2) If a large amount of data in an indexed column has been added, changed, or removed (that is, if the distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE statement and then repopulated 3) Database is upgraded from a previous version What is the difference between clustered and nonclustered indexes?

Answer: There are clustered and nonclustered indexes. 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 are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors? Cursors allow row-by-row prcessing of the resultsets. Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information. Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). represent a third state, which is NULL. Define candidate key, alternate key, composite key.

A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

Shared Locks
Shared (S) locks allow concurrent transactions to read (SELECT) a resource under pessimistic concurrency control. For more information, see Types of Concurrency Control. No other transactions can modify the data while shared (S) locks exist on the resource. Shared (S) locks on a resource are released as soon as the read operation completes, unless the transaction isolation level is set to repeatable read or higher, or a locking hint is used to retain the shared (S) locks for the duration of the transaction.

Update Locks

Update (U) locks prevent a common form of deadlock. In a repeatable read or serializable transaction, the transaction reads data, acquiring a shared (S) lock on the resource (page or row), and then modifies the data, which requires lock conversion to an exclusive (X) lock. If two transactions acquire shared-mode locks on a resource and then attempt to update data concurrently, one transaction attempts the lock conversion to an exclusive (X) lock. The shared-mode-to-exclusive lock conversion must wait because the exclusive lock for one transaction is not compatible with the shared-mode lock of the other transaction; a lock wait occurs. The second transaction attempts to acquire an exclusive (X) lock for its update. Because both transactions are converting to exclusive (X) locks, and they are each waiting for the other transaction to release its shared-mode lock, a deadlock occurs. To avoid this potential deadlock problem, update (U) locks are used. Only one transaction can obtain an update (U) lock to a resource at a time. If a transaction modifies a resource, the update (U) lock is converted to an exclusive (X) lock.

Exclusive Locks

Exclusive (X) locks prevent access to a resource by concurrent transactions. With an exclusive (X) lock, no other transactions can modify data; read operations can take place only with the use of the NOLOCK hint or read uncommitted isolation level. Data modification statements, such as INSERT, UPDATE, and DELETE combine both modification and read operations. The statement first performs read operations to acquire data before performing the required modification operations. Data modification statements, therefore, typically request both shared locks and exclusive locks. For example, an UPDATE statement might modify rows in one table based on a join with another table. In this case, the UPDATE statement requests shared locks on the rows read in the join table in addition to requesting exclusive locks on the updated rows.

Intent Locks

The Database Engine uses intent locks to protect placing a shared (S) lock or exclusive (X) lock on a resource lower in the lock hierarchy. Intent locks are named intent locks because they are acquired before a lock at the lower level, and therefore signal intent to place locks at a lower level. Intent locks serve two purposes:

y y

To prevent other transactions from modifying the higher-level resource in a way that would invalidate the lock at the lower level. To improve the efficiency of the Database Engine in detecting lock conflicts at the higher level of granularity.

For example, a shared intent lock is requested at the table level before shared (S) locks are requested on pages or rows within that table. Setting an intent lock at the table level prevents another transaction from subsequently acquiring an exclusive (X) lock on the table containing that page. Intent locks improve performance because the Database Engine examines intent locks only at the table level to determine if a transaction can safely acquire a lock on that table. This removes the requirement to examine every row or page lock on the table to determine if a transaction can lock the entire table.

Locking in Microsoft SQL Server


Alexander Chigrik chigrik@mssqlcity.com

Introduction Transaction Isolation Levels Lock types Locking optimizer hints Deadlocks View locks (sp_lock) Literature

Introduction
In this article, I want to tell you about SQL Server 7.0/2000 Transaction Isolation Levels, what kinds of Transaction Isolation Levels exist, and how you can set the appropriate Transaction Isolation Level, about Lock types and Locking optimizer hints, about deadlocks, and about how you can view locks by using the sp_lock stored procedure.

Transaction Isolation Levels


There are four isolation levels: y READ UNCOMMITTED y READ COMMITTED y REPEATABLE READ y SERIALIZABLE Microsoft SQL Server supports all of these Transaction Isolation Levels and can separate REPEATABLE READ and SERIALIZABLE. Let me to describe each isolation level.

READ UNCOMMITTED
When it's used, SQL Server not issue shared locks while reading data. So, you can read an uncommitted transaction that might get rolled back later. This isolation level is also called dirty read. This is the lowest isolation level. It ensures only that a physically corrupt data will not be read.

READ COMMITTED
This is the default isolation level in SQL Server. When it's used, SQL Server will use shared locks while reading data. It ensures that a physically corrupt data will not be read and will never read data that another application has changed and not yet committed, but it not ensures that the data will not be changed before the end of the transaction.

REPEATABLE READ
When it's used, the dirty reads and nonrepeatable reads cannot occur. It means that locks will be placed on all data that is used in a query, and another transactions cannot update the data. This is the definition of nonrepeatable read from SQL Server Books Online: nonrepeatable read When a transaction reads the same row more than one time, and between the two (or more) reads, a separate transaction modifies that row. Because the row was modified between reads within the same transaction, each read produces different values, which introduces inconsistency.

SERIALIZABLE
Most restrictive isolation level. When it's used, the phantom values cannot occur. It prevents other users from updating or inserting rows into the data set until the transaction

will be completed. This is the definition of phantom from SQL Server Books Online: phantom Phantom behavior occurs when a transaction attempts to select a row that does not exist and a second transaction inserts the row before the first transaction finishes. If the row is inserted, the row appears as a phantom to the first transaction, inconsistently appearing and disappearing. You can set the appropriate isolation level for an entire SQL Server session by using the SET TRANSACTION ISOLATION LEVEL statement. This is the syntax from SQL Server Books Online: SET TRANSACTION ISOLATION LEVEL { READ COMMITTED | READ UNCOMMITTED | REPEATABLE READ | SERIALIZABLE } You can use the DBCC USEROPTIONS statement to determine the Transaction Isolation Level currently set. This command returns the set options that are active for the current connection. This is the example: SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED GO DBCC USEROPTIONS GO

Lock types
There are three main types of locks that SQL Server 7.0/2000 uses: y Shared locks y Update locks y Exclusive locks Shared locks are used for operations that do not change or update data, such as a SELECT statement. Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes. Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE. Shared locks are compatible with other Shared locks or Update locks. Update locks are compatible with Shared locks only.

Exclusive locks are not compatible with other lock types. Let me to describe it on the real example. There are four processes, which attempt to lock the same page of the same table. These processes start one after another, so Process1 is the first process, Process2 is the second process and so on. Process1 Process2 Process3 Process4 : : : : SELECT SELECT UPDATE SELECT

Process1 sets the Shared lock on the page, because there are no another locks on this page. Process2 sets the Shared lock on the page, because Shared locks are compatible with other Shared locks. Process3 wants to modify data and wants to set Exclusive lock, but it cannot make it before Process1 and Process2 will be finished, because Exclusive lock is not compatible with other lock types. So, Process3 sets Update lock. Process4 cannot set Shared lock on the page before Process3 will be finished. So, there is no Lock starvation. Lock starvation occurs when read transactions can monopolize a table or page, forcing a write transaction to wait indefinitely. So, Process4 waits before Process3 will be finished. After Process1 and Process2 were finished, Process3 transfer Update lock into Exclusive lock to modify data. After Process3 was finished, Process4 sets the Shared lock on the page to select data.

Locking optimizer hints


SQL Server 7.0/2000 supports the following Locking optimizer hints: y NOLOCK y HOLDLOCK y UPDLOCK y TABLOCK y PAGLOCK y TABLOCKX y READCOMMITTED y READUNCOMMITTED y REPEATABLEREAD y SERIALIZABLE

y READPAST y ROWLOCK NOLOCK is also known as "dirty reads". This option directs SQL Server not to issue shared locks and not to honor exclusive locks. So, if this option is specified, it is possible to read an uncommitted transaction. This results in higher concurrency and in lower consistency. HOLDLOCK directs SQL Server to hold a shared lock until completion of the transaction in which HOLDLOCK is used. You cannot use HOLDLOCK in a SELECT statement that includes the FOR BROWSE option. HOLDLOCK is equivalent to SERIALIZABLE. UPDLOCK instructs SQL Server to use update locks instead of shared locks while reading a table and holds them until the end of the command or transaction. TABLOCK takes a shared lock on the table that is held until the end of the command. If you also specify HOLDLOCK, the lock is held until the end of the transaction. PAGLOCK is used by default. Directs SQL Server to use shared page locks. TABLOCKX takes an exclusive lock on the table that is held until the end of the command or transaction. READCOMMITTED Perform a scan with the same locking semantics as a transaction running at the READ COMMITTED isolation level. By default, SQL Server operates at this isolation level. READUNCOMMITTED Equivalent to NOLOCK. REPEATABLEREAD Perform a scan with the same locking semantics as a transaction running at the REPEATABLE READ isolation level. SERIALIZABLE Perform a scan with the same locking semantics as a transaction running at the SERIALIZABLE isolation level. Equivalent to HOLDLOCK. READPAST Skip locked rows. This option causes a transaction to skip over rows locked by other transactions that would ordinarily appear in the result set, rather than block the transaction waiting for the other transactions to release their locks on these rows. The READPAST lock hint applies only to transactions operating at READ COMMITTED isolation and will read only past row-level locks. Applies only to the SELECT statement. You can only specify the READPAST lock in the READ COMMITTED or REPEATABLE READ isolation levels.

ROWLOCK Use row-level locks rather than use the coarser-grained page- and table-level locks. You can specify one of these locking options in a SELECT statement. This is the example: SELECT au_fname FROM pubs..authors (holdlock)

Deadlocks
Deadlock occurs when two users have locks on separate objects and each user wants a lock on the other's object. For example, User1 has a lock on object "A" and wants a lock on object "B" and User2 has a lock on object "B" and wants a lock on object "A". In this case, SQL Server ends a deadlock by choosing the user, who will be a deadlock victim. After that, SQL Server rolls back the breaking user's transaction, sends message number 1205 to notify the user's application about breaking, and then allows the nonbreaking user's process to continue. You can decide which connection will be the candidate for deadlock victim by using SET DEADLOCK_PRIORITY. In other case, SQL Server selects the deadlock victim by choosing the process that completes the circular chain of locks. So, in a multiuser situation, your application should check the error 1205 to indicate that the transaction was rolled back, and if it's so, restart the transaction. Note. To reduce the chance of a deadlock, you should minimize the size of transactions and transaction times.

View locks (sp_lock)


Sometimes you need a reference to information about locks. Microsoft recommends using the sp_lock system stored procedure to report locks information. This very useful procedure returns the information about SQL Server process ID, which lock the data, about locked database, about locked table ID, about locked page and about type of locking (locktype column). This is the example of using the sp_lock system stored procedure: spid ---------11 11 locktype table_id page dbname ----------------------------------- ----------- ----------- ---------Sh_intent Ex_extent 688005482 0 0 336 master tempdb

The information, returned by sp_lock system stored procedure needs in some clarification, because it's difficult to understand database name, object name and index name by their ID numbers.

Check the link below if you need to get user name, host name, database name, index name object name and object owner instead of their ID numbers: Detailed locking view: sp_lock2

How Many databases do you handle?

A. We handle around 60 servers of which 30 are Production Databases and rest are development and test boxes.

Q. What is the Max Size of the database that you handle?

A. We have a database which is 150 gB in size and the rest range from 600Gigs to 100 Gigs, some are less than 100Gig. Backup Strategy Followed By Hp.

1) Full Backup Taken Weekly mostly on Sundays at 2 am in the nights. On Tape 2) Differential Backup Taken Daily Except Sundays On Tape 3) TLog Backup Every 1Hr or 15 Min. depending on application Criticality. On Disk

How do you check blocking? Sp_Who or Sp_Who2 (Sp_Who2 gives more elaborated result .)
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 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 What are End points?
Endpoints are objects that represent a communication point between the server and a client. SQL Server automatically creates an endpoint for each of the four protocols (TCP/IP, Shared Memory, Named Pipe, VIA) that accept TDS connections.

How to rebuild an index?


Recommendation: Index should be rebuild when index fragmentation is great than 40%. Index should be reorganized when index fragmentation is between 10% to 40%. Index rebuilding process uses more CPU and it locks the database resources. SQL Server development version and Enterprise version has option ONLINE, which can be turned on when Index is rebuilt. ONLINE option will keep index available during the rebuilding.

When you create or rebuild an index, you can specify a fill factor, which is the amount the data pages in the index that are filled. A fill factor of 100 means that each index page is 100% full, a fill factor of 50% means each index page is 50% full. If you create a clustered index that has a fill factor of 100, and it is not based on a monotonically increasing key, that means that each time a record is inserted (or perhaps updated), page splits may occur because there is no room for the data in the existing pages. Numerous page splits can slow down SQL Server's performance. If you find that your transaction log grows to an unacceptable size when you run DBCC REINDEX, you can minimize this growth by switching from the Full Recovery mode to the Bulk-Logged mode before you reindex, and when done, switch back. This will significantly reduce

I forgot the sa password. How I can reset it?

Answer: To reset the sa password, you can make the following: 1. Login to the SQL Server box as the Administrator. 2. Run SQL Server Enterprise Manager. 3. Right-click the server name and choose 'Edit SQL Server Registration properties'.

4. Choose 'Use Windows authentication' and click OK button. 5. Expand a server, expand a Security and click Logins. 6. Double-click the sa login and specify new password on the General tab.

How to check fragmentation?


SQL Server 2005 introduces a new DMV (Dynamic Management View) to check index fragmentation levels: sys.dm_db_index_physical_stats. Although SQL Server 2005 still supports the SQL Server 2000 DBCC SHOWCONTING command, this feature will be removed on a future version of SQL Server.

DBCC SWOWCONTING example:

How do we know if our database is fragmented? y y


We have to pay attention to theavg_fragmentation_in_percent value. A value between 5-30% indicates moderate fragmentation, while any value over 30% indicates high fragmentation (book pages missing any order). The avg_page_space_used_in_percent is another value that it is worth to look closely. This value represent the amount of spaced used in the indexes. A value below 75% is usually associated to internal fragmentation (more blank pages on our book than recommended). For moderate fragmentation index reorganization will be enough, for heavily fragmented indexes a rebuild process is needed

Reference Values (in %) avg_fragmentation_in_percent > 5 AND < 30

Action Reorganize Index

SQL statement ALTER INDEX REORGANIZE

avg_fragmentation_in_percent > Rebuild Index ALTER INDEX REBUILD 30


Enable remote connections for SQL Server 2005 Express or SQL Server 2005 Developer Edition
You must enable remote connections for each instance of SQL Server 2005 that you want to connect to from a remote computer. To do this, follow these steps:

1.
2. 3.

Click Start, point to Programs, point to Microsoft SQL Server 2005, point toConfiguration Tools, and then click SQL Server Surface Area Configuration. On the SQL Server 2005 Surface Area Configuration page, click Surface Area Configuration for Services and Connections. On the Surface Area Configuration for Services and Connections page, expandDatabase Engine, click Remote Connections, click Local and remote connections, click the appropriate protocol to enable for your environment, and then click Apply.

How do I monitor SQL Server performance?


There are some Microsoft tools that can help monitor your database performance: Microsoft Operations Manager (MOM) Performance Monitor (ships with Windows) SQL Profiler

(ships with SQL Server client tools) There are also some third-party tools: BMC DBXray BMC Patrol Embarcadero Performance Center Heorix eQ HybridX SQL Spy Intrinsic Design Coefficient Mercury Interactive SiteScope Micromuse Netcool NetIQ AppManager NetIQ DiagnosticManager PUREnetworking ServerMonitor Quest Foglight Quest I/Watch Quest Spotlight SQL Server Monitor (The site has a demo, but doesn't make it clear how to obtain the code/product.) Veritas InDepth (formerly a product from Precise) Zero Impact SQL Monitor

How to shrink log files ?


1. Back up the transaction log file to make most of the active virtual log files inactive. Therefore, the inactive virtual log files can be removed in a later step. To do this, run a Transact-SQL statement that is similar to the following Transact-SQL statement.

BACKUP LOG <DatabaseName> TO DISK = '<BackupFile>'


Note In this statement, <DatabaseName> is a placeholder for the name of the database that you are backing up. In this statement, <BackupFile> is a placeholder for the full path of the backup file. For example, run the following Transact-SQL statement.

BACKUP LOG TestDB TO DISK='C:\TestDB1.bak'


2. Shrink the transaction log file. To do this, run a Transact-SQL statement that is similar to the following Transact-SQL statement.

DBCC SHRINKFILE (<FileName>, <TargetSize>) WITH NO_INFOMSGS


The SQL Server 2000-supported replication types are as follows: yTransactional ySnapshot yMerge 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. When synchronization 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

Re: Difference between sql server 2000 and sql server 2005? Answer 1. In SQL Server 2000 the Query Analyzer and Enterprise # 2 Manager are seperate,whereas in SQL Server 2005
both were combined as Management Studio. 2. In Sql 2005,the new datatype XML is used,whereas in Sql 2000 there is no such datatype 3. In Sql server2000 we can create 65,535 databases,whereas in Sql server2005 2(pow(20))-1 databases can be created. In sql server2000 Extended Stored procedures , and it modified it into CLR Stored procedures Enabling client connections ? By default when you install SQL Server 2005 Express Edition, connections are only possible via the Shared Memory protocol on the same machine and only then by the new sqlcmd commandline tool ( the replacement for osql/isql). In order to connect from downlevel clients (such as Query Analyzer) or from another machine, you have to follow a number of steps detailed below. The walkthrough is for a default named instance called SQLEXPRESS. 1. 2. 3. 4. 5. 6. 7. 8. Goto Start>Programs>Microsoft SQL Server 2005>SQL Computer Manager Expand Server Network Configuration in the left pane Select Protocols for SQLEXPRESS in the left pane Right click on Np in the right pane and select Enable Right click on Tcp in the right pane and select Enable Restart the SQL Express service (MSSQL$SQLEXPRESS) Goto Start>Run and type in services.msc and hit Enter Locate the SQL Browser service in the list of services and start it

You should now be able to use tools such as Query Analyzer to connect to your SQL Server 2005 Express Edition instance

To view the SQL Server error log


1. 2. In Object Explorer, expand a server, expand Management, and then expand SQL Server Logs. Right-click a log and click View SQL Server Log.

See Also

How do I access the Log File Viewer?


1. 2. 3. 4. 5. Launch SQL Server Management Studio. Navigate to your SQL Server 2005 instance. Expand the instance, then expand the Management folder followed by the SQL Server Logs folder. Double click on any of the log files. Below is the default Log File Viewer interface that will be loaded.

What are the available data sources for the Log File Viewer? y y y y
Database Mail SQL Server Agent Logs SQL Server Error Logs Windows Event Logs (Application, Security and System)

What is fill factor? he fillfactor effect specifies the percentage of space filled on index data pages when an index is initially created. The default fillfactor setting of zero, which can be altered at the global server level through a configuration option, will cause an index to be almost filled to capacity, with only a small amount of space being left at the upper level region of the index. A 100% setting completely fills each index page. One important thing to remember is that this amount is not adhered to after the index is first built. An index can be rebuilt and the original fillfactor setting re-instituted with the variety of DBCC index rebuild or ALTER INDEX (SQL Server 2005) commands. Ediions in sql server 2008?

Enterprise Standard Workgroup Web Developer Express Compact 3.5

What is a Schema in SQL Server 2005?


The ANSI SQL-92 standard defines a schema as a collection of database objects that are owned by a single principle and form a single namespace.

All objects within a schema must be uniquely named and a schema must be uniquely named in the database catalog. SQL Server 2005 breaks the link between users and schemas, users do not own objects. Schemas own objects and principles own schemas. A schema can be owned by either a primary or secondary principle, with the term principle meaning any SQL Server entity that can access securable objects.

Principle types that can own schemas:

y o o o y o

Primary SQL Server Login Database User Windows Login Secondary SQL Server Roles

o o

Windows Groups Default Schemas Users can now have a default schema assigned using the DEFAULT_SCHEMA option of CREATE USER and ALTER USER commands. If no default schema is supplied for a user then DBO will be used as the default schema.

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.

Re: Define Check points and End Points? Answer CheckPoints:Whenever we perform any DML operations in the # 1 database,it will go to the checkpoint and then
commit in the database.If we don't have checkpoints,the data will get store in transaction log file,once it got fill full,it will make the database performance issues. Endpoints:Endpoints are objects that represent a communication point between the server and a client.

Re: How do you troubleshoot SQL Server if its running very slow? Answer First check the processor and memory usage to see that # 1 processor is not above 80% utilization and
memory not above 40-45% utilization then check the disk utilization using Performance Monitor, Secondly, use SQL Profiler to check for the users and current SQL activities and jobs running which might be a problem. Third would be to run UPDATE_STATISTICS command to update the indexes

Re: what is sql injection? Answer #1


It's a secuity vulnerability that occurs between the database layer of an application.

Re: How to find the latest updated value in a table without sending any parameters to that query Answer by using scope_identity() #1

What is difference between OSQL and Query Analyzer Both are same for functioning but there is a little difference OSQL is command line tool which execute query and display the result same a Query Analyzer do but Query Analyzer is graphical.OSQL have not ability like Query Analyzer to analyze queries and show statistics on speed of execution .And other useful thing about OSQL is that its helps in scheduling which is done in Query Analyzer with the help of JOB.

Can you explain the role of each service


SQL SERVER - is for running the databases SQL AGENT - is for automation such as Jobs, DB Maintenance, Backups DTC - Is for linking and connecting to other SQL Servers.

What is SQL tuning


SQL tuning is the process of getting that the SQL statements that an application that will issue that's run in the fastest possible time.

How many types of local table in sql define with syntax


There are 2 types of temporary tables, local and global. Local temporary tables are created using a single pound (#) sign and are visible to a single connection and automatically dropped when that connection ends. Global temporary tables are created using a double pound (##) sign and are visible across multiple connections and users and are automatically dropped when all SQL sessions stop referencing the global temporary table. CREATE TABLE #MyTempTabl e ( PolicyId INT IDENTITY(1,1) PRIMARY KEY NOT NULL, LastName VARCHAR(50) NOT NULL )

Can you explain about buffer cash and log Cache in sql server?
Buffer Cache: Buffer cache is a memory pool in which data pages are read. It performance of the buffer cache is indicated as follows: 95% indicates that pages that were found in the memory are 95% of time. Another 5% is needed for physical disk access. If the value falls below 90%, it is the indication of more physical memory requirement on the server. Log Caches: Log cache is a memory pool used to read and write the log pages. A set of cache pages are available in each log cache. The synchronization is reduced between log and data buffers by managing log caches separately from the buffer cache.

What is a Trace frag? Where do we use it?


Temporary setting of specific server characteristics is done by trace tags. DBCC TRACEON is the command to set the trace flags. Once activated, trace flag will be in effect until the server is restarted. Trace frags are frequently used for diagnosing performance issues. For example, the trace flag 3205 is used for disabling hard compression for tape drives, when an instance of SQL Server starts.

Explain how to make remote connection in database


The following is the process to make a remote connection in database:

    

Use SQL Server Surface Area Configuration Tool for enabling the remote connection in database.
Click on Surface Area Configuration for Services and Connections. Click on SQLEXPRESS/Database Engine/RemoteConnections Select the radio button: Local and Remote Connections and select Using TCP/IP only under Local and Remote Connections. Click on OK button / Apply button

What is index segmentation?


A segment is a part of relational data base and consists of one or more extents. Each extent is further divided into blocks. Every segment has an index for holding all of its data for quick data retrieval. Index segments can be created explicitly by using the CREATE INDEX command. Storage parameters for the extents of the index segment can be specified along with this command. What is transact-SQL? Describe its types?
T-SQL is used by any application trying to access/use SQL Server. All applications thus interact with an SQL Server instance using T-SQL statements.

Types of T-SQL:

    

Data types User defined temporary objects Specialized functions global variables System and extended procedures Cursors

Define database object.


Database object depicts the properties of a single SQL Server instance.

How can I make database to be read only?

Answer: To make database to be read only, you can use the Enterprise Manager or the sp_dboption system stored procedure. For example, to make the pubs database to be read only, you can use the following statement: EXEC sp_dboption 'pubs', 'read only', 'TRUE' Read SQL BOL to get more information about the sp_dboption system stored procedure.
HOW TO FIND DATABASE SIZE USING QUERY IN SQL SERVER ?

Its : sp_spaceused

What is Index Fragmentation ?

Index fragmentation is a phenomena where index contents are no longer stored continuously in the storage. When index contents become scattered in the storage, fragmented, performance on index will degrade.
How To Test ODBC DSN Connection Settings?

Assuming you have followed other FYIcenter.com tutorials and created an ODBC DSN called "ggl_SQL_SERVER", and planning to use it your PHP scripts, you should test this ODBC connection first as shown in this tutorial: 1. Go to Control Panel > Administrative Tools. 2. Run Data Sources (ODBC). The ODBC Data Source Administrator window shows up. 3. Click "System DSN" tab, select "ggl_SQL_SERVER", and click "Configure..." button. The Microsoft SQL Server DSN Configuration wizard window shows up. 4. Review the first screen and click Next. 5. Review the second screen, enter the password as "GlobalGuideLine", and click Next. 6. Review the third screen and click Next. 7. Review the fourth screen and click Finish. 8. Review the confirmation screen and click "Test Data Source...". You should see the test result as: Attempting connection Connection established Verifying option settings Disconnecting from server
What Happens If You Are Trying to Access a Schema Not Owned by You?

In general, if you are trying to access an object in schema owned by another database user, you will get a "permission denied" error, unless that you have been granted access permission to that object explicitly. Here is a tutorial example showing you the permission error: -- Login with "ggl_login" USE GlobalGuideLineDatabase; GO

PRINT User_Name(); GO ggl_User SELECT COUNT(*) FROM dbo.ggl_random; GO Msg 229, Level 14, State 5, Line 1 SELECT permission denied on object 'ggl_random', database 'GlobalGuideLineDatabase', schema 'dbo'.

How To List All Login Names on the MS SQL Server?

If you want to see a list of all login names defined on the server, you can use the system view, sys.server_principals as shown in this tutorial exercise: -- Login with sa SELECT name, sid, type, type_desc FROM sys.server_principals WHERE type = 'S'; GO name sid type type_desc
How To Change the Ownership of a Schema in MS SQL Server?

If you want to change the owner of a schema, you can use the "ALTER AUTHORIZATION" statement using the following syntax: ALTER AUTHORIZATION ON SCHEMA::schema_name TO user_name The following tutorial example shows you how to change ownership of schema "ggl" to "ggl_user": -- Login with "sa" USE GlobalGuideLineDatabase; GO ALTER AUTHORIZATION ON SCHEMA::ggl TO ggl_user GO SELECT s.name, u.name AS owner FROM sys.schemas s, sys.database_principals u WHERE s.principal_id = u.principal_id; GO

name owner ------------------- -------------------dbo dbo ggl ggl_User guest guest


How To Verify the Port Number of the SQL Server?

When applications use TCP/IP for network communication, you need to know the port number where the server is listening for connect request from the client. If you want to connect to the SQL Server through the TCP/IP, you must know on which port number the SQL Server is listening for connection requests. Follow this tutorial to find and verify the port number of your SQL Server. 1. Go to Start > All Programs > Microsoft SQL Server 2005 > Configuration Tools > SQL Server Configuration Manager. 2. Double click on "SQL Server 2005 Network Configuration" to see the list of SQL Server instances. 3. Click on "Protocols for SQLEXPRESS". You will see a list of protocols. 4. Right-mouse click on TCP/IP and select the "Properties" command. The properties dialog box shows up. Click the IP Address tab. The server IP address and port number used by the SQL Server will be displayed. You should see something like: IP Address: 127.0.0.1 Ports: 1269 Note that 1433 may also be used as the default port number by your SQL Server.

WHY DO YOU WANT TO WORK FOR THIS ORGANIZATION?

Brief about Bulk copy with an example.


Answer Bulk copy utility of SQL allows data to be copied from one data file to another. The data is first exported from the source data file and then imported into the SQL server using the bcp command. It can also be used to transfer data from a table to a file.

What is Index Tuning Wizard in sqlserver 2005?


Index Tuning Wizard is a software application that identifies tables which have inefficient indexes. It makes recommendations on how indexes should be built on a database to optimize performance. The recommendations are based on TSQL commands that the wizard analyzes.

List out what Index Tuning Wizard can do in Sqlserver 2005


1. 2. 3. 4. 5. 6. It identifies tables in need of an index change Implements recommendations Determines how a proposed change might affect performance Has the capability to make indexes change immediately and schedule them Helps to tune indexes.

What are high availability features in Sql server 2005?


1. Log Shipping 2. Mirroring 3. Replication 4. Failover Clustering 1) Log Shipping is an old technique available since SQL SERVER 2000. Here the transactional log (ldf) is transferred periodically to the standby server. If the active server goes down, the stand by server can be brought up by restoring all shipped logs. Usage Scenario: You can cope up with a longer down time. You have limited investments in terms of shared storage, switches, etc.

2) Mirroring which was introduced with 2005 edition, works on top of Log Shipping. Main difference is the uptime for the standby server is quite less in mirroring. Standby server automatically becomes active in this case (through help of a broker server which is called as Witness in SQL SERVER parlance), without having to restore logs (actually logs are continuously merged in this scenario no wonder it s called Mirror ). Additional advantages of Mirroring include support at .NET Framework level (read no switching/routing code requires ADO.NET 2.0 & higher) plus some new features like Auto Page Recovery introduced with SQL SERVER 2008. Usage Scenario: You want very less down time and also a cost effective solution in terms of shared storage, switches, etc. Also you are targeting a single database which easily fits in your disks. 3) Replication is used mainly when data centers are distributed geographically. It is used to replicate data from local servers to the main server in the central data center. Important thing to note here is, there are no standby servers. The publisher & subscriber both are active. It has no down time Usage Scenario: A typical scenario involves syncing local / regional lookup servers for better performance with the main server in data center periodically, or sync with a remote site for disaster recovery. 4) Failover Clustering is a high availability option only (unlike others above which can be used for disaster recovery as well) used with clustering technology provided by hardware + OS. Here the data / databases don t belong to either of servers, and in fact reside on shared external storage like SAN. Advantages of a SAN storage is large efficient hot pluggable disk storage. Here s a good article on adding geo redundancy to a failover cluster setup. You might want to look at the licensing options of SQL Server, various editions available and how they map to above features

What are some well-known DBCC (Data Base Consistency Check) Commands in Sqlserver 2005?
1. DBCC Shrinkdatabase 2. DBCC SHRINKfile 3. DBCC Showcontig 4. DBCC help 5. DBCC IndexDefrag

6. DBCC CheckDB 7. DBCC CheckFilegroup It shows what are all the open transactions in log8. DBCC OPENTRAN It gives you status of virtual logs if status=2 then that is in use9. DBCC LOGINFO 10. DBCC DBREINDEX( Table name , Index anme , Fillfactor ) 11. DBCC CHECKIDENT( T_B_P Table anme , RESEED, 45) it sets seed to 45 12. DBCC SQLPERF( LOGSPACE) Used to see all databases log file sizes. EX: DBCC SQLPERF(LOGSPACE); GO

How to get top 3 records without using TOP clause in sqlserver 2005?
set rowcount 3 SELECT * FROM dept Execute the two statements in a single process. But it sets all the values are set to 3 in this process, if you want to change set rowcount 0

How do I list all the indexes on a particular table in sqlserver 2005?


USE YourDatabasename; GO EXEC sp_helpindex 'Your_Table_Name' GO

What is refreshing in SQLServer?


You most likely refresh a development or test environment frequently with a recent production environment backup. Depending on what you are testing or developing, current data may be critical to ensuring your results are valid. Creating an automated task to restore the database regularly (weekly, daily or even several times a day as needed) will save lots of time and guarantee that you do not miss any necessary restore steps. At a high level, you should complete the following steps to refresh a test or development environment using backup and restore as the refresh method: 1. Back up the production database: You should already have a scheduled process that creates daily full backups, so use the backup files that are already in place. 2. Copy all the users in test environment to some other table in master data base 2. Kill connections to database: In order to do a restore, there can be no active connections to the

database. All connections to the database must be killed before you start the restore. 3. Restore the database: Issue the restore command. 4. Re-link users and logins: Users and logins are associated by SIDs (security identifiers). These may not be the same on your production and test environments, so you will need to re-lid

Difference between Sql server 2000 and 2005


SQL Server 2000

Security:Owner = Schema, hard to remove old users at times Encryption:No options built in, expensive third party options with proprietary skills required to implement properly. High Availability Clustering or Log Shipping require Enterprise Edition. Expensive hardware. Scalability:Limited to 2GB, 4CPUs in Standard Edition. Limited 64-bit support.

SQL Server 2005

Security Schema is separate. Better granularity in easily controlling security. Logins can be authenticated by certificates. Encryption Encryption and key management build in. High Availability Clustering, Database Mirroring or Log Shipping available in Standard Edition. Database Mirroring can use cheap hardware. Scalability 4 CPU, no RAM limit in Standard Edition. More 64-bit options offer chances for consolidation.

Killing open transaction in Sql server


In Sql server 2005 we can see open Tranasctions by using DBCC Command DBCC opentran() Press enter It Shows open transactions with Tranaction ID(Process ID) Then Apply kill command Kill 45 ( here 45 is pocessID)

How to reset identity seed value?


SELECT IDENT_CURRENT('TestTable') IdentityInTable -- shows current identity Now execute the DBCC CHECKIDENT command to reset the Seed value for the table as DBCC CHECKIDENT('TestTable', RESEED, 33) reset identity

check the current Identity Value. SELECT IDENT_CURRENT('TestTable') IdentityInTable

Is it possible to take system data bases backup?


Yes, it s possible except to take temp data base backup

Importance of the Resource Database


SQL Server 2005 introduced a new read-only, hidden system database named Resource (RDB). The Resource database contains copies of all system objects that are shipped with SQL Server 2005 and SQL Server 2008. Resource Database Overview The Resource database is a read only, hidden system database that contains all the SQL Server system objects such as sys.objects which are physically available only in the Resource database, even though they logically appear in the SYS schema of every database. The Resource Database does not contain any user data or any user metadata. By design, the Resource database is not visible under SQL Server Management Studio s Object Explorer | Databases | System Databases Node. The physical file names of the Resource database is mssqlsystemresource.mdf and mssqlsystemresource.ldf. The important thing to be noted is that each instance of SQL Server has one and only one associated mssqlsystemresource.mdf & mssqlsystemresource.ldf file and that instances do not share this file. In a clustered environment, the Resource database exists in the \Data folder on a shared disk drive. The ID for the Resource Database will be always 32767. The DBA shouldn t rename or move the Resource Database file. If the files are renamed or moved from their respective locations then SQL Server will not start. The other important thing to be considered is not to put the Resource Database files in a compressed or encrypted NTFS file system folders as it will hinder the performance and will also possibly prevent upgrades. Resource Database File Location in SQL Server 2005 In SQL Server 2005 the Resource Database related MDF and LDF files will be available in :\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\ directory. The important thing to be noted is that the Resource Database related MDF & LDF file need to be available in the same directory where the Master Databases MDF & LDF files are located. By default during the installation of SQL Server 2005 both the Resource and the Master database files will be available in the same \Data directory. Resource Database File Location in SQL Server 2008 In SQL Server 2008 the Resource Database related MDF and LDF files will be available in : \Program Files\Microsoft SQL Server\MSSQL10.\MSSQL\Binn. The important thing to be noted is that the Resource Database related MDF & LDF file are in the \Binn directory and the Master Databases MDF & LDF files will be located in the : \Program Files\Microsoft SQL Server\MSSQL10.\MSSQL\Data directory.

In SQL Server 2008 it is not mandatory to keep both the Resource and Master Database files in the same directory. Advantages of Resource Database In previous versions of SQL Server whenever service packs are applied all the system objects that are residing within the system and user databases gets updated which makes it very difficult to rollback the changes. The only way to rollback the changes is to uninstall the instance of SQL Server and reinstall SQL Server followed by applying any Service Packs or Hotfixes to revert it to the previous version of the SQL Server Instance In SQL Server 2005 onwards the changes will be made to the Resource Database, which will indeed reflect the changes in all the system and user database of the particular instance If the DBA needs to apply a Service Pack to multiple instances, then the mssqlsystemresource.mdf and mssqlsystemresource.ldf needs to be copied by the DBA to the target instance If the DBA needs to rollback the changes performed by the Service Packs then they need to replace the Resource Database related MDF and LDF files with that of the previous backed up version TSQL Query to determine the version of Resource Database SELECT SERVERPROPERTY('ResourceVersion') GO TSQL Query to determine when the Resource Database was last backed up SELECT SERVERPROPERTY('ResourceLastUpdateDateTime'); GO

difference between Indexes and Statistics in SQL Server


An index is a physically implemented structure in the database (you can read up more in BOL on clustered and non-clustered indexes) whereas statistics are a set of values that help the optimizer during the execution plan formation stages to decide whether to use an index or not. And it is not a 1-1 relationship between indexes and statistics i.e. all indexes have statistics but one can have statistics without an index. And these statistics that do not associate to an index can also help in the formation of the right execution plan. We will cover that in another post as to how that can help. In this post, let s cover the basics of these statistics. An index helps the optimizer to find the data during the execution of the statements and statistics help the optimizer to determine which indexes to use. So, what exactly do statistics contain that make them so useful? Statistics essentially contain two pieces of information: 1) A histogram which contains a sampling of the data values from the index and the distribution of the values in the ranges of data

2) Density groups (collections) over the column (or number of columns) of a table or an indexed view. Density essentially reflects the uniqueness of the values in a particular column.

How to set alias name for column while retrival in sqlserver 2005
Alias name is name which is given by user.... Select Emp_ID, Emp_name from Emp o/p: Emp_ID Emp_name --------------------101 suresh 102 kumar If i need to display Emp_ID as Employee Number and Emp_name as EmployeeName, Then we will change our querry as follows Select Emp_ID AS Employee Number , Emp_name AS EmployeeName from Emp o/p: Employee Number EmployeeName --------------------------------------101 suresh 102 kumar

How do we list all the statistics for particular table?


USE URDATABASE; GO EXEC sp_helpstats 'YOUR_Table_Name' GO

Find Disk Free Space in Sql Server 2005 or 2008


Execute following procedue in Query window Use Master GO EXEC master..XP_FixedDrives GO

Trouble shooting Alerts


Troubleshooting SQL Server Alerts

If you have problems with Microsoft SQL Server alerts, review this troubleshooting checklist to find potential solutions. 1. Check that you are using the latest SQL Server service pack. Because many alert bugs were fixed in SQL Server service packs, you should install the latest SQL Server service pack. Check "How can I check what SQL service pack am I running?" to find out which SQL Server service pack you are running. 2. Check that the account the SQLServerAgent services runs under is a member of the Domain Users group. The LocalSystem account does not have network access rights. Therefore, if you want to forward events to the application logs of other Windows NT or Windows 2000 computers, or your jobs require resources across the network, or you want to notify operators through e-mail or pagers, you must set the account the SQLServerAgent service runs under to be a member of the Domain Users group. 3. If all of the alerts are not firing, check that the SQLServerAgent and EventLog services are running. These services must be started, if you need the alerts to be fired. So, if these services are not running, you should run them. 4. If an alert is not firing, make sure that it is enabled. The alert can be enabled or disabled. To check if an alert is enabled, you can do the following: 1. Run SQL Server Enterprise Manager. 2. Expand a server group; then expand a server. 3. Expand Management; then expand SQL Server Agent. 4. Double-click the appropriate alert to see if the alert is enabled. 5. Check the history values of the alert to determine the last date that the alert worked.

To view the history values of the alert, you can do the following: 1. Run SQL Server Enterprise Manager. 2. Expand a server group; then expand a server. 3. Expand Management; then expand SQL Server Agent. 4. Double-click the appropriate alert to see the alert history. 6. Verify that the counter value is maintained for at least 20 seconds. Because SQL Server Agent polls the performance counters at 20 second intervals, if the counter value is maintained for only a few seconds (less than 20 seconds), there is a high likelihood that the alert will not fire. 7. Check the SQL Server error log, SQL Server Agent error log, and Windows NT or Windows 2000 application log to get a more detailed error description. Comparing the dates and times for alert failure events between the SQL Server error log, the SQL Server Agent error log, and the Windows NT or Windows 2000 application log can help you to determine the reason of the failure. 8. If the alert fires, but the responsible operator does not receive notification, try to send 'e-mail', 'pager', or 'net send' message to this operator manually. In most cases, this problem arises when you have entered an incorrect 'e-mail', 'pager', or 'net send' addresses. If you can send an 'email', 'pager', or 'net send' message manually to this operator, check the account the SQL Server Agent runs under, as well as the operator's on-duty schedule. 9. If the alert fires, but the notification is not timely, decrease the 'Delay between responses' setting for the alert and try to send notifications to as few operators as possible. To decrease the 'Delay between responses' setting for the alert, you can do the following:

1. Run SQL Server Enterprise Manager. 2. Expand a server group; then expand a server. 3. Expand Management; then expand SQL Server Agent. 4. Double-click the appropriate alert and choose the 'Response' tab. 5. Specify a new 'Delay between responses' setting. 10. Alert cannot send e-mail notification with xp_logevent or RAISERROR. This is an SQL Server 7.0 and SQL Server 2000 bug. This happens if the alert is defined to be restricted to a specific database other than the master database. To work around this, you can define the alert on the master database, or all databases. To define the alert on all databases, you can do the following: 1. Run SQL Server Enterprise Manager. 2. Expand a server group; then expand a server. 3. Expand Management; then expand SQL Server Agent. 4. Double-click the appropriate alert and choose '(All Databases)' in the Database name combobox. 11. Alerts are triggered incorrectly when Security Auditing is enabled. This is an SQL Server 7.0 and SQL Server 2000 bug. This bug was fixed in SQL Server 2000 service pack 1 and in SQL Server 7.0 service pack 4. To work around this problem, you can disable Security Auditing, or you can install the service packs. 12. After Installing SQL Server 7.0 service pack 3, SQL Server Agent alerts may fail to work. This is an SQL Server 7.0 service pack 3 bug. To work around this, you should install SQL Server 7.0 service pack 4. 13. Responses for performance condition alerts are sent every 20 seconds, regardless of the 'Delay between responses' setting for the alert. This is an SQL Server 7.0 bug. To work around this, you should install

SQL Server 7.0 service pack 1 or higher.

DIFFERENCE BETWEEN SQLSERVER 2005 AND 2008


DIFFERENCE BETWEEN 2005 AND 2008:

Feature Name Backup Compression Page level compression

SqlSearver 2005 Not available

Sqlserver 2008 Available

Not available

Available Available 16 nodes are supported in Enterprise Edition Available Available Available Available ( In mirroring all transactions are encrypted while moving data)

Data Compression Not available Clustering 8 nodes are supported in Enterprise Edition

Resource Governor Not available File Stream Facets Encryption Not available Not available Not available

Show header form Data Base backup with out backup restoration
List header data from Backup without restoration: Here is code for list heade that is in Backup. It just show header information. Syntax: RESTORE HEADERONLY FROM DISK='path of your backup file' EXAMPLE: RESTORE HEADERONLY FROM DISK='D:\mydatabse_backup.bak' Here 'mydatabse_backup.bak' is my data base backup name. So replace this name with your database backup file name. Posted by SQLCode4u at 3:55 PM 0 comments Email This BlogThis! Share to Twitter Share to Facebook Share to Google Buzz Labels: RESTORE HEADERONLY in SQLSERVER 2005

List All files from Backup without restoration, How?


List All files from Backup without restoration:

Here is code for list all files that are in Backup. It just show files list not restore. Syntax: RESTORE FILELISTONLY FROM DISK='path of your backup file' EXAMPLE: RESTORE FILELISTONLY FROM DISK='D:\mydatabse_backup.bak' Here 'mydatabse_backup.bak' is my data base backup name. So replace this name with your database backup file name. Posted by SQLCode4u at 3:51 PM 0 comments Email This BlogThis! Share to Twitter Share to Facebook Share to Google Buzz Labels: RESTORE FILELISTONLY in SQLSERVER

Tuesday, October 26, 2010

SQL Server 2008 FILESTREAM


Implementing SQL Server 2008 FILESTREAM functionality The new FILESTREAM functionality in SQL Server 2008 lets you configure a varbinary(max) column so that the actual data is stored on the file system, rather than within the database. You can still query the column as you would a regular varbinary(max) column even though the data itself is stored externally. The FILESTREAM feature integrates Windows NTFS with the SQL Server database engine by storing binary large object (BLOB) data as files on the local file system. You can use Transact-SQL statements to query, insert or update the data, or you can use Win32 file system interfaces for direct streaming access to the data. Microsoft recommends that you use FILESTREAM only if (1) your BLOB data files are, on average, larger than 1 MB, (2) you need fast read access to that data, and (3) your application uses a middle tier for application logic. Otherwise, you should use a regular varbinary(max) column. If you do decide to implement a FILESTREAM column, you'll need to take the following steps: Enable FILESTREAM support on the SQL Server 2008 service. Configure the database to support FILESTREAM storage. Define a column that supports FILESTREAM storage. Posted by SQLCode4u at 4:26 PM 0 comments Email This BlogThis! Share to Twitter Share to Facebook Share to Google Buzz

Labels: SQL Server 2008 FILESTREAM

SQLCODE4YOU: Resource Governor in SQL Server 2008


SQLCODE4YOU: Resource Governor in SQL Server 2008: "Resource Governor in SQL Server 2008 This is new version for Sql Server 2008. Resource governor is one of the best additions in SQL Server..." Posted by SQLCode4u at 3:52 PM 0 comments Email This BlogThis! Share to Twitter Share to Facebook Share to Google Buzz

Resource Governor in SQL Server 2008


Resource Governor in SQL Server 2008

This is new version for Sql Server 2008. Resource governor is one of the best additions in SQL Server 2008. It gives you a real control on your environment as a DBA and can be very useful for better utilization of your database server resources. So far so good, but don t just start using it without knowing how it actually restricts resource utilization. Following are some points to remember for better utilization of this feature: Normally, most of us assume that if we restricts a memory usage for a user A upto 10% only then he will never be able to utilize more than 10% of server in any case. Right? Wrong. Actually, Resource governer only restricts user to utilize not more than 10% if it feels that remaining memory is not available but if memory is available and there are no pending workload then it will allow the user to use more than its allowed quota of 10%. This is there to optimize the utilization of memory and avoids wastage of resources. But it can have worse effects also because if User A fires it query before other users then server will start utilizing all the available memory and all other users which came afterwards will suffer the consequences. Please note that Resource Governor is for database engine not for other services in SQL Server 2008. It means you can not control usage of Reporting Services, Analysis Services or Integration Services. If you have multiple instances running on same machine then you can not use Resource Governor to manage load between these instances. Keeping these points in your mind will help you to better understand how to use resource governor and what to expect. It is one of the best tools to manage your load and highly recommended but make sure you know the pros and cons of it.

Why Logshipping supports only FullBackup and Bulk-logged recovery models?

Logshipping means ship log files to another location from stand by server. Log file contains all the DML statements information. The basic aim behind Logshipping is to maintain all old transactions in seperate place. If we use simple recovery model all the DML Statements information is not recorded So, This is not supported for logShipping. Where as in the case of full/bulklogged recovery model all the DML Statements coresponding log information is avilable in log files. So LogShipping accepts only Full/Bulk-Logged recovery models.

Run command for sqlserver 2008


1.click on start button 2.click on run from start menu 3.type SSMS 4.press enter 5.It opens SQLServer 2008 or 10.0 version

Run command for for sqlserver 2005


1.click on start button 2.click on run from start menu 3.type sqlwb 4.press enter 5.It opens SQLServer 2005

RESTORE VERIFYONLY In SQL Server 2005


RESTORE Usage: RESTORE VERIFYONLY FROM DISK = 'C:\www\EMP_backup_201010130110.bak'

Out Put: The backup set on file 1 is valid.

DBCC CHECKDB
The question I ask in an interview is: "You get an error in the logs indicating that you have a torn page or checksum error. What do you do?"

Half the candidates look confused. Of the rest, roughly 90% tell me to run DBCC CHECKDB with one of the repair options! When I challenge them to explain how CHECKDB performs the repair, none are able to answer, unaware of the damage they might be doing. So here is how to use DBCC CHECKDB, and what to do when you have a torn or corrupt page. So How Do I Use It? The primary purpose is to check for consistency errors, and should ideally be run every day. The basic syntax is: DBCC CHECKDB ('DB Name') WITH NO_INFOMSGS NO_INFOMSGS prevents an excessive number of informational messages from being generated. There are several other options, but this is the syntax you should aim to use as it performs all integrity checks. This may take a long time on large databases and you may want to specify the PHYSICAL_ONLY option. This checks physical on-disk structures, but omits the internal logical checks. The syntax is: DBCC CHECKDB ('DB Name') WITH PHYSICAL_ONLY What Do I Do? You do have backups don't you? You might be lucky; a non-clustered index can be dropped and rebuilt but actual data, such as a clustered index, cannot. By far the best option is to restore from a backup, but let's look at how you investigate which pages are affected and what type of data is affected: Look at the output from DBCC CHECKDB. You may see something like this:

bject ID 2088535921, index ID 0, partition ID 72345201021503994, alloc unit ID 72345201051571606 (type In-row data): Page (1:94299) could not be processed. See other errors for details. Msg 8939, Level 16, State 98, Line 1 Table error: Object ID 2088535921, index ID 0, partition ID 72345201021503994, alloc unit ID 72345201051571606 (type In-row data), page (1:94299). Test (IS_OFF (BUF_IOERR, pBUF->bstat)) failed. CHECKDB found 0 allocation errors and 2 consistency errors in table 'yourtable' (object ID 2088535921). CHECKDB found 0 allocation errors and 2 consistency errors in database 'yourdb'. repair_allow_data_loss is the minimum repair level for the errors found by DBCC CHECKDB (yourdb).

From this you can see what page is corrupted (1:94299) The first thing to do is check if it is data in a heap, in a clustered index, or in a non-clustered index. In the above text you can see it is index ID 0. You could also examine the page (1:94299 in database 'yourdb') as follows: DBCC TRACEON (3604, -1) GO DBCC PAGE('yourdb', 1, 94299, 3) GO In the output you will see something like: Metadata: IndexId = n If n is greater than 1 it is a non-clustered index and can safely be dropped and recreated. If n is 0 or 1 you have data corruption and need to perform one of the options described below. Restoring from a backup If the recovery model is FULL (or BULK_LOGGED, with some limitations), you can backup the tail of the log, perform a restore (with norecovery) from the last clean full backup, followed by subsequent log backups and finally the tail of the log. If only a few pages are affected you have the option of selectively restoring only the bad pages, as follows:

RESTORE DATABASE yourdb PAGE = '1:94299' FROM DISK = 'C:\yourdb.bak' WITH NORECOVERY If the recovery model is simple you don't have that option, and have to accept that a restore from the last full backup will result in subsequent transactions being lost. In this case, or if you have no backups at all, you may decide that an automatic repair is the only option. Automatic Repair Options First let me emphasise the importance of running a backup BEFORE you go any further. Have a look at the output of the original CHECKDB. It will specify the minimum repair level. REPAIR_REBUILD If the minimum repair level is REPAIR_REBUILD you have been lucky. The syntax is DBCC CHECKDB('DB Name', REPAIR_REBUILD) REPAIR_ALLOW_DATA_LOSS This attempts to repair all errors. Sometimes the only way to repair an error is to deallocate the affected

page and modify page links so that it looks like the page never existed. This has the desired effect of restoring the database's structural integrity but means that something has been deleted (hence the ALLOW_DATA_LOSS). There are likely to be issues with referential integrity, not to mention the important data that may now be missing. The syntax is DBCC CHECKDB('DB Name', REPAIR_ALLOW_DATA_LOSS) Make sure you run DBCC CHECKCONSTRAINTS afterwards so you are aware of referential integrity issues and can take the appropriate action. And Finally My original reason for writing this was to stress that the correct action when faced with corruption is nearly always to restore from a backup. Only use the automatic repair options as a last resort, and with full understanding of the damage this may do. Just as important is that regular backups are an essential part of a DBA's responsibilities, and you should use the FULL recovery model with regular log backups for all but the most trivial databases. DBCC CHECKDB is a powerful tool, but also very dangerous in the wrong hands. Maybe instead of adding the REPAIR_ALLOW_DATA_LOSS option, Microsoft should have created a separate DBCC command called: DBCC DELETE_DATA_BECAUSE_I_COULDNT_BE_BOTHERED_TO_TAKE_A_BACKUP

SQLCODE4YOU: When and how to use Database Snapshots


SQLCODE4YOU: When and how to use Database Snapshots: "SQL Server 2005 offers many features that did not exist in previous versions of the product. One such feature is Database Snapshots. Databas..."

SQL Server 2005 Recovery Models


SQL Server 2005 Recovery Models Full Recovery Model Bulk-Logged Recovery Model Simple Recovery Model

Full Recovery Model The Full Recovery Model is the most resistant to data loss of all the recovery models. The Full Recovery Model makes full use of the transaction log all database operations are written to the transaction log. This includes all DML statements, but also whenever BCP or bulk insert is used.

For heavy OLTP databases, there is overhead associated with logging all of the transactions, and the transaction log must be continually backed up to prevent it from getting too large.

Benefits: 1. Most resistant to data loss 2. Most flexible recovery options - including point in time recovery

Disadvantages:
y y

Can take up a lot of disk space Requires database administrator time and patience to be used properly

Bulk-Logged Recovery Model The Bulk-Logged Recovery Model differs from the Full Recovery Model in that rows that are inserted during bulk operations aren t logged yet a full restore is still possible because the extents that have been changed are tracked.

The following transactions are minimally logged in a Bulk-Logged Recovery Model:

SELECT INTO bcp and BULK INSERT CREATE INDEX Text and Image operations Benefits: 1. 2. 3. 4. 5. 6. Transaction log stays small Easier from an administration standpoint (don t have to worry about transaction logs) Disadvantages: Not for production systems Point in time recovery not possible Least data resistant recovery model

Simple Recovery Model The simple recovery model is the most open to data loss. The transaction log can t be backed up and is

automatically truncated at checkpoints. This potential loss of data is makes the simple recovery model a poor choice for production databases. This option can take up less disk space since the transaction log is constantly truncated.

Benefits: 1. 2. 3. 4. 5. 6. Transaction log stays small Easier from an administration standpoint (don t have to worry about transaction logs) Disadvantages: Not for production systems Point in time recovery not possible Least data resistant recovery model

clustering in SQL Server


It is high avilability concept only. It does not provide any 'Fault Tolarene' (i.e, I have Data Base, in this some table is missing.. By using Clustering we cont restore that table data.) Adv: No down time i say ( i.e 99.9999%) not 100%. Note: It is totally related to Windows based only. Not Sql Server related. Defination: It is concept of providing high avilability. By using using this we can reduce down time. Note: After installation of Clustering the total sql server behaves like normal sqlserver. There is no change in behaviour. Clustering supports only Server Operating Systems. Requirements: 1. Minimum Two machines(we cal this machine as NODE) with same Hardware (Same Ram, Same Hard drive, Same Processor) 2. Same Server Operating system(win 2003server..) in each node(Machine) 3. Active Directory in another machine(domain Controller) 4. SAN Box(Shared Array) like External Hard Disk. 5. 2 Network cards for each machine 6. 6 IP's (1 for Public Cluster, 1 for Public sqlserver, 4 for Network cards)

IDEA:

Quorum Drive: All sql server installation things are stored. FAQS: 1.What is Active/ Passive ? 2.Is sql server behaves different afetr we instal sql server in Cluster machine? Ans: No, It behaves normal 3.How to take Offline/Online? Ans: Right Click on Group--> Select Offline 4.What are the issues you faced? Ans: The node getting down 5.What are the minimum IP's Required for Clustering? Ans: For Two Cluster environment we need 6 IP's 6.How to trace failOver? 7.What happend We plugged out SAN Box Cable? 8.Is it support Load balancing? Ans: No 9.What is the minimum storage space require for Quorum? Ans:500 MB 10.How much time it takes come online from Offline? Ans: 1 min 11.What is hart Beat? Ans: It is a process of authenticating both nodes it alive or not

12.What is group? Ans: A group is nothing but managing node resources seperatly 13.Is it posible to install Two Sql Server Instances in single Group? Ans:No, This feature is avilable in 2008 version 14.How to Stop and Start SQl Servr Service in Cluster Environment? Ans: From Cluadmin then Click on group-->Right Click on service appear in right side pannel and then click stop/start. dont go to services.msc and stop from there. 15. how to Check Is our Machine participating in Clustering? Ans: Select serverproperty('IsCluster') 16.What is the Difference Between 32 bit and 64 bit? 17. How many cluster nodes are support in SQLSERVER 2005 with windows 2003 server? Ans:8 nodes 18. How many cluster nodes are support in SQLSERVER 2008 with windows 2008 server? Ans:16 nodes 19.How to Add node fro Cluster? Ans: Down load from the link fro etailed information... ClickHere

1486 Error in Mirroring


Error Description: Database mirroring transport is disabled in the endpoint configuration ............ Solution: ALTER ENDPOINT [mirroring] STATE= STARTED Here 'mirroring' is my end point name..

@@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT


When to use @@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT ?

@@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT are similar functions because they all return the last value inserted into the IDENTITY column of a table.

To give you a quick overview.... @@IDENTITY returns the last identity value generated for any table in the current session, across all

scopes. SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

@@IDENTITY After an INSERT, SELECT INTO, or bulk copy statement is completed, @@IDENTITY contains the last identity value that is generated by the statement. If the statement did not affect any tables with identity columns, @@IDENTITY returns NULL. If multiple rows are inserted, generating multiple identity values, @@IDENTITY returns the last identity value generated. If the statement fires one or more triggers that perform inserts that generate identity values, calling @@IDENTITY immediately after the statement returns the last identity value generated by the triggers. If a trigger is fired after an insert action on a table that has an identity column, and the trigger inserts into another table that does not have an identity column, @@IDENTITY returns the identity value of the first insert. The @@IDENTITY value does not revert to a previous setting if the INSERT or SELECT INTO statement or bulk copy fails, or if the transaction is rolled back.

SCOPE_IDENTITY (Transact-SQL) It returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch. For example, there are two tables, T1 and T2, and an INSERT trigger is defined on T1. When a row is inserted to T1, the trigger fires and inserts a row in T2. This scenario illustrates two scopes: the insert on T1, and the insert on T2 by the trigger. Assuming that both T1 and T2 have identity columns, @@IDENTITY and SCOPE_IDENTITY will return different values at the end of an INSERT statement on T1. @@IDENTITY will return the last identity column value inserted across any scope in the current session. This is the value inserted in T2. SCOPE_IDENTITY() will return the IDENTITY value inserted in T1. This was the last insert that occurred in the same scope. The SCOPE_IDENTITY() function will return the null value if the function is invoked before any INSERT statements into an identity column occur in the scope.

IDENT_CURRENT (Transact-SQL) IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope. It returns NULL when the function is invoked on an empty table or on a table that has no identity column.

SQL DBA interview questions+ CSC

CSC: 1. What is backup strategy? 2. How to rename SQL Server?


sp_dropserver GO sp_addserver , local GO

Remote Logins - If the computer has any remote logins, running sp_dropserver might generate an error similar to the following: Copy
Server: Msg 15190, Level 16, State 1, Procedure sp_dropserver, Line 44 There are still remote logins for the server 'SERVER1'.

To resolve the error, you must drop remote logins for this server.

To drop remote logins


For a default instance, run the following procedure: Copy
sp_dropremotelogin old_name GO

For a named instance, run the following procedure: Copy


sp_dropremotelogin 'old_name\instancename' GO

3. How to trouble shoot temp db? 4. How to solve connection issue?

5. How to solve recovery status issue, if my db box has 100 databases, In that only one db has go to suspect mode? How to solve? 6. IS Full text search service comes as default service? 7. How to find fragmentation level by using command prompt? 8. What are maintenance plans that you executed? 9. What type of alerting system that you configured for your sql server box? 10. What is your database size? 11. How to solve Log file growing issue? 12. Is it possible to take back up from primary server what was participated in log shipping? 13. What is end point in mirroring? 14. What are the security concerns that you execute while we configure mirroring? Posted by SQLCode4u at 5:39 PM 0 comments Email This BlogThis! Share to Twitter Share to Facebook Share to Google Buzz Labels: SQL DBA interview questions

Security in SQL Server 2005 VS SQL Server 2000

SQL Server 2000 1.Security:Owner = Schema, hard to remove old users at times 2.Encryption:No options built in, expensive third party options with proprietary skills required to implement properly. 3.High Availability:Clustering or Log Shipping require Enterprise Edition. Expensive hardware

SQL Server 2005 1.Security:Schema is separate. Better granularity in easily controlling security. Logins can be authenticated by certificates.

.Scalability:Limited to 2GB, 4CPUs in Standard Edition. Limited 64-bit support.

2.Encryption:Encryption and key management build in. 3.High Availability:Clustering, Database Mirroring or Log Shipping available in Standard Edition.

Database Mirroring can use cheap hardware.


.Scalability:4 CPU, no RAM limit in Standard Edition. More 64-bit options offer chances for consolidation.

1)-In SQL SERVER 2000 there where maximum 16 instances but in 2005 you can have up to 50 instances. 2)-Database mirror concept supported in SQL SERVER 2005 which was not present in SQL SERVER 2000. 3)-SQL SERVER 2005 has reporting services for reports which is a newly added feature and does not exist for SQL SERVER 2000.It was a separate installation for SQL Server 2000. 4)-SQL Server 2005 introduces a dedicated administrator connection (DAC) to access a running server even if the server is not responding or is otherwise unavailable. This enables you to execute diagnostic functions or Transact-SQL statements so you can troubleshoot problems on a server. which was not present in SQL SERVER 2000.

Posted by SQLCode4u at 5:36 PM 0 comments Email This BlogThis! Share to Twitter Share to Facebook Share to Google Buzz Labels: Security in SQL Server 2005 VS SQL Server 2000

SQL DBA interview questions+ IBM

1. What are tools that are used for backup and ticketing? a. Lite speed, BMC Remedy 2. How to restore lite speed backup into sqlserver, is it possible to restore directly? a. That is not possible, because media type should be same 3. What is the difference between User and login? a. User is data base level and login is server level 4. How to add drive for cluster? a. Go to cluadmin

b. Choose groups from left side c. Right click on add d. Choose drive which we want to add for existing cluster 5. What is heart beat? 6. What are problems that you face for log shipping? a. Establish network tunnel b. Reduce transaction backup time from 30 min to 15 min 7. What is your backup strategy? 8. What are the major differences between 2000 and 2005 in terms of security? a. Owner = Schema, hard to remove old users at times in 2000 b. Schema is separate. Better granularity in easily controlling security. Logins can be authenticated by certificates. In 2005 c. In 2000 there is no concept of synonyms, in 2005 it is introduced d. In 2000 there in policy based management, in 2008 it s there 9. What are the steps for restoring data base? a. Go through the restore wizard in sql server management studio 10. How to find deadlocks and how to resolve that? a. Just switch on the trace for 1204, 1222, 3605 b. ex:DBCC Traceon(1204,1222,3505,-1) 11. How to move logfile location from once drive to another drive?

a. By attach and detach


12. My log file is full how to solve it? a. By apply the shrink command b. Or by applying truncate command 13. Can you tell some regular use of DBCC Commands? a. Dbcc checkdb()

b. Dbcc showcontig() c. Dbcc dbreindex() d. Dbcc sqlperf() e. Dbcc traceon() f. Dbcc traceoff() g. Dbcc shrinkdatabase() h. Dbcc shrinkfile() i. Dbcc help() j. Dbcc ind() k. Dbcc checkident() l. Dbcc showfilestats() m. Dbcc inputbuffer() n. Dbcc outputbuffer() o. Dbcc log() p. Dbcc page( wowzzy ,1,945894,3) check page is corrupted or not 14. What is importance of dbcc showcontig()? Posted by SQLCode4u at 5:35 PM 0 comments Email This BlogThis! Share to Twitter Share to Facebook Share to Google Buzz Labels: SQL DBA interview questions

SQL DBA interview questions+ HCL + 2nd round

1. What is the difference between sys.databases and sysdatabases 2. How can we know linked servers information? Ans: select * from sys.servers 3. How to know all databases info that are in box? Ans: select * from sysdatabases 4. Are we run query on mirror server?

5. Are we run query on secondary server of log shipping? 6. What is default port for sqlserver? 1433(tcp/Ip), UDP:1434 7. What is dynamic port in sqlserver? 8. How to set default backup directory path? 9. How to add full text service after installation? 10. How to find orphan logins? 11. What is quorum? 12. What is the advantage of active & active two node clustering? 13. What are the reasons when a particular user account is not working? 14. What are the reasons for connection is slow? 15. What is the default time for remote connections? 600 16. What is auditing? 17. Which server role is assigned for backup? ANS: DB_BACKUPOPERATOR 18. I have 30GB Ram, How can we configure for production environment? Ans: Depends SLA 19. What are problems that you faced for log shipping? 20. What is the distribution database? 21. What does distribution database contains is it contains data? 22. What is fill factor? 23. How to shrink database? What are the steps? 24. How to move temp data base? 25. What are suggestible raid levels for mdf and log files?mdf-raid1, log raid5 26. How many temp db s are recommended as per Microsoft standards? 27. Have you used profiler? 28. Is it possible to save profiler data into table? Yes, in text file aslo 29. What are table partitions? 30. What is schema binding? 31. Can I create index on table partitions?

32. Can I get error while index is rebuilt? 33. I have 4 databases, in that having 4 users, those 4 users are mapped with some server roles, and those 4 users are there in one database. If I am deleting that major db, is remaining db users are working or not? Yes, they have access with reaming db s. Those are called orphan logins 34. How to take resource data base backup? Backing up the Resource database Since the Resource database is not available from the SQL Server tools, we cannot perform a backup similar to how we do it with the other databases. You can backup the database using the following options: . You can use a simple xcopy command to copy from the source location to a destination where you keep your daily database backups. Use the -Y option to suppress the prompt to confirm if you want to overwrite the file. You can create a scheduled task to do this on a daily basis. If you want to keep multiple copies of the database files, you can create an automated script to rename them after the copy process. xcopy :\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\mssqlsystemresource.mdf /Y xcopy :\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\mssqlsystemresource.ldf /Y . . . You can use your file-based backup utilities such as NTBackup, IBM Tivoli Storage Manager, Symantec BackupExec, etc. Restoring the Resource database It is important to document the location of your master database as part of your disaster recovery process. In previous versions of SQL Server, all we need to do to restore the server instance is to worry about the masterdatabase. After a SQL Server 2005 instance has been rebuilt a restore of the master database will be done, the Resourcedatabase files should go along with it should a WITH MOVE option be required. This means that if the old location of themaster database will be different from the one after the restore, the Resource database files should already be there prior to restoring the master database. This is very critical if a hardware failure occurred and you need to move the system databases on a different drive during the server instance rebuild. To restore the Resource database, just copy the database files to the location of the master database files. If you have an older version of the Resource database, it is important to re-apply any subsequent updates. This is why the recommended approach is to simply do a daily backup of these files.

Posted by SQLCode4u at 5:34 PM 0 comments Email This BlogThis! Share to Twitter Share to Facebook Share to Google Buzz Labels: SQL DBA interview questions+ HCL + 2nd round

SQL DBA interview questions+ Infosys

1. What is your backup strategy? 2. What is quorum? 3. How to install quorum? 4. What is DMV? 5. What normalization? 6. Solve backup failure scenario? 7. How many instances are there for your production box? 8. How to create Login? 9. How many CPU s are there for your environment? 10. What is the size of DB? 11. What are differences between sql server 2000 to sql server 2005? 12. What are the different versions in sql server? 13. What is your current version?

Posted by SQLCode4u at 5:33 PM 0 comments Email This BlogThis! Share to Twitter Share to Facebook Share to Google Buzz Labels: SQL DBA interview questions

SQL DBA interview questions+ HCL

HCL: 1. What is SQL Server Architecture? 2. What is page?

3. What is extent? 4. What are the different types of extents? Ans: Uniform extents: consists pages from same object, mixed mode extents: consists from different objects 5. What is the difference between those two extents? 6. Which pages are available in extents? 7. What is fill factor? 8. How to take backup of DB when the db is in Log shipping by taking that backup without changing LSN? Ans: By taking copy only backups 9. How to change port number for sql server? Ans: To assign a TCP/IP port number to the SQL Server Database Engine In SQL Server Configuration Manager, in the console pane, expand SQL Server 2005 Network Configuration, expand Protocols for, and then double-click TCP/IP. In the TCP/IP Properties dialog box, on the IP Addresses tab, several IP addresses appear, in the format IP1, IP2, up to IPAll. One of these are for the IP address of the loopback adapter, 127.0.0.1. Additional IP addresses appear for each IP Address on the computer. Right-click each address, and then click Properties to identify the IP address that you wish to configure. 10. Is it possible to change port for mirroring after configuring mirroring? Ans: Yes it is possible, by using above mechanism 11. What is the major difference between Merge replication and Transactional replication? Ans: In Merge replication the both publisher and subscriber can work independently 12. How to resolve conflicts in merge replication? 13. What is quorum in clustering? 14. What happened when quorum gone? 15. Is it possible to start service when quorum is gone? Ans: -No quorum 16. How to take backup of 400GB DB with in less time? Ans: Generally 1 GB take 1 min, If we use stripped backups we can reduce time, If we have 4 processors and 4 drives. 17. How to find what are the driver s available in our machine? Ans: EXEC master.sys.xp_fixeddrives 18. What is check point? Ans:Check point is raised when we take backup of database or restarting sql server service 19. Is it posible to raise chaeckpoint our self? Ans:Yes sp_configure 'recovery interval', 32767 go reconfigure with override

20. What is the difference between procedure and function? 21. How to call procedure? 22. What is the advantage of recompile statement in procedure? Ans: I have noticed that after inserting many rows in one table many times the stored procedure on that table executes slower or degrades. This happens quite often after BCP or DTS. I prefer to recompile all the stored procedure on the table, which has faced mass insert or update. sp_recompiles marks stored procedures to recompile when they execute next time. 23. How to know the current connected connections? 24. How to set maximum connections? Ans: SP_Configure 25. How to start sql service without raising checkpoint?
SHUTDOWN WITH NOWAIT

26. Have you work on cmd prompts? Ans: Run CMD net start mssqlserver Run CMD net stop mssqlserver 27. What is transaction? Ans: IT is nothing but sequence of actions 28. Can you say syntax of transaction? Ans: Begin Tran Statements Commit Tran 29. What is difference between cascade drop of table? Ans: Cascade option allows the user to delete all the tables which are defined by foreign key relation 30. What happened if we issue drop table command? Ans: If the tables are involved in foreign key relation, if we try to delete those tables. It will not allow deleting. If we delete under any circumstances we define that as cascade 31. What are the several recovery models? Ans: Full, simple, Bulk logged recovery model 32. Why log shipping is not supported in simple recovery model? 33. What is the default port for mirroring? Ans: 5022

34. How to change default port for sqlserver?

Ans: Go to sqlserver configuration manager service protocols choose TCP/IP right click Take properties Go to advanced Change IP for which are not loop backed ip 35. What is resource governor? 36. What is heart beating in clustering? 37. Which cable is used for heart beat, Is it cross cable or plain cable? ANS: Cross cable 38. What are the different types of indexes? 39. What are the limits for cluster and non cluster indexes? ANS: 1- 255 40. Why we have only one cluster index for table? 41. What is the importance of statistics? 42. Scenario: My server running fast upto the yester day, today onwords slows, As a DBA what you have to do? 43. How to find what are the queries that are running in particular SPID? sys.dm_exec_sql_text 44. How to find sql server version? Ans: select @@version 45. What is another port number for sqlserver? Ans: for TCP/IP: 1433, UDP: 1434 46. I have backup and I want to restore upto particular time only? Ans: Restore database wowzzy to disk= with stopat= time stamp 47. How to create user, how to assign read and write permissions only for that user? 48. What is Super admin, who is having total rights in system level? Ans: SA 49. What is full form of SA? Ans: System Administrator 50. What are the different locks? 51. What are different isolation levels? 52. What is serelizable? 53. What is exclusive lock? 54. I have done some schema change (Add column for table) in merge replication for an article, is it applied for subscriber? 55. Can you list some system tables?

Finding and troubleshooting SQL Server deadlocks


By: Greg Robidoux -- 8/9/2006
Rating: | Comments (2) | Print | Share

We're giving away another Kindle loaded with SQL Server eBooks

Problem One thing that will you most certainly face at some time as a DBA is dealing with deadlocks. A deadlock occurs when two processes are trying to update the same record or set of records, but the processing is done in a different order and therefore SQL Server selects one of the processes as a deadlock victim and rolls back the statements. For example you have two sessions that are updating the same data, session 1 starts a transaction updates table A and then session 2 starts a transaction and updates table B and then updates the same records in table A. Session 1 then tries to update the same records in table B. At this point it is impossible for the transactions to be committed, because the data was updated in a different order and SQL Server selects one of the processes as a deadlock viticm. To further illustrate how deadlocks work you can run the following code in the Northwind database.
To create a deadlock you can issue commands similar to the commands below. Step Commands

--open a query window (1) and run these commands 1

begin tran update products set supplierid = 2


-- open another query window (2) and run these commands 2

begin tran update employees set firstname = 'Bob' update products set supplierid = 1
-- go back to query window (1) and run these commands

update employees set firstname = 'Greg' At this point SQL Server will select one of the process as a deadlock victim and roll back the statement

--issue this command in query window (1) to undo all of the changes

rollback
5 --go back to query window (2) and run these commands to undo changes

rollback Solution The only solution for handling deadlocks is to find the problem in your code and then modify your processing to avoid deadlock situations. The first thing you need to do is find the deadlock situations and then investigate the problem. There are a couple of ways of doing this. The first approach is to turn on the trace flag to find the deadlocks. This can be done with the following statement run in Query Analyzer.
DBCC TRACEON (1204)

When a deadlock occurs the information like the following will be captured in the SQL Server Error Log.

From this output we can see that SPID 53: was updating object 1977058079 and SPID 52: was updating object 117575457. But what do these numbers mean. These numbers are the objectIDs. To determine what table is affected you will need to query the sysobjects table in the Northwind database or whatever user database the deadlock occurred in using the following command and the find the ID that matches the ID from the deadlock information. SELECT id, name FROM sysobjects WHERE xtype = 'U' ORDER BY id Another option to find the tables is to use the object_name function: SELECT object_name(1977058079) --(returns Employees) SELECT object_name(117575457) --(returns Products) Thanks goes out to Armando P. for pointing out the error as well as using the object_name function. With this information it is possible to see what tables were part of the deadlock process, but trying to figure out what statements caused the problem is much more difficult. To provide

further information about the deadlock process you will need to run a Trace to capture all of the information and then try to decipher what is going on. This can be done by either using Profiler or by using a Server Side Trace. With the trace there are a couple of additional items that need to be captured to help figure out what is going on and with what objects. SQL Profiler To do this using SQL Profiler, you will need to capture the Lock Events Lock:Deadlock and Lock:Deadlock Chain.

And also capture the ObjectId data column.

Server Side Trace For a Server Side Trace the following additional information will need to collected to capture the deadlock information.
EventNumber Event Description Indicates that two concurrent transactions have deadlocked each other by trying to obtain incompatible locks on resources the other transaction owns. Produced for each of the events leading up to the deadlock.

25

Lock:Deadlock

59

Lock:Deadlock Chain

In addition, you will also need to capture this additional column to see what objects are part of the deadlock chain.
ColumnNumber 22 Column ObjectID Description System-assigned ID of the object.

The output from our trace would show the following information:

From here we can see what was occurring at the time of the deadlock. This is a very simple example, but you can see how this additional information from a trace can help solve the problem. When you have a lot of information to go through it is easier to load the data into a SQL Server table and then query the data for the particular timeframe and SPIDs in question. This was covered in a Server Side Trace tip. Here is a sample query that can help you narrow down the timeframe when the deadlock occurred. By changing the date values and the SPIDs to look at you can narrow down what was occurring at the time or right around the time that the deadlock occurred.
DECLARE @lowDate AS datetime, @highDate AS datetime SET @lowDate = '2006-08-01 13:47:17.000' SET @highDate = '2006-08-01 13:47:18.999'

SELECT TextData, StartTime, EndTime, SPID,

Duration, Reads, Writes, EventClass FROM TraceFile WHERE SPID IN (52,53,4) AND (StartTime BETWEEN @lowDate AND @highDate OR EndTime BETWEEN @lowDate AND @highDate OR StartTime < @lowDate AND EndTime > @lowDate) ORDER BY StartTime

Next Steps
y y y Take the time to learn more about how to capture and troubleshoot deadlocks. Use the sample script to understand how they occur and what you can do to solve deadlock issues in your environment Learn how a Server Side Trace and loading the data to a SQL table can help troubleshoot this type of problem

User Defined Functions in Microsoft SQL Server 2000

By Don Schlichting
This article will explore the uses, restrictions and benefits of User Defined Functions in Microsoft SQL Server 2000

Introduction
User Defined Functions are compact pieces of Transact SQL code, which can accept parameters, and return either a value, or a table. They are saved as individual work units, and are created using standard SQL commands. Data transformation and reference value retrieval are common uses for functions. LEFT, the built in function for getting the left part of a string, and GETDATE, used for obtaining the current date and time, are two examples of function use. User Defined Functions enable the developer or DBA to create functions of their own, and save them inside SQL Server.

Advantages of User Defined Functions


Before SQL 2000, User Defined Functions (UDFs), were not available. Stored Procedures were often used in their place. When advantages or disadvantages of User Defined Functions are discussed, the comparison is usually to Stored Procedures. One of the advantages of User Defined Functions over Stored Procedures, is the fact that a UDF can be used in a Select, Where, or Case statement. They also can be used to create

joins. In addition, User Defined Functions are simpler to invoke than Stored Procedures from inside another SQL statement.

Disadvantages of User Defined Functions


User Defined Functions cannot be used to modify base table information. The DML statements INSERT, UPDATE, and DELETE cannot be used on base tables. Another disadvantage is that SQL functions that return non-deterministic values are not allowed to be called from inside User Defined Functions. GETDATE is an example of a nondeterministic function. Every time the function is called, a different value is returned. Therefore, GETDATE cannot be called from inside a UDF you create.

Types of User Defined Functions


There are three different types of User Defined Functions. Each type refers to the data being returned by the function. Scalar functions return a single value. In Line Table functions return a single table variable that was created by a select statement. The final UDF is a Multi-statement Table Function. This function returns a table variable whose structure was created by hand, similar to a Create Table statement. It is useful when complex data manipulation inside the function is required.

Scalar UDFs
Our first User Defined Function will accept a date time, and return only the date portion. Scalar functions return a value. From inside Query Analyzer, enter: CREATE FUNCTION dbo.DateOnly(@InDateTime datetime) RETURNS varchar(10) AS BEGIN DECLARE @MyOutput varchar(10) SET @MyOutput = CONVERT(varchar(10),@InDateTime,101) RETURN @MyOutput END To call our function, execute: SELECT dbo.DateOnly(GETDATE()) Notice the User Defined Function must be prefaced with the owner name, DBO in this case. In addition, GETDATE can be used as the input parameter, but could not be used inside the function itself. Other built in SQL functions that cannot be used inside a User Defined Function include: RAND, NEWID, @@CONNCECTIONS, @@TIMETICKS, and @@PACK_SENT. Any built in function that is non-deterministic. The statement begins by supplying a function name and input parameter list. In this case, a date time value will be passed in. The next line defines the type of data the UDF will return. Between the BEGIN and END block is the statement code. Declaring the output variable was for clarity only. This function should be shortened to: CREATE FUNCTION testDateOnly(@InDateTime datetime)

RETURNS varchar(10) AS BEGIN RETURN CONVERT(varchar(10),@InDateTime,101) END

Inline Table UDFs


These User Defined Functions return a table variable that was created by a single select statement. Almost like a simply constructed non-updatable view, but having the benefit of accepting input parameters. This next function looks all the employees in the pubs database that start with a letter that is passed in as a parameter. In Query Analyzer, enter and run: USE pubs GO CREATE FUNCTION dbo.LookByFName(@FirstLetter char(1)) RETURNS TABLE AS RETURN SELECT * FROM employee WHERE LEFT(fname, 1) = @FirstLetter To use the new function, enter: SELECT * FROM dbo.LookByFName('A') All the rows having a first name starting with A were returned.

MS SQL

May 7, 2004

User Defined Functions in Microsoft SQL Server 2000

By Don Schlichting

Multi Statement UDFs


Multi Statement User Defined Functions are very similar to Stored Procedures. They both allow complex logic to take place inside the function. There are a number of restrictions

unique to functions though. The Multi Statement UDF will always return a table variable-and only one table variable. There is no way to return multiple result sets. In addition, a User Defined Function cannot call a Stored Procedure from inside itself. They also cannot execute dynamic SQL. Remember also, that UDFs cannot use non-deterministic built in functions. So GETDATE and RAND cannot be used. Error handling is restricted. RAISERROR and @@ERROR are invalid from inside User Defined Functions. Like other programming languages, the purpose of a User Defined Function is to create a stand-alone code module to be reused over and over by the global application. For a Multi Statement test, we will create a modified version of the LookByFName function. This new function will accept the same input parameter. But rather than return a table from a simple select, a specific table will be created, and data in it will be manipulated prior to the return: CREATE FUNCTION dbo.multi_test(@FirstLetter char(1)) RETURNS @Result TABLE ( fname varchar(20), hire_date datetime, on_probation char(1) ) AS BEGIN INSERT INTO @Result (fname, hire_date) SELECT fname, hire_date FROM employee WHERE LEFT(fname, 1) = @FirstLetter UPDATE @Result SET on_probation = 'N' UPDATE @Result SET on_probation = 'Y' WHERE hire_date < '01/01/1991' RETURN END To use the new function, execute: SELECT * FROM dbo.multi_test('A')

With the new Multi Statement Function, we can manipulate data like a Stored Procedure,

but use it in statement areas like a View. For example, only specific columns can be returned. SELECT fname FROM dbo.multi_test('A')

The function can also be joined like a view: SELECT e.lname, f.fname FROM employee e INNER JOIN dbo.multi_test('A') f ON e.fname = f.fname

Conclusion
User Defined Functions offer an excellent way to work with code snippets. The main requirement is that the function be self-contained. Not being able to use non-deterministic built in functions is a problem, but if it can be worked around, UDFs will provide you with a programming plus.

Anda mungkin juga menyukai