Wednesday, April 16, 2014

Dynamic Management Views (DMV's)

The dynamic management views (DMVs) in SQL Server 2005 are designed to give you a window into what's going on inside SQL Server. They can provide information on what's currently happening inside the server as well as the objects it's storing. They are designed to be used instead of system tables and the various functions provided in SQL Server 2000. This article provides an introduction to DMVs and covers a few of the basic views and functions.

The Dynamic Management Views are actually composed of both views and table-valued functions. Some apply to the entire server and are stored in the master database. Others are specific to each database. All are stored in the sys schema. They all start with dm_ in the name. They have been broken up into twelve categories:

  • Common Language Runtime Related Dynamic Management Views
  • I/O Related Dynamic Management Views and Functions
  • Database Mirroring Related Dynamic Management Views
  • Query Notifications Related Dynamic Management Views
  • Database Related Dynamic Management Views
  • Replication Related Dynamic Management Views
  • Execution Related Dynamic Management Views and Functions
  • Service Broker Related Dynamic Management Views
  • Full-Text Search Related Dynamic Management Views
  • SQL Operating System Related Dynamic Management Views
  • Index Related Dynamic Management Views and Functions
  • Transaction Related Dynamic Management Views and Functions
This article will focus on a few of the more common views.

Sessions

We'll start by looking at a view that will give us information on each session. Selecting from sys.dm_exec_sessions is similar to running sp_who2 or selecting from sysprocesses. It lists one row per session. Remember that when you reference any of the dynamic management views or functions you'll need to qualify with the sys schema.
SELECT
 session_id,
 login_name,
 last_request_end_time,
 cpu_time
FROM
 sys.dm_exec_sessions
WHERE
 session_id >= 51
GO


session_id login_name           last_request_end_time   cpu_time
---------- -------------------- ----------------------- -----------
51         L30\billgraziano     2005-10-30 17:11:26.487 170
52         bg                   2005-10-30 17:03:33.667 190
53         L30\billgraziano     2005-10-30 16:43:26.160 30
55         bg                   2005-10-30 17:03:34.740 90
The view also returns an extra 25 columns or so but this is a good place to start. The session_id is basically the SPID that we're used to seeing. In SQL Server 2000 selecting @@SPID returned the "server process identifier" or SPID. In SQL Server 2005 selecting @@SPID returns the "session ID of the current user process". The view also returns session-specific information such as the ANSI NULL settings, reads, writes and other set-able session objects.

Connections

For those sessions that come from outside SQL Server (session_id >= 51) we can also look at the connection information. We'll query sys.dm_exec_connections for this information. This view returns one row for each connection.
SELECT
 connection_id,
 session_id,
 client_net_address,
 auth_scheme
FROM
 sys.dm_exec_connections
GO

connection_id                        session_id  client_net_address   auth_scheme
------------------------------------ ----------- -------------------- -----------
71AE7560-9366-486C-ACBF-D5405E89B6F5 51          local machine        NTLM
CAB9E608-0312-42D8-A19C-AD1D954AA427 52          192.168.8.20         SQL
7369B4B6-7199-4527-A882-215023D352EC 53          local machine        NTLM
192FFCE9-588C-49DA-9BE1-07134291BC86 55          192.168.8.20         SQL
There are about fifteen other columns but we're going to focus on these for now. Notice that the IP address of the client is listed as well as the authentication scheme. One of the things I've always wanted from SQL Server is an easy way to see the IP address for each connection.

Requests

In order to what each connection is actually doing we're going to use the sys.dm_exec_requests view. This lists each request that is executing within SQL Server.
SELECT
 session_id,
 status,
 command,
 sql_handle,
 database_id
FROM
 sys.dm_exec_requests
WHERE
 session_id >= 51 
GO

session_id status     command   sql_handle                                         database_id
---------- ---------- --------- -------------------------------------------------- -----------
54         running    SELECT    0x02000000DF1170132662EE95912DA70270B3EE0F74BCD15C 1
56         suspended  WAITFOR   0x02000000C72622210D647D6515783CD4D7140FEB7EE478B5 1
In this case there are two running queries. The first (#54) is my select from sys.dm_exec_requests. The second is another query running from a different connection. We can see that it's current running a WAITFOR command. This view has a number of other interesting columns including the start time, plan_handle (hash map of the cached query plan), wait type information, transaction information, reads, writes and connection specific settings. Let's see what we can find out about the other query that's running.

SQL Text

sys.dm_exec_sql_text is a dynamic management function that returns the text of a SQL statement given a SQL handle. Fortunately we just happen to have a SQL handle from our query of sys.dm_exec_requests. To see the SQL text that's currently executing in session #54 we can use this query:
SELECT 
 st.text
FROM
 sys.dm_exec_requests r
CROSS APPLY 
 sys.dm_exec_sql_text(sql_handle) AS st
WHERE
 r.session_id = 56
GO


text
----------------------------------------------
SELECT
 *
FROM
 TAMSDev.dbo.AuditLog

WAITFOR DELAY '00:00:10'

Notice that we used a CROSS APPLY to execute the function for each row returned by the view.

Security

In order to query these views a user needs specific permissions granted. To view the server-wide DMVs the user must be granted the VIEW SERVER STATE on the server. After running the following query as administrator

GRANT VIEW SERVER STATE to bg
I was able to query the DMVs when logged in as a regular user. To query database specific DMVs a user must be granted the VIEW DATABASE STATE permission in each specific database. If you want to deny a user permission to query certain DMVs you can use the DENY command and reference those specific views. And remember it's always better to grant permission to roles instead of individual users.

Summary

Those are some of the basic dynamic management views. In a future article I'll cover a few more of the management views that provide additional information about the server and what's in it.
- See more at: http://www.sqlteam.com/article/dynamic-management-views#sthash.2ssBo5Ja.dpuf

Friday, February 7, 2014

Pagination

There are instances when you want to display large result sets to the end user. The best way to display large result set is to split them i.e.  apply pagination. So developers had their own hacky ways of achieving pagination using “top”, “row_number” etc. But from SQL Server 2012 onwards we can do pagination by using “OFFSET” and “FETCH’ commands.
For instance let’s says we have the following customer table which has 12 records. We would like to split the records in to 6 and 6.

So doing pagination is a two-step process: -
  • First mark the start of the row by using “OFFSET” command.
  • Second specify how many rows you want to fetch by using “FETCH” command.
You can see in the below code snippet we have used “OFFSET” to mark the start of row from “0”position. A very important note order by clause is compulsory for “OFFSET” command.
select * from
tblcustomer order by customercode
offset 0 rows – start from zero
In the below code snippet we have specified we want to fetch “6” rows from the start “0”position specified in the “OFFSET”.
fetch next 6 rows only
Now if you run the above SQL you should see 6 rows.

To fetch the next 6 rows just change your “OFFSET” position. You can see in the below code snippet I have modified the offset to 6. That means the row start position will from “6”.
select * from
tblcustomer order by customercode
offset 6 rows



fetch next 6 rows only
The above code snippet displays the next “6” records , below is how the output looks.

Sequence Object in SQL Server 2012



This feature is personally feel it just mimics Oracle’s sequence objects. if Oracle has it why not SQL Server. A sequence object generates sequence of unique numeric values as per specifications. we have something similar like this called as “Identity” columns. But the big difference is sequence object is independent of a table while identity columns are attached to a table.

Below is a simple code to create a sequence object. You can see we have created a sequence object called as “MySeq” with the following specification:-

  • Starts with value 1.
  • Increments with value 1 Minimum value it should start is with zero.
  • Maximum it will go to 100. No cycle defines that once it reaches 100 it will throw an error.
  • If you want to restart it from 0 you should provide “cycle”.
  • “cache 50”  specifies that till 50 the values are already incremented in to cache to reduce IO. If you specify “no cache” it will make input output on the disk.

 

create sequence MySeq as int

               start with 1  -- Start with value 1

               increment by 1-- Increment with value 1

               minvalue 0 -- Minimum value to start is zero

               maxvalue 100 -- Maximum it can go to 100

               no cycle -- Do not go above 100

               cache 50 -- Increment 50 values in memory rather than incrementing from

IO

To increment the value we need to call the below select statement. This is one more big difference as compared to identity.In identity the values increment when rows are added here we need to make an explicit call.

SELECT NEXT VALUE FOR dbo.MySequence AS seq_no;

 Once you exceed to the MaxValue of Sequence SQL-Server throws error

Msg 11728, Level 16, State 1, Line 1

The sequence object 'TestSEQ' has reached its minimum or maximum value. Restart the sequence object to allow new values to be generated.

 Limitations and Restrictions

The NEXT VALUE FOR function cannot be used in the following situations

·         When a database is in read-only mode

·         In subqueries including common table expressions and derived tables.

·         In views, in user-defined functions, or in computed columns

·         In a statement using the DISTINCT, UNION, UNION ALL, EXCEPT or INTERSECT operator.

·         In a statement using the ORDER BY clause unless NEXT VALUE FOR … OVER (ORDER BY …) is used.

·         In a VALUES clause that is not part of an INSERT statement.

·         In a statement using TOP, OFFSET, or when the ROWCOUNT option is set.

·         In the WHERE clause of a statement.

 You can get one or more values out of the sequence object. You can also ALTER the sequence object to RESTART it, or change many of its properties

-- Restart the sequence from 1

 ALTER SEQUENCE dbo.TestSEQ

RESTART WITH 2

INCREMENT BY 2

MINVALUE 2

MAXVALUE 10

CACHE 20

NO CYCLE;

Note – Alter statement cannot have the Start Value




 

Column Store Indexes

To get the Column Index right click on the indexes folder as “Non-Clustered Column store Index” , as shown in the below figure.


So let’s quickly understand what exactly it does. Now Relational database store data “row wise”. These rows are further stored in 8 KB page size.
For instance you can see in the below figure we have table with two columns “Column1” and “Column2”. You can see how the data is stored in two pages i.e. “page1” and “page2”. “Page1” has two rows and “page2” also has two rows. Now if you want to fetch only “column1”, you have to pull records from two pages i.e. “Page1” and “Page2”, see below for the visuals.
As we have to fetch data from two pages its bit performance intensive.


If somehow we can store data column wise we can avoid fetching data from multiple pages. That’s what column store indexes do. When you create a column store index it stores same column data in the same page. You can see from the below visuals, we now need to fetch “column1” data only from one page rather than querying multiple pages.

Thursday, January 9, 2014

DML on Views


·         Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table.

·         The columns that are being modified in the view must reference the underlying data in the table columns directly. They cannot be derived in any other way, such as through:

·         An aggregate function (AVG, COUNT, SUM, MIN, MAX, GROUPING, STDEV, STDEVP, VAR and VARP).

·         A computation; the column cannot be computed from an expression using other columns. Columns formed using set operators (UNION, UNION ALL, CROSSJOIN, EXCEPT, and INTERSECT) amount to a computation and are also not updatable.

·         The columns that are being modified cannot be affected by GROUP BY, HAVING, or DISTINCT clauses.

·         TOP cannot be used anywhere in the select_statement of the view when WITH CHECK OPTION is also specified.


Schema Binding

Schema binding ties an object to the base object that this new object depends upon.  So without schema binding if a view is created and the underlying table is changed, the view may break, but the table change can still occur.  With schema binding, if the base object is bound to another object, you will not be able to modify the based object unless you drop or alter the object to remove the schema binding

So if you want to create an index on a view or you want to preserve the base table schema once a view has been defined, in both these cases you have to use the "WITH SCHEMABINDING" clause to bind the view to the schema of the base tables

you must first create a unique clustered index on the view, before you can create any non-clustered indexes.

·         You can not create an index on a view with outer joins used in it, even if you use schema binding

·         You can not use '*' in the select statement of a view when it is schema bound. In such case you will clearly get error message of level 15 as "Syntax '*' is not allowed in schema-bound objects.".

·         You will not be able to create clustered index on a view if the view references any nondeterministic functions.

·         You can not use aggregate functions when using schema binding.