bet.ucoz.co.uk

Posts Tagged ‘Tips and Tricks’

SQL Server: Locking basics November 15th, 2012

Vinod Kumar

The learning journey can never stop. As we learn the basic building blocks of SQL Server there is always a need to do refreshers. This blog is on the same lines. I would urge you to read the Blog around Concurrency over at Pinal’s site and then continue the reading below because the basics of Locking is incomplete if we don’t understand what are the concurrency basics. Just like you have traffic signals that regulates traffic to make sure there are no grid locks or long waits for commuters. The parallel lanes for traffic is synonymous to concurrency. SQL Server uses locks as an mechanism to bring the consistency at the same time build the concurrency for the system. Locks are inevitable in any database world and those are also fundamental building blocks.

  1. Locks are applied in both optimistic and pessimistic concurrency models.
  2. Locking is used for maintaining consistency for concurrent transactions.
  3. Read operations acquire shared locks, exclusive locks by write operations while update locks are got during initial portion of an update operation when SQL Server is searching for the data to update.
  4. SQL Server releases locks automatically and manages compatibility between various locking modes, resolves deadlocks and lock escalations are done to reduce overheads.
  5. SQL Server controls locks on tables, on the pages of the table, on index keys and on individual rows of data based on the operation done.

Lock Modes

  1. Shared Locks
    1. Automatically acquired while reading data.
    2. This lock can be on a page, table, index key or individual row based on the isolation level.
    3. Multiple processes can hold shared locks on the same data and read from it too.
    4. No other process can get an exclusive lock on data that has a shared lock. Neither can a process acquire a shared lock when there is an exclusive lock already on the table.
    5. Shared locks are not held for the whole duration of read in the default isolation level.
  2. Exclusive Locks
    1. This lock is acquired on data when modifications are done by DML statements like INSERT, UPDATE or DELETE operation.
    2. At any point in time exclusive locks can be held by only one process.
    3. In an exclusive locking mode no other process can take locks in this process.
    4. Exclusive locks are taken for the duration of the transaction length as the process can either commit or rollback.
  3. Update Locks
  1. This is an hybrid of exclusive and shared locks.
  2. This lock is taken when SQL Server searches the table to find the resource that needs to be modified.
  3. This can also be initiated using using query hints. It is desirable not to use the same.
  4. Even in this lock, it is not the sufficient level to change data. SQL Server must take exclusive lock to modify data.
  5. Used as an intermediate lock before escalating to exclusive locks.
  • Intent Locks
    1. As the name suggests is a pre-qualifiers to shared/update/exclusive locks.
    2. Since SQL Server can acquire locks at different levels, before the process completes or the statements completes SQL Server might want to know if locks are already acquired.
    3. This is an intermediate locking state and not to be confused as a separate locking mode.
  • Special Lock Modes
    1. Schema stability locks – at the time of compilations, this lock makes sure that no other process is modifying the schema of the underlying objects.
    2. Schema modification locks – acquired when a table’s structure is being modified.
    3. Bulk update locks – locks taken for BULK INSERT command or bcp utility operation. This lock can also be turned on using the table hints.
  • Conversion Locks
    1. As the name suggests, this lock happens during a conversion from one mode to another. There are three types SIX, SIU, UIX where SIX is the most common and the details are below.
  • Key-Range Locks
    1. Locks taken in serializable isolation level for locking ranges of data.
    2. Can be taken only on keys.
  • Let us look at the common abbreviation and locking mode descriptions:

    1. S – Shared: Allows processes to read concurrently but cannot change the resource locked.
    2. X – Exclusive: Prevents processes from modifying or reading data in the data.
    3. U – Update: Prevents external processes from acquiring an update or exclusive lock.
    4. IS – Intent shared: Acquired when resource is locked with a shared lock.
    5. IU – Intent update: Acquired when the resource is locked with an update lock.
    6. IX – Intent exclusive: Acquired when the resource is locked with an exclusive lock.
    7. SIX – Shared with intent exclusive: Shows that a shared lock pages have either a page or row with exclusive locks.
    8. SIU – Shared with intent update: Shows that a shared lock pages have either a page or row with an update lock.
    9. UIX – Update with intent exclusive: Shows that a update lock pages have either a page or row with exclusive locks.
    10. Sch-S – Schema stability: Used to show a query using the object is being compiled at that moment.
    11. Sch-M – Schema modification: Used to indicate the table’s structure is being updated at this moment.
    12. BU – Bulk update: Lock acquired when bulk copy operation (like bcp) is copying data into a table.

    Lock Granularity

    1. SQL Server can lock resources at the table, page, partition or row level.
    2. If locks are escalated, SQL Server can also lock a single partition of a table or index.
    3. SQL Server can also lock index keys and ranges of index keys if needed.
    4. DMV sys.dm_tran_locks view keeps track of each lock and contains information about the resource which is locked and an identifier for the specific resource

    Key Locks

    1. SQL Server use of key locks depends on the isolation level of the transaction.
    1. If isolation level is Read Committed, Repeatable Read or Snapshot, SQL Server locks the actual index keys accessed while processing the query.
    2. If isolation level is serializable, to counter phantoms reads, key-range locks are acquired for the range of values queried.
    3. Incase of tables with clustered index, leaf node contains the data and hence the locks are acquired at this level.
  • There are 9 types of key-range locks:
    1. RangeS-S
    2. RangeS-U
    3. RangeIn-Null
    4. RangeX-X
    5. RangeIn-S
    6. RangeIn-U
    7. RangeIn-X
    8. RangeX-S
    9. RangeX-U 

    Other Locking Assets

    1. We saw locks on objects, pages, keys, partitions and rows. Three are other SQL Server can lock too.
    2. Extents are units of 64KB disk space that can be locked. This is a special type of lock that is taken when an object needs to expand and a new extent is allocated.
    3. Generally connections hold a lock on at least one database object and will have resource_type = DATABASE at a minimum running in the session.
    4. You occasionally have locks on individual partitions, indicated in the lock metadata as HOBT locks. Occurs when locks are escalated and escalation to that partition level is allowed

    Lock Duration

    1. The length of time that a lock is held depends primarily on the mode of the lock and transaction isolation level in effect.
    2. Shared locks in Read Committed and Snapshot isolation levels are released as soon as SQL Server has read and processed the locked data
    3. Shared locks behave the same as exclusive locks in Repeatable Read and Serializable isolation levels – they are not released until the end of the transaction
    4. Update locks are also held until the end of the transaction unless it has been promoted to an exclusive lock in which case it behaves like the exclusive lock

    Lock Ownership

    1. Lock duration is directly affected by lock ownership
    2. Ownership == scope of the lock
    3. Four types of lock scopes
      1. Transactions – Durations depend on isolation level and lock mode (shared locks and update/exclusive locks)
      2. Cursors – requested explicitly when a cursor is declared. If a cursor is opened using a locking mode of SCROLL_LOCKS, a cursor lock is held on every row fetched until the next row is fetched or the cursor is closed. Even if the transaction commits before the next fetch, the cursor lock is not released
      3. Transaction_Workspaces – acquired every time a database is accessed and the resource associated with these locks is always a database. A workspace holds database locks for sessions – usually there is one workspace per session and all DATABASE locks acquired in the session are kept in the same workspace object. In distributed transactions, multiple sessions are enlisted into the same workspace so they share the database locks
      4. Sessions – must be requested explicitly using the sp_getapplock procedure, and apply only to APPLICATION locks. Its duration is until the session disconnects or the lock is released explicitly

    Thanks for reading this far. I know there is more to learn and write like Lock Timeout, Locking Hints, Version Stores, Snapshot Isolation Level, Row Versioning, Deadlocks, Lock Escalations, Row-level Locking and Page-level Locking, Lock Blocks, internal locking etc !!! I will surely keep you posted similarly in future.

    Continue reading...


     

    SQL Server: Transaction Logs and Recovery November 12th, 2012

    Vinod Kumar

    In my day-today customer interactions I meet a lot young, smart DBA’s who are still stepping into the ranks of making their applications robust. As part of their daily activities they are getting guided by some seniors who impose some of their views based on their past experience. Unfortunately, in this process the fundamentals are lost and as we build our career we need to understand the basics. One of the topics I explain almost every customer is about how Transaction Logs work, why they keep growing, how to make it cycle/reuse, what happens after backup etc. So I plan to write such posts in the future too, these are lists for reference making learning fun and easy. I am writing this post in the style of notes taken in a class, hope that will make reading easy and leaning faster :).

    Transaction Log Basics

    1. Transaction log records changes made to the database and stores enough information to allow SQL Server to recover the database.
    2. Recovery is the process of reconciling the data files and the log.
    3. Any changes to the data that the log indicates have been committed must appear in the data files and any changes that are not marked as committed must not appear in the data files
    4. Log also stores information on how to roll back transactions if a ROLLBACK TRAN is received from the client or a deadlock generates an internal ROLLBACK.
    5. One or more transaction log files are associated with a database when the database is created.
    6. Log record is labeled with a Log Sequence Number (LSN) which is guaranteed to be unique.
    7. Log entries part of the same transaction are linked so that they can be located easily for undo or redo activities.
    8. SQL Server keeps track of the current position in the log by the LSN and when a page is changed the LSN corresponding to the log entry for that change is written into the header of the data page.
    9. Dirty pages can be written to the disk only when the LSN on the page is less than or equal to the LSN for the last record written to the log.
    10. The Buffer Manager guarantees that the transaction log will be written before changes to the database are written (write-ahead logging).
    11. Buffer Manager also guarantees that log pages are written in a specific order making it clear which log blocks must be processed after a system failure regardless of when the failure occurred.
    12. Log records for a transaction are written to disk before the commit transaction is sent to the client process. Actual changed data might not have been written out to data pages yet.
    13. Though log writes are asynchronous, at commit time thread must wait for the write to complete to the point of writing the commit record in the transaction log. Data page writes are completely asynchronous.
    14. Logging involves "demarcating" the begin and end of each transaction with information about changes made to the data in between. At the end, its marked with a commit record.
    15. An aborted transaction undoes the changes made to the original data and these changes are written to the log and marked as "compensation log records".
    16. There are two types of recovery (goal for both is to make sure log and data are in sync):
      1. Restart Recovery – runs every time SQL Server is started. Runs on each database (in parallel) and the SQL Server error log tells you how many transactions were rolled forward and back. This is also called as Crash Recovery.
      2. Restore Recovery – also known as Media Recovery is run by request when a restore operation is requested via the backup route.
    17. Both the above types have to deal with 2 important situations:
      1. When transactions are recorded as committed in the log but not written to the data file.
      2. When changes to the data file don’t correspond to committed transactions. This can happen when a implicit indirect or explicit checkpoint forced this case.

    Phases of Recovery

    Now that I have set some context to the basic units of transactional logs and why they are used. We need to also understand the stages of recovery process.

    1. Phase 1: Analysis Phase – Forward pass starting at the last checkpoint record in the transaction log. Determines and constructs a Dirty Page Table (DPT) consisting of pages that might have been dirty when SQL Server stopped. Active Transactions Table is also built consisting of uncommitted transactions
    2. Phase 2: Redo Phase - Returns the database to the state it was in at the time SQL Server was stopped. Starting point for this forward pass is the start of the oldest uncommitted transaction. The minimum LSN in the DPT is the first page that is expected to be redone. But all logged operations starting at the oldest open transaction need to be redone for necessary locks to be acquired
    3. Phase 3: Undo Phase – Uses the list of Active Transactions found in Phase 1 to roll each transaction back individually. Any transaction that was not committed is undone
    4. Fast Recovery Phase – available in Enterprise and Developer edition allows for a database to be online as soon as redo phase is finished

    Page LSNs and Recovery

    1. Every database page has a LSN in the page header that reflects the location in the transaction log of the last log entry that modified a row on this page.
    2. Also keeps track of the LSN which was on the data page before the change recorded by the latest log record.
    3. During redo, LSN of each log record is compared to the LSN of the data page that the log entry modified.
      1. If it’s equal to the previous page LSN in the log record, the operation indicated in the log entry is redone.
      2. If it’s equal or higher than the actual LSN for the log record, REDO operation is skipped.
    4. A transaction log cannot be truncated prior to the point of the earliest transaction that is still open, no matter how many checkpoints have occurred.

    Virtual Log Files

    1. A transaction log for any database is maintained as a set of virtual log files (VLFs) who size is determined internally by SQL Server by the total size of all the log files and the growth increment used when enlarging the log.
    2. Log file is grown in units of entire VLFs and be shrunk only to a VLF boundary:
      1. When a log file is first created it always has between 2 and 16 VLFs.
      2. If its 1 MB or less – log file size is divided by minimum VLF size 31 * 8KB to determine number of VLFs.
      3. If its between 1 and 64 MB – log is split into 4 VLFs.
      4. If greater than 64 MB but less than 1 GB 8 VLFs are created.
      5. If greater than 1 GB, 16 VLFs are created.

        The above rules of thumb can be different depending on the version of SQL Server you are working.

    3. 4 states for a VLF:
      1. Active – active portion of the log begins at the minimum LSN representing an active transaction. The active portion of the log ends at the last LSN written
      2. Recoverable – portion of the log preceding the oldest active transaction is needed only to maintain a sequence of log backups for restoring the database to a former state
      3. Reusable – If transaction log backups are not being maintained or if log was already backed up, VLFs before the oldest active transaction are not needed and can be reused
      4. Unused – One or more VLFs at the physical end of the log files might not have been used yet if not enough log activity has taken place. Or if earlier VLFs have been marked as reusable and then reused
    4. Automatic Truncation – understand when the Log backups are not existent:
      1. You have configured the database to truncate a log on a regular basis by setting the recovery model to SIMPLE.
      2. You have never taken a full database backup.
      3. All log records prior to the oldest active transaction are invalidated and all VLFs not containing any part of the active log are marked as reusable. This process doesn’t shrink the physical file it is used in a cyclic manner.
    5. Automatic Shrinkage – A database is truncated to allow for shrinking. If autotruncate and autoshrink option is set, the log is physically shrunk at regular intervals. This is something not recommended, though this option exists.

    Database Recovery Models

    As we learn about transaction logs, we cannot miss understanding the recovery models and the effects of the same. There are 3 modes of recovery models:

    1. FULL Recovery Model
      1. Provides the least risk of losing work in case of a damaged data file.
      2. All operations are fully logged – in addition to logging every row changed via DML, the entire row is written to the transaction log using BCP or BULK INSERT operation.
      3. Also fully logs CREATE INDEX operations.
      4. Use this if you need to recover to a Point-in-time from your backup.
    2. BULK_LOGGED Recovery Model
      1. Allows you to restore a database completely in case of media failure and gives the best performance and least log space usage for certain bulk operation.
      2. Minimal logging compared to FULL recovery model.
      3. Minimal logging consists of logging information that is required to roll back the transaction without supporting point-in-time recovery.
      4. Every data file in SQL has a special page called Bulk Changed Map (BCM) page also called Minimally Logged Map (ML Map) page. Each bit on a BCM page represents an extent and if the bit is 1 it means that this extent has been changed by a minimally logged bulk operation since the last transaction log backup.
      5. BCM map is located on page 7 of a 4GB span and all the bits are reset to 0 every time a log backup occurs.
    3. SIMPLE Recovery Model
      1. Offers the simplest backup and restore strategy.
      2. Transaction log is truncated whenever a checkpoint occurs (which happens regularly).
      3. Only backups that can be made are ones that don’t require log backups.

    Choosing the right recovery model is very important for functioning of your databases.

    Backing Up and Restoring a Database

    SQL Server has four main types of backups:

    1. Full Backup – Copies all pages from a database onto a backup device.
    2. Differential Backup – Copies only the extents that were changed since the last full backup was made. Done by examining the bits on the DCM pages for each data file in the database. When any page in an extent is changed, the corresponding bit in the DCM page is set to 1
    3. Log Backup – Copies all the log records that have been written to the transaction log since the last full or log backup was made
    4. File and Filegroup Backup – these backups are intended to increase flexibility in scheduling and media handling compared to full backups, in particular for very large databases. Useful when database contains varying update characteristics or priority levels

    Thanks for reading this far. Hope the basics are clear now. Given these pointers, feel free to explore more into MSDN documentation.

    Continue reading...


     

    SQL DBA Checklist November 8th, 2012

    Vinod Kumar

    Long time back I did write about what activities constitute a DBA role and as I start meeting more DBA in my day job – I get asked, is there any checklist? If you really ask me, that article does call out most of the points. Here is just yet another list. Feel free to add more to this list -

    As a DBA we work to keep the systems up and running for the business, hence there are business requirements we need to be aware off like below – know the answers to the below and ask your respective stakeholders before designing the system:

    1. Establish specific SLAs (service level agreements) with stakeholders
    2. What Availability do they want? (aka  find our your maintenance windows)
    3. RPO (recovery point objectives – how much you can afford to lose if DR / corruption occurs)
    4. RTO (recovery time objective – how long to bring database/system back up after DR/Corruption)
    5. Points of contact (owners) for the various databases. This is true in consolidation environments. People change roles or switch jobs – keep this uptodate always.
    6. Change control – how often, who has what rights to DB, what auditing is in place etc. – especially important for shared instances
    7. Response times & escalation procedures (how soon you will do changes if you do them for the customer, how soon you respond when problems arise – are you a 24×6, 24×7, 7×12, 5×10 shop,  do you have people on call, how do they reach on call person, etc.)
    8. Based on the responses, make your backup strategy based on this because the RTO, RPO will be something decided by this strategy.
    9. Know the immediate or near future plans of the organization to support newer versions. Plan on a upgrade or migration strategy before hand and know the nuances. Check my previous post on Upgrading to SQL Server 2012.
    10. Know your various contact points from an Hardware perspective – SAN vendor, Software vendors, Network switch vendors, Network Admins and the various access mechanisms to reach the server. Document them and keep them handy always.

    Other lists include:

    1. Test your disaster recovery plan by a junior DBA to check if you have missed any steps.
    2. Pre-grow your databases to cover the projections for the next year
    3. Pre-size the tempDB to its regular maximum size.
    4. Check that security is still tight – people who have left the group/company no longer have logins, no new logins have snuck into highly privileged groups, etc.
    5. Check all your logs thoroughly for abnormality.
    6. If you’re not yet using Policy Based Management, double check that all your configuration settings are still correct.
    7. Take new performance baselines to track if the system is performing better compared to a baseline.
    8. Resync your test and development systems with production or production like data
    9. Implement some of those cool new techniques, functionality, tips, etc. you learned at your last conference. Always look at implementing new efficient methods of code.
    10. Ask your hardware admins to do low level hardware diagnostics
    11. Install MOM/SCOM agents (or at least some other monitoring / alerting tool).
    12. At the very least configure SQL (SMTP) Mail and Operator alerts for job failures.
    13. Ensure you have maintenance plans for re-indexing/defragging  and updating statistics.
    14. Configure your maintenance plans to pick up new databases automatically or write your own scripts to detect and configure new plans (in the process of writing some now).
    15. Add a job to recycle the error log every night to keep logs small.
    16. Keep an script handy for any non-compliance and keep running them time-to-time on the environment.
    17. Test your disaster recovery plan again!!

    Additionally I might do things on a daily basis and quarterly basis like, some tasks done daily are:

    1. Monitor and Check for blocking spids
    2. Monitor and check for deadlocks
    3. Monitor and check status of SQLAgent jobs
    4. Monitor disk growth (especially processes that might be eating up transaction log-space).
    5. Monitor for rogue, ad-hoc queries that might be running against your production systems (and take appropriate, punitive action).
    6. Check if there are Login Errors or any suspicious activity on the logs.

    Maybe quarterly I might do:

    1. Collect database and table growth history (at least once per week), then review growth rate every quarter.  Compare the actual growth rate against expected growth rate from the TECH spec  (DEV should always provide estimated growth rates in either the tech spec or deployment plan!)
    2. Create a simple SQL Profile trace that you can run as a SQLAgent job that collects samples of durations of the most critical stored procs and queries in the system.   Just like the growth rates above, compare the actual durations against expectations in the tech spec…   Also, look for concerning performance degradation over time.
    3. Collect blocking history and review trends quarterly
    4. Collect deadlock history and review trends quarterly
    5. Check who has access to the database regularly
    6. Keep looking at the organizations operational guides and see if there needs to be changes because of upgrades or if the behavior changed in the next releases.
    7. Check once in a while if the tapes and backups are uptodate and functional. This can be randomly done during the quarter.

    I am sure I am missing some of the vital points you are doing in your environment. So please feel free to add it over comments and I will be more than happy to merge them.

    Continue reading...


     

    Let go and move forward November 5th, 2012

    Vinod Kumar

    Courage is the power to let go of the familiar – Raymond Lindquist

    Life is about challenges, interesting twists and there is a strong hold we have to certain things. These holds can be because of 100 other reasons like our egos, emotions, love, passion, comfort etc. The list why we keep doing the way we do is numerous, but if we take a small step back and analyze within there are lots we can live without. In this blog post I am calling few of these from my experience that I feel we all need to let-go to move forward in life.

    1. Past failures are not shame

    A lot of us hold on to the failures of past – understand that the past is not predicting that your future will also be that way. If that is the case, then you have not learnt from the past failures or you are making the same conscious choice. Sometimes stop thinking about the past and think what you are doing right now and move forward.

    2. Others don’t control your life

    I did talk about this in my previous picture post around opinions. Stop letting the opinions of others decide what you do in your life today. What matters these days is what you feel about yourself that counts and not what others think of you. Understand that you have to do exactly what is best for you and your life not what is best for everyone else.

    3. Stop procrastinating ON your goals

    There is an old saying that the best time to plant a tree was 20 years back. If that is the case, the best time to live your dreams and pursue your goals is NOW. Stop procrastinating – period !!! There are two sides to the coin – accept what condition exists or take control with responsibility to change the situation in hand.

    Letting go doesn’t mean giving up, but rather accepting that there are things that cannot be – Anon

    4. Your right to be wrong 

    You don’t get a chance to choose how you are going to die or when. You can only decide how you are going to live right now. So every day is a new chance to choose and that choice is yours. Worst-case, never give up your right to be wrong. The experience that you will get from these decisions will make you move forward in life and become a better person.

    5. Running away is not solving 

    This is one big suggestion I give to almost anyone who comes to me. Stop running away from your problems. Face the issues, fix the problems, forgive, appreciate and communicate with the people who deserve it. Walk the fears you have and become a wise person.

    6. Make your decisions 

    Stop making excuses, stand up and be ready to say – “Yes, I screwed up”. Most of the long term failures are made because of indecisions & excuses and not by the decisions made at that moment. Don’t try to paralyze yourself by over-analyzing – take a decision now and move forward. There are always times you can make appropriate course corrections if needed.

    7. Appreciate your moments 

    We all tend to be so much far sighted that we forget the moments that is in front of us. A classic example, we are running behind planning our children’s future and forgetting the need to appreciate your present moment when they are growing up, they started walking, they started bicycling, made their first drawing etc. Quite often we try to accomplish something big without realizing that the greatest part of life is made up of the little things.

    Some think it’s holding on that makes one strong; sometimes it’s letting go – Sylvia Robinson

    Thanks for reading this far. There are surely things you strongly believe we need to let-go and I am all ears to listen to your views.

    Continue reading...


     

    SQL Server Script: When were Statistics last updated October 30th, 2012

    Vinod Kumar

    At my job I often help customers with Performance tuning their SQL Server environments and their application. One of the common recommendation we give is to check their maintenance plans and see if the Statistics of tables are up-to-date. This is a very common exercise and given that you have 1000s of tables to monitor, you might want an easy script to figure out which are those tables / indexes that need attention. I am giving a simple script that we use at our environments to identify the same.

    SELECT 
    OBJECT_NAME(ind.object_id) AS ‘Table Name’, 
    ind.name AS ‘Index Name’, 
    STATS_DATE(ind.object_id, ind.index_id) AS ‘Statistics Date’
    FROM  sys.indexes ind
    WHERE OBJECTPROPERTY(object_id,‘IsMSShipped’)=0
    ORDER BY 3 DESC

    With the above script the output would be as below:

    image

    Look at the “Statistics Date” column and this gives you information of how dated the statistics are. Once you have figured out the statistics are out-of-date by few weeks or months, use the UPDATE STATISTICS command to update the same. Yet another command used for this purpose is sp_updatestats.

    Also, even if you have AUTO_CREATE_STATISTICS, AUTO_UPDATE_STATISTICS and AUTO_UPDATE_STATISTICS_ASYNC (Statistics documentation) options enabled inside your database Statistics *can* be out-of-date. So analyze your environments from time-to-time and then come up with your updating strategy.

    Continue reading...


     

    SQL Server: How to find mapping of tables with filegroups October 29th, 2012

    Vinod Kumar

    One of the recommendations I give to customers coming to MTC is to do proper placement of tables to appropriate filegroups. The default behavior is – SQL Server would create a default PRIMARY filegroup and all the data would be placed into the .mdf file. And this is something I have seen at a lot of ISV’s forget to work on and configure.

    Recently, when this recommendation was given, one of the DBA did ask me – “How do we know which table is in which filegroup? Is there an instant script for the same?”. Well, there are a number of ways to find this information and I am attaching the same for reference here.

    Method 1: sp_help

    The simplest and the old technique is to use our proven sp_help. The last result set has the filegroup this table dbo.t1 is associated with.

    sp_help ‘[dbo].[t1]‘
    go 

    A typical output looks like below:

    image

    Method 2: sp_objectfilegroup

    The limitation of the method 1 is that it gives in different result set and it is difficult to take this information for future use. Here is an undocumented procedure which can get you this information.

    DECLARE @ObjectID INT = (Object_id(‘[dbo].[t1]‘))
    EXEC sys.sp_objectfilegroup @ObjectID
    go 

    The output for the above call is:

    image

    Method 3: DMV’s

    Since SQL Server 2005 we have DMVs that give us important information and interesting insights that we are not aware off. And this information is also hidden inside few DMVs like the query below.

    SELECT d.name AS Data_located_on_filegroup
    FROM   sys.data_spaces d
    WHERE  EXISTS (SELECT 1
                   FROM   sys.indexes i
                   WHERE  i.object_id = OBJECT_ID(‘[dbo].[t1]‘)
                          AND i.index_id <= 1
                          AND d.data_space_id = i.data_space_id)

    GO 

    The output of this query would look like:

    image

    A small extension to the same query can be made in such a way that we can get all the tables and the filegroups these tables are mapped to. So feel free to use the same.

    SELECT OBJECT_NAME (a.object_id) AS ObjectName,
           (SELECT name
            FROM   sys.data_spaces
            WHERE  data_space_id = a.data_space_id) AS FileGroupName
    FROM   sys.indexes a
    WHERE  index_id <= 1 

    I just ran this on my AdventureWorks2012 DB to get the output as below.

    image

    Thanks for reading so far. Hope this query will help you plan placing your tables in the right filegroups.

    Continue reading...


     

    SQL Server Script: Finding past connectivity issues October 25th, 2012

    Vinod Kumar

    In my day job I meet a lot of DBA’s who try to send some really interesting requirements. Recently, one of these proactive customer wanted to know if there were any past errors that they can query from the DMVs about connectivity issues. This was interesting and I had sent them the below script for use.

    SELECT
    CONVERT (VARCHAR(30), Getdate(), 121)
    AS [Run_Time],
    Dateadd (ms, ( ORB.[timestamp] - OSI.ms_ticks ), Getdate())
    AS Time_Stamp,
    Cast(record AS
    XML).value(‘(//Record/ConnectivityTraceRecord/RecordType)[1]‘, ‘varchar(50)’) AS [Action],
    Cast(record AS
    XML).value(‘(//Record/ConnectivityTraceRecord/RecordSource)[1]‘, ‘varchar(50)’) AS [Source],
    Cast(record AS XML).value(‘(//Record/ConnectivityTraceRecord/Spid)[1]‘,‘int’) AS [SPID],
    Cast(record AS
    XML).value(‘(//Record/ConnectivityTraceRecord/RemoteHost)[1]‘, ‘varchar(100)’) AS [RemoteHost],
    Cast(record AS
    XML).value(‘(//Record/ConnectivityTraceRecord/RemotePort)[1]‘, ‘varchar(25)’) AS [RemotePort],
    Cast(record AS
    XML).value(‘(//Record/ConnectivityTraceRecord/LocalPort)[1]‘, ‘varchar(25)’) AS [LocalPort],
    Cast(record AS
    XML).value(‘(//Record/ConnectivityTraceRecord/TdsDisconnectFlags/PhysicalConnectionIsKilled)[1]‘, ‘int’) AS [isPhysicalConnectionIsKilled],
    Cast(record AS
    XML).value(‘(//Record/ConnectivityTraceRecord/TdsDisconnectFlags/DisconnectDueToReadError)[1]‘, ‘int’) AS [isDisconnectDueToReadError],
    Cast(record AS
    XML).value(‘(//Record/ConnectivityTraceRecord/TdsDisconnectFlags/NetworkErrorFoundInInputStream)[1]‘, ‘int’) AS [isNetworkErrorFound],
    Cast(record AS
    XML).value(‘(//Record/ConnectivityTraceRecord/TdsDisconnectFlags/ErrorFoundBeforeLogin)[1]‘, ‘int’) AS [isErrorBeforeLogin],
    Cast(record AS
    XML).value(‘(//Record/ConnectivityTraceRecord/TdsDisconnectFlags/SessionIsKilled)[1]‘, ‘int’) AS [isSessionKilled],
    Cast(record AS
    XML).value(‘(//Record/ConnectivityTraceRecord/TdsDisconnectFlags/NormalDisconnect)[1]‘, ‘int’) AS [isNormalDisconnect],
    Cast(record AS
    XML).value(‘(//Record/ConnectivityTraceRecord/TdsDisconnectFlags/NormalLogout)[1]‘, ‘int’) AS [isNormalLogout],
    Cast(record AS XML).value(‘(//Record/@id)[1]‘, ‘bigint’)
    AS [Record_Id],
    Cast(record AS XML).value(‘(//Record/@type)[1]‘, ‘varchar(30)’) AS [Type],
    Cast(record AS XML).value(‘(//Record/@time)[1]‘, ‘bigint’)
    AS [Record_Time]
    FROM   sys.dm_os_ring_buffers ORB
    CROSS JOIN sys.dm_os_sys_info OSI
    WHERE  ORB.ring_buffer_type = ‘RING_BUFFER_CONNECTIVITY’
    AND Cast(record AS XML).value (‘(//Record/ConnectivityTraceRecord/Spid)[1]‘, ‘int’) <> 0
    ORDER  BY ORB.timestamp ASC 

    There are so many interesting hidden information that is available inside a DMV that we miss to visualize. If you want, we can also look into why the connection got lost or why it didn’t go through.

    image

    If you want to be a proactive DBA then using the DMV can be tricky as the values can be lost in a restart of the instance. But using other mechanisms will also help -

    1. Use default logging of Invalid Logins.
    2. Use SQL Server Auditing to track Failed Logins

    Being proactive DBA is a challenge and we need to use every trick inside SQL Server to achieve our requirements. Hope you found the script useful.

    Continue reading...


     

    SQL Server 2012: Offline Documentation October 24th, 2012

    Vinod Kumar

    With the installation of SQL Server 2012, a lot of people ask how to get the documentation offline. Every time we fire the F1 for help it tries to connect online for content. This is not always useful and people want to have an offline version when they are on the move and getting online is not an option. Just initialize the Help library Manager from the SSMS Tools –> Help –> Manage Help Settings. Select the Install from Online.

    image

    Select SQL Server 2012 and Add the Books Online + Developer reference and Select Update.

    image

    Another way to get the same as an offline version is to download it from the Download Center. “Product Documentation for Microsoft SQL Server 2012 for firewall and proxy restricted environments”. Please keep checking the Download Center for the latest update for the documentation.

    Continue reading...


     

    SQL Server 2012: Finding Sequence of backup taken October 22nd, 2012

    Vinod Kumar

    Recently I had a customer come over for a session on designing their HA/DR strategy and one of the steps for that was to understand the backup strategy too. I took sometime to talk at length what FULL Backup, Differential Backup and Transaction Log Backups. After understanding the core concepts one of the developer asked me, “Is there a way I can know in what sequence the current backups are taken? This will help me re-visit the current process done by my networking team”. Interestingly, a lot of people fail to understand how Page level restore needs to be done.

    This was an interesting question and needed a little digging into the MSDB database which has most of the information. The below query will give you a list of backups and feel free to check the same in your environments. This also works in any of the SQL Server versions.

    SELECT s.database_name,
           m.physical_device_name,
           s.backup_start_date,
           CASE s.[type]
             WHEN ‘D’ THEN ‘Full’
             WHEN ‘I’ THEN ‘Differential’
             WHEN ‘L’ THEN ‘Transaction Log’
           END AS BackupType,
           s.recovery_model
    FROM   msdb.dbo.backupset s
    INNER JOIN msdb.dbo.backupmediafamily m
    ON s.media_set_id = m.media_set_id
    ORDER  BY database_name,
              backup_start_date,
              backup_finish_date 

    A typical output looks like below:

    image

    All these information are great stuff and the best part starts when we use the same for RESTORE. The UI for example will show interesting information which I was pleasantly surprised.

    image

    There are two things that stand out in the above dialog -

    1. The header shows we need to take the tail of the log backup for the restore. This is an awesome step which a lot of DBA forget in their restore process.
    2. The Backup Step shows what you will be restoring and in what sequence. This is also a pre-requisite for any restore stage.

    On initializing the Filegroup restore dialog I can see ALL the Backups taken for the restore step and this is also handy if you are planning to restore any corrupt files.

    image

    Hope you find these improvements useful and the scripts handy. In future posts, let me take a shot in showing what all can be done with these backups.

    Continue reading...


     

    Perils of Social Networking October 17th, 2012

    Vinod Kumar

    If content is king, then conversion is queen – John Munsell, CEO of Bizzuka

    The concept of Social networking has been used in an abusive manner these days. We hardly get to understand, appreciate and efficiently use the same in our day-to-day life. Strange is this generation where we mean Social Networking synonymous to the online involvement via our favorite sites of Facebook, LinkedIn, Twitter, G+ etc. But the fundamental rules of social networking is understanding the social structure from which this got evolved. Under the Web 2.0 website categorization, if the user is able to interact with others and create content that can change based on user then that is a form of social networking. In this categorization, even the blogs, WIKIs that we write can be interesting social networking site in some way.

    There are pros and cons in this so called Social Networking and in this blog let me take a stab at demystifying some of the problems of such sites. This is super-critical because I am sure the next generation will become a victim of these pitfalls.

    It’s all about people. It’s about networking and being nice to people and not burning any bridges – Mike Davidson

    How we use social sites?

    There are obviously two schools of thought when it comes to social networking. This divide among people is what feeds information into the online avatars. There are people who use the sites for personal purposes only and target to share their baby pictures to keep in touch with the friends and families. This is a great use of sites like Facebook. There are another set of people who use this for professional reasons only and have a vast ocean of people to interact with. This is also another usecase, unfortunately both these styles of interaction rubbing onto each other is where the problem starts.

    Family Oriented

    This is one set of group that I have seen grown in large numbers. There are a number of people who have their jobs away from their native (spanning across continents) and they see that Facebook has been a great way to keep in touch with family and share their wonderful moments. These days we do see housewives, great-grand mothers all able to see their grand kids in the comfort of their home. Not to forget the advent of smartphones, now sharing with loved ones is just a click away. With these intentions, this group is averse to any professional marketing one might do. I see a merit here in this model and that is the human factor !!!

    Focus on how to be social, not on how to do social - Jay Baer, Convince & Convert

    Professionally Oriented

    This is the second breed of people that we will see filled with marketing and business nerds who want to use the connects into market shares and using social to promote and break the traditional rules of market. The presence of such people are growing leaps & bounds and are comparable comparable to any corporate in the real world. These folks are strictly behind the promotions they can generate via the channel and are slowly getting away from the conventional billboards they were used to. Though there are this group, they are also cognizant of the fact that too much of anything is also not going to gain any market share or accelerate any sales.

    Wikis and social networking are just tools. – Jimmy Wales

    Nowhere to go – I am stuck in middle

    Let us also take a moment to realize that there are obviously people who walk the think line of family and professionalism on the same social site. These are people who have an identity and yet want to add the human element just like anyone else out there. In this state, many fail to transition gracefully from personal life to professional life and vice-versa when handling the social sites.

    This is not a situation anyone wants to be in. Don’t try to write about professional content in the first post and follow up with a post at a party last night. This surely confuses people keeping this identities separate can also help. I have seen some have just a profile for connecting with family separate from the other list.

    An acquaintance who you made as a friend can see this in two forms: First feeling can be “I am getting spammed by all these personal stuff when I am here to connect professionally” or it can be “I maybe stepping onto the personal space of an individual who I don’t quite care”. Both these behaviors are common and how many times do we see people not want to see ALL posts from a single person but selective based on the interest.

    For example, last thing I would want to share with my parents and grandparents is about some Garbage Collector article which they have no interest on and they have a different definition meaning for that :).

    Impact of Social Networking

    I do have accounts in various networking sites and have my own views on some on reading and writing my own updates. I enjoy doing them but let me tell you that all these so-called social networking are not creating a positive impact on our lives but have a negative influence that we forget to recognize. Let me bring some of the perspectives in this blog post next:

    Friendship

    The concept of friends have changed in the past 15-20 years. Friendship used to be really simple and we recognized that friendship to someone we knew, hung around with and liked the company they gave us – that was simple friendship. That description of people are still one of my dearest friends and I cherish their company even today. Even though there are many who live miles apart, chat or talk once in a while – the definition of friendship will never change with them.

    Now talking about how friendship is defined in social sites, I personally feel this has abused word and lost its sanity. Having several thousands of friends or followers doesn’t really mean anything in my opinion. I just hope the next generation does not get clouded by these sites and forgets the meaning of friendship, relationships and casual acquaintances.

    For example, heights of getting social: Husband and Wife greeting each other on their anniversary day over Facebook. How extreme can you become?

    Life no more fun

    With all these sharing from others, there are sections of people who suddenly find themselves wondering why their life isn’t so much of fun. This social addiction can set you back and into a depressing mood as you question why you are still stuck where you are. Don’t buckle into this social depression as I call it.

    For example, someone puts up a status of “I am screwed”. And now there are close to 100+ comments or tweets around that. Now if you are having such conversations you are surely screwed at work – I can guarantee you that !!

    Generally, social networking sites can be hugely promising and beneficial in opening new friendships and vistas and knowledge of the world, but they are also fraught with peril, when young people are reckless or headless – Richard Blumenthal

    Comment or confront?

    Earlier I wrote a post asking “Are you the same person online?” I have seen this is fundamental where people are lesser sensitive and comfortable to comment on your post rather than walk over the corridor to pass a comment. How many times do you feel comfortable in complimenting someone in-person rather easier to just say good luck over as comments. Sometimes the odd insensitive comments are also reasons for people fighting and blocking others.

    Friends reduced to likes

    Social sites are fundamentally about you. What you like, what you share, what are your interests and what are you doing. For people who are shy in sharing this are unlikely to be active on Facebook or twitter. They are a miserable failure and above all are hardly interacted. In my opinion those who try to update their status once in a bluemoon are miserable failure for me. It is better for them to deactivate their account :).

    This self-centered attention seeking perspective is something the younger generation relishes like anything. It is good and bad in my opinion. I know many who sometimes call to ask if we have seen their photographs and why we didn’t like them. This gives social pressure and sometimes rejections to why am I forced under the like banner. Social sites are better served if used for conversation and sharing unique ideas, not measured on the number of likes someone gets. I hope people realize this.

    Privacy is dead, and social media hold the smoking gun.” – Pete Cashmore, Mashable CEO

    Reduced Attention span

    Since the advent of mobile phone our dependency on remembering our home phone numbers have gone and I know many struggle too. In the same manner, after the internet era people have resorted to search engines to get what they want. Interestingly enough this has also made our mind to flirt all over the place. Just remember the last time you wanted to learn something over the internet and you somehow drifted to 10 other sites and ultimately forgot what you were searching for? Did this happen to you?

    Now from the social sites perspective, it is a stream of information overload and it switches context almost every other post and we are the main victim of this behavior. It is because of this reason why twitter or Facebook have given a limit of 140 or 250 characters. It surely is a testimony that we have lost this game and the battle of the minds.

    For example, when was the last time you had gone to a dinner with family & friends and invariably browsing or checking your status / mails at the dinner table? If you have made time for them, it is worth taking that extra attention for them. Better, switch off your phones if you can. Smart phones are surely making us dumb not smarter.

    You can run but not hide

    This is really a chicken-and-egg situation. Sometimes when you mix out both personal and professional life in one place, there are situations you want to hide away from work yet want to share all this with your loved ones. In this situation, there are problems and you tend to not be yourself because you become conscious of where and what you are doing.

    For example, have read a number of articles where Facebook check-in has lead to divorces and at times to even people taking their life away. This social obsession and not handling it proper has its big disadvantage.

    Don’t say anything online that you wouldn’t want plastered on a billboard with your face on it – Erin Bury, Sprouter community manager

    Hampers Productivity

    This is completely a no-brainer in my opinion. I did make a Picture Post on this very topic earlier this week. With reduced attention span it is really hard to stay focused and be on track with all the social media updates and notifications.

    I am not saying these social sites are the only attention seekers but there are the Angry birds and worst the addicts of farmville that are a killer and great distractions to productivity.

    Miss-information

    This comes from a old school of thought and still holds good. Rumors spread like wild fire and social sites are no exception to this. On the contrary, it is also a great way to pass-on information but many times we have seen people just share information which are not properly researched and hence creating a ripple effect.

    If you’re looking for the next big thing, and you’re looking where everyone else is, you’re looking in the wrong place Mark Cuban, owner of the Dallas Mavericks

    Career Limiting :)

    I have known people have two different life – one as they are with family& friends and other when they are at work. I have seen these days that organization’s HR ping and check your social sites to check what type of person you are before actually taking the plunge. LinkedIn is a great start but be cognizant of what you express over your Facebook and Twitter in public. It can surely become a career limiting move for the future. I do understand you have visibility settings, privacy etc but doing the right things is better.

    Not as bad as it looks

    Though I am highlighting a number of shortcomings, the situation doesn’t need to be this alarming. My intentions were to give you a glimpse of things we might keep in mind for the future.

    Social sites do have some positive effects on our daily lives too. It needs to be seen as a new way to communicate with people we cannot meet because of distance. Another neat thing about this is the ability to interact with each other and share ideas. Such interactions can be fun and a great way to learn from others in a casual manner.

    Social Networking that matters is helping people archive their goals. Doing it reliably and repeatability so that over time people have an interest in helping you achieve your goals – Seth Godin, Seth’s Blog

    Social networking is not limited to casual interactions but for people concerned about their career this can be a serious business. The more popularity you get in the corporate social circles, you are building a professional brand and making contact for a future move.

    Use social sites with tact and build a good reputation for yourself. You need to have your own identity, being yourself helps and most importantly share your views and just not parrot not what others are saying.

    Look at the social sites to connect with people than just building social interactions. Social networking is not “Real social” so don’t try to over do. Like, if it is your best friends B’day – pick the phone and wish him/her personally. This is can be really go a long way and make the other persons day. That would truly becoming social :).

    Final thoughts

    As I sign off bringing my views of social networking, I am not advocating against it. I am trying to bring the elements that can make us non-social via these sites. Evaluate your strategy of being yourself in social sites, what you do, how you interact, what you share, what you say etc. Don’t become Facebook or Twitter depressed. There is also life outside of it. Thanks for reading this far, would love to hear from you too.

    Neither privacy nor publicity is dead, but technology will continue to make a mess of both Danah Boyd, fellow at Harvard University

    Continue reading...