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
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.
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.
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.
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.
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
A. We handle around 60 servers of which 30 are Production Databases and rest are development and test boxes.
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.
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
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.
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.
(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
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
See Also
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?
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.
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: 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 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.
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
Types of T-SQL:
Data types User defined temporary objects Specialized functions global variables System and extended procedures Cursors
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
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'.
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
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.
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
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
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.
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.
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
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
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
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
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
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.
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.
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
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.
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
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
@@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.
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.
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
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.
2.Encryption:Encryption and key management build in. 3.High Availability:Clustering, Database Mirroring or Log Shipping available in Standard Edition.
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
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?
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
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
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
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
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?
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
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.
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'
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
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.
joins. In addition, User Defined Functions are simpler to invoke than Stored Procedures from inside another SQL statement.
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)
MS SQL
May 7, 2004
By Don Schlichting
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.